blob: 7c73c17df8bbdcc0b1b42bb4592392ac2869a9a6 [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
Fariborz Jahanian66c93f42012-09-06 16:43:18 +000069static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
70 // Warn if this is used but marked unused.
71 if (D->hasAttr<UnusedAttr>()) {
Fariborz Jahanian979780f2012-09-06 18:38:58 +000072 const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
Fariborz Jahanian66c93f42012-09-06 16:43:18 +000073 if (!DC->hasAttr<UnusedAttr>())
74 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
75 }
76}
77
Ted Kremenek6eb25622012-02-10 02:45:47 +000078static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000079 NamedDecl *D, SourceLocation Loc,
80 const ObjCInterfaceDecl *UnknownObjCClass) {
81 // See if this declaration is unavailable or deprecated.
82 std::string Message;
83 AvailabilityResult Result = D->getAvailability(&Message);
Fariborz Jahanian25d09c22011-11-28 19:45:58 +000084 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
85 if (Result == AR_Available) {
86 const DeclContext *DC = ECD->getDeclContext();
87 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
88 Result = TheEnumDecl->getAvailability(&Message);
89 }
Fariborz Jahanian974c9482012-09-21 20:46:37 +000090 const ObjCPropertyDecl *ObjCPDecl = 0;
91 if (Result == AR_Deprecated || Result == AR_Unavailable)
92 if (ObjCPropertyDecl *ND = S.PropertyIfSetterOrGetter(D)) {
93 AvailabilityResult PDeclResult = ND->getAvailability(0);
94 if (PDeclResult == Result)
95 ObjCPDecl = ND;
96 }
Fariborz Jahanian25d09c22011-11-28 19:45:58 +000097
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000098 switch (Result) {
99 case AR_Available:
100 case AR_NotYetIntroduced:
101 break;
102
103 case AR_Deprecated:
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000104 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl);
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000105 break;
106
107 case AR_Unavailable:
Ted Kremenek6eb25622012-02-10 02:45:47 +0000108 if (S.getCurContextAvailability() != AR_Unavailable) {
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000109 if (Message.empty()) {
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000110 if (!UnknownObjCClass) {
Ted Kremenek6eb25622012-02-10 02:45:47 +0000111 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000112 if (ObjCPDecl)
113 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
114 << ObjCPDecl->getDeclName() << 1;
115 }
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000116 else
Ted Kremenek6eb25622012-02-10 02:45:47 +0000117 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000118 << D->getDeclName();
119 }
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000120 else
Ted Kremenek6eb25622012-02-10 02:45:47 +0000121 S.Diag(Loc, diag::err_unavailable_message)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000122 << D->getDeclName() << Message;
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000123 S.Diag(D->getLocation(), diag::note_unavailable_here)
124 << isa<FunctionDecl>(D) << false;
125 if (ObjCPDecl)
126 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
127 << ObjCPDecl->getDeclName() << 1;
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000128 }
129 break;
130 }
131 return Result;
132}
133
Richard Smith852265f2012-03-30 20:53:28 +0000134/// \brief Emit a note explaining that this function is deleted or unavailable.
135void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
136 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
137
Richard Smith6f1e2c62012-04-02 20:59:25 +0000138 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
139 // If the method was explicitly defaulted, point at that declaration.
140 if (!Method->isImplicit())
141 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
142
143 // Try to diagnose why this special member function was implicitly
144 // deleted. This might fail, if that reason no longer applies.
Richard Smith852265f2012-03-30 20:53:28 +0000145 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +0000146 if (CSM != CXXInvalid)
147 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
148
149 return;
Richard Smith852265f2012-03-30 20:53:28 +0000150 }
151
152 Diag(Decl->getLocation(), diag::note_unavailable_here)
153 << 1 << Decl->isDeleted();
154}
155
Jordan Rose28cd12f2012-06-18 22:09:19 +0000156/// \brief Determine whether a FunctionDecl was ever declared with an
157/// explicit storage class.
158static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
159 for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
160 E = D->redecls_end();
161 I != E; ++I) {
162 if (I->getStorageClassAsWritten() != SC_None)
163 return true;
164 }
165 return false;
166}
167
168/// \brief Check whether we're in an extern inline function and referring to a
Jordan Rosede9e9762012-06-20 18:50:06 +0000169/// variable or function with internal linkage (C11 6.7.4p3).
Jordan Rose28cd12f2012-06-18 22:09:19 +0000170///
Jordan Rose28cd12f2012-06-18 22:09:19 +0000171/// This is only a warning because we used to silently accept this code, but
Jordan Rosede9e9762012-06-20 18:50:06 +0000172/// in many cases it will not behave correctly. This is not enabled in C++ mode
173/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
174/// and so while there may still be user mistakes, most of the time we can't
175/// prove that there are errors.
Jordan Rose28cd12f2012-06-18 22:09:19 +0000176static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
177 const NamedDecl *D,
178 SourceLocation Loc) {
Jordan Rosede9e9762012-06-20 18:50:06 +0000179 // This is disabled under C++; there are too many ways for this to fire in
180 // contexts where the warning is a false positive, or where it is technically
181 // correct but benign.
182 if (S.getLangOpts().CPlusPlus)
183 return;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000184
185 // Check if this is an inlined function or method.
186 FunctionDecl *Current = S.getCurFunctionDecl();
187 if (!Current)
188 return;
189 if (!Current->isInlined())
190 return;
191 if (Current->getLinkage() != ExternalLinkage)
192 return;
193
194 // Check if the decl has internal linkage.
Jordan Rosede9e9762012-06-20 18:50:06 +0000195 if (D->getLinkage() != InternalLinkage)
Jordan Rose28cd12f2012-06-18 22:09:19 +0000196 return;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000197
Jordan Rose815fe262012-06-21 05:54:50 +0000198 // Downgrade from ExtWarn to Extension if
199 // (1) the supposedly external inline function is in the main file,
200 // and probably won't be included anywhere else.
201 // (2) the thing we're referencing is a pure function.
202 // (3) the thing we're referencing is another inline function.
203 // This last can give us false negatives, but it's better than warning on
204 // wrappers for simple C library functions.
205 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
206 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
207 if (!DowngradeWarning && UsedFn)
208 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
209
210 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
211 : diag::warn_internal_in_extern_inline)
212 << /*IsVar=*/!UsedFn << D;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000213
214 // Suggest "static" on the inline function, if possible.
Jordan Rosede9e9762012-06-20 18:50:06 +0000215 if (!hasAnyExplicitStorageClass(Current)) {
Jordan Rose28cd12f2012-06-18 22:09:19 +0000216 const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
217 SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
218 S.Diag(DeclBegin, diag::note_convert_inline_to_static)
219 << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
220 }
221
222 S.Diag(D->getCanonicalDecl()->getLocation(),
223 diag::note_internal_decl_declared_here)
224 << D;
225}
226
Douglas Gregor171c45a2009-02-18 21:56:37 +0000227/// \brief Determine whether the use of this declaration is valid, and
228/// emit any corresponding diagnostics.
229///
230/// This routine diagnoses various problems with referencing
231/// declarations that can occur when using a declaration. For example,
232/// it might warn if a deprecated or unavailable declaration is being
233/// used, or produce an error (and return true) if a C++0x deleted
234/// function is being used.
235///
236/// \returns true if there was an error (this declaration cannot be
237/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +0000238///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +0000239bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000240 const ObjCInterfaceDecl *UnknownObjCClass) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000241 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000242 // If there were any diagnostics suppressed by template argument deduction,
243 // emit them now.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000244 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000245 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
246 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000247 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000248 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
249 Diag(Suppressed[I].first, Suppressed[I].second);
250
251 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000252 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000253 // entry from the table, because we want to avoid ever emitting these
254 // diagnostics again.
255 Suppressed.clear();
256 }
257 }
258
Richard Smith30482bc2011-02-20 03:19:35 +0000259 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +0000260 if (ParsingInitForAutoVars.count(D)) {
261 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
262 << D->getDeclName();
263 return true;
Richard Smith30482bc2011-02-20 03:19:35 +0000264 }
265
Douglas Gregor171c45a2009-02-18 21:56:37 +0000266 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +0000267 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +0000268 if (FD->isDeleted()) {
269 Diag(Loc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +0000270 NoteDeletedFunction(FD);
Douglas Gregor171c45a2009-02-18 21:56:37 +0000271 return true;
272 }
Douglas Gregorde681d42009-02-24 04:26:15 +0000273 }
Ted Kremenek6eb25622012-02-10 02:45:47 +0000274 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000275
Fariborz Jahanian66c93f42012-09-06 16:43:18 +0000276 DiagnoseUnusedOfDecl(*this, D, Loc);
Jordan Rose2684c682012-06-15 18:19:48 +0000277
Jordan Rose28cd12f2012-06-18 22:09:19 +0000278 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
Jordan Rose2684c682012-06-15 18:19:48 +0000279
Douglas Gregor171c45a2009-02-18 21:56:37 +0000280 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000281}
282
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000283/// \brief Retrieve the message suffix that should be added to a
284/// diagnostic complaining about the given function being deleted or
285/// unavailable.
286std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
287 // FIXME: C++0x implicitly-deleted special member functions could be
288 // detected here so that we could improve diagnostics to say, e.g.,
289 // "base class 'A' had a deleted copy constructor".
290 if (FD->isDeleted())
291 return std::string();
292
293 std::string Message;
294 if (FD->getAvailability(&Message))
295 return ": " + Message;
296
297 return std::string();
298}
299
John McCallb46f2872011-09-09 07:56:05 +0000300/// DiagnoseSentinelCalls - This routine checks whether a call or
301/// message-send is to a declaration with the sentinel attribute, and
302/// if so, it checks that the requirements of the sentinel are
303/// satisfied.
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000304void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCallb46f2872011-09-09 07:56:05 +0000305 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000306 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000307 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000308 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000309
John McCallb46f2872011-09-09 07:56:05 +0000310 // The number of formal parameters of the declaration.
311 unsigned numFormalParams;
Mike Stump11289f42009-09-09 15:08:12 +0000312
John McCallb46f2872011-09-09 07:56:05 +0000313 // The kind of declaration. This is also an index into a %select in
314 // the diagnostic.
315 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
316
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000317 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000318 numFormalParams = MD->param_size();
319 calleeType = CT_Method;
Mike Stump12b8ce12009-08-04 21:02:39 +0000320 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000321 numFormalParams = FD->param_size();
322 calleeType = CT_Function;
323 } else if (isa<VarDecl>(D)) {
324 QualType type = cast<ValueDecl>(D)->getType();
325 const FunctionType *fn = 0;
326 if (const PointerType *ptr = type->getAs<PointerType>()) {
327 fn = ptr->getPointeeType()->getAs<FunctionType>();
328 if (!fn) return;
329 calleeType = CT_Function;
330 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
331 fn = ptr->getPointeeType()->castAs<FunctionType>();
332 calleeType = CT_Block;
333 } else {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000334 return;
John McCallb46f2872011-09-09 07:56:05 +0000335 }
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000336
John McCallb46f2872011-09-09 07:56:05 +0000337 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
338 numFormalParams = proto->getNumArgs();
339 } else {
340 numFormalParams = 0;
341 }
342 } else {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000343 return;
344 }
John McCallb46f2872011-09-09 07:56:05 +0000345
346 // "nullPos" is the number of formal parameters at the end which
347 // effectively count as part of the variadic arguments. This is
348 // useful if you would prefer to not have *any* formal parameters,
349 // but the language forces you to have at least one.
350 unsigned nullPos = attr->getNullPos();
351 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
352 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
353
354 // The number of arguments which should follow the sentinel.
355 unsigned numArgsAfterSentinel = attr->getSentinel();
356
357 // If there aren't enough arguments for all the formal parameters,
358 // the sentinel, and the args after the sentinel, complain.
359 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000360 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCallb46f2872011-09-09 07:56:05 +0000361 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000362 return;
363 }
John McCallb46f2872011-09-09 07:56:05 +0000364
365 // Otherwise, find the sentinel expression.
366 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall7ddbcf42010-05-06 23:53:00 +0000367 if (!sentinelExpr) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000368 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +0000369 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000370
John McCallb46f2872011-09-09 07:56:05 +0000371 // Pick a reasonable string to insert. Optimistically use 'nil' or
372 // 'NULL' if those are actually defined in the context. Only use
373 // 'nil' for ObjC methods, where it's much more likely that the
374 // variadic arguments form a list of object pointers.
375 SourceLocation MissingNilLoc
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000376 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
377 std::string NullValue;
John McCallb46f2872011-09-09 07:56:05 +0000378 if (calleeType == CT_Method &&
379 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000380 NullValue = "nil";
381 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
382 NullValue = "NULL";
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000383 else
John McCallb46f2872011-09-09 07:56:05 +0000384 NullValue = "(void*) 0";
Eli Friedman9ab36372011-09-27 23:46:37 +0000385
386 if (MissingNilLoc.isInvalid())
387 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
388 else
389 Diag(MissingNilLoc, diag::warn_missing_sentinel)
390 << calleeType
391 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCallb46f2872011-09-09 07:56:05 +0000392 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000393}
394
Richard Trieuba63ce62011-09-09 01:45:06 +0000395SourceRange Sema::getExprRange(Expr *E) const {
396 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor87f95b02009-02-26 21:00:50 +0000397}
398
Chris Lattner513165e2008-07-25 21:10:04 +0000399//===----------------------------------------------------------------------===//
400// Standard Promotions and Conversions
401//===----------------------------------------------------------------------===//
402
Chris Lattner513165e2008-07-25 21:10:04 +0000403/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000404ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000405 // Handle any placeholder expressions which made it here.
406 if (E->getType()->isPlaceholderType()) {
407 ExprResult result = CheckPlaceholderExpr(E);
408 if (result.isInvalid()) return ExprError();
409 E = result.take();
410 }
411
Chris Lattner513165e2008-07-25 21:10:04 +0000412 QualType Ty = E->getType();
413 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
414
Chris Lattner513165e2008-07-25 21:10:04 +0000415 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000416 E = ImpCastExprToType(E, Context.getPointerType(Ty),
417 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000418 else if (Ty->isArrayType()) {
419 // In C90 mode, arrays only promote to pointers if the array expression is
420 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
421 // type 'array of type' is converted to an expression that has type 'pointer
422 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
423 // that has type 'array of type' ...". The relevant change is "an lvalue"
424 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000425 //
426 // C++ 4.2p1:
427 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
428 // T" can be converted to an rvalue of type "pointer to T".
429 //
David Blaikiebbafb8a2012-03-11 07:00:24 +0000430 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000431 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
432 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000433 }
John Wiegley01296292011-04-08 18:41:53 +0000434 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000435}
436
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000437static void CheckForNullPointerDereference(Sema &S, Expr *E) {
438 // Check to see if we are dereferencing a null pointer. If so,
439 // and if not volatile-qualified, this is undefined behavior that the
440 // optimizer will delete, so warn about it. People sometimes try to use this
441 // to get a deterministic trap and are surprised by clang's behavior. This
442 // only handles the pattern "*null", which is a very syntactic check.
443 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
444 if (UO->getOpcode() == UO_Deref &&
445 UO->getSubExpr()->IgnoreParenCasts()->
446 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
447 !UO->getType().isVolatileQualified()) {
448 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
449 S.PDiag(diag::warn_indirection_through_null)
450 << UO->getSubExpr()->getSourceRange());
451 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
452 S.PDiag(diag::note_indirection_through_null));
453 }
454}
455
John Wiegley01296292011-04-08 18:41:53 +0000456ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000457 // Handle any placeholder expressions which made it here.
458 if (E->getType()->isPlaceholderType()) {
459 ExprResult result = CheckPlaceholderExpr(E);
460 if (result.isInvalid()) return ExprError();
461 E = result.take();
462 }
463
John McCallf3735e02010-12-01 04:43:34 +0000464 // C++ [conv.lval]p1:
465 // A glvalue of a non-function, non-array type T can be
466 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000467 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +0000468
John McCall27584242010-12-06 20:48:59 +0000469 QualType T = E->getType();
470 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000471
John McCall27584242010-12-06 20:48:59 +0000472 // We don't want to throw lvalue-to-rvalue casts on top of
473 // expressions of certain types in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000474 if (getLangOpts().CPlusPlus &&
John McCall27584242010-12-06 20:48:59 +0000475 (E->getType() == Context.OverloadTy ||
476 T->isDependentType() ||
477 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000478 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000479
480 // The C standard is actually really unclear on this point, and
481 // DR106 tells us what the result should be but not why. It's
482 // generally best to say that void types just doesn't undergo
483 // lvalue-to-rvalue at all. Note that expressions of unqualified
484 // 'void' type are never l-values, but qualified void can be.
485 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000486 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000487
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000488 CheckForNullPointerDereference(*this, E);
489
John McCall27584242010-12-06 20:48:59 +0000490 // C++ [conv.lval]p1:
491 // [...] If T is a non-class type, the type of the prvalue is the
492 // cv-unqualified version of T. Otherwise, the type of the
493 // rvalue is T.
494 //
495 // C99 6.3.2.1p2:
496 // If the lvalue has qualified type, the value has the unqualified
497 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000498 // type of the lvalue.
John McCall27584242010-12-06 20:48:59 +0000499 if (T.hasQualifiers())
500 T = T.getUnqualifiedType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000501
Eli Friedman3bda6b12012-02-02 23:15:15 +0000502 UpdateMarkingForLValueToRValue(E);
503
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000504 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
505 E, 0, VK_RValue));
506
Douglas Gregorc79862f2012-04-12 17:51:55 +0000507 // C11 6.3.2.1p2:
508 // ... if the lvalue has atomic type, the value has the non-atomic version
509 // of the type of the lvalue ...
510 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
511 T = Atomic->getValueType().getUnqualifiedType();
512 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
513 Res.get(), 0, VK_RValue));
514 }
515
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000516 return Res;
John McCall27584242010-12-06 20:48:59 +0000517}
518
John Wiegley01296292011-04-08 18:41:53 +0000519ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
520 ExprResult Res = DefaultFunctionArrayConversion(E);
521 if (Res.isInvalid())
522 return ExprError();
523 Res = DefaultLvalueConversion(Res.take());
524 if (Res.isInvalid())
525 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000526 return Res;
Douglas Gregorb92a1562010-02-03 00:27:59 +0000527}
528
529
Chris Lattner513165e2008-07-25 21:10:04 +0000530/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000531/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000532/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000533/// apply if the array is an argument to the sizeof or address (&) operators.
534/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000535ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000536 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000537 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
538 if (Res.isInvalid())
539 return Owned(E);
540 E = Res.take();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000541
John McCallf3735e02010-12-01 04:43:34 +0000542 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000543 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000544
545 // Half FP is a bit different: it's a storage-only type, meaning that any
546 // "use" of it should be promoted to float.
547 if (Ty->isHalfType())
548 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
549
John McCallf3735e02010-12-01 04:43:34 +0000550 // Try to perform integral promotions if the object has a theoretically
551 // promotable type.
552 if (Ty->isIntegralOrUnscopedEnumerationType()) {
553 // C99 6.3.1.1p2:
554 //
555 // The following may be used in an expression wherever an int or
556 // unsigned int may be used:
557 // - an object or expression with an integer type whose integer
558 // conversion rank is less than or equal to the rank of int
559 // and unsigned int.
560 // - A bit-field of type _Bool, int, signed int, or unsigned int.
561 //
562 // If an int can represent all values of the original type, the
563 // value is converted to an int; otherwise, it is converted to an
564 // unsigned int. These are called the integer promotions. All
565 // other types are unchanged by the integer promotions.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000566
John McCallf3735e02010-12-01 04:43:34 +0000567 QualType PTy = Context.isPromotableBitField(E);
568 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000569 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
570 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000571 }
572 if (Ty->isPromotableIntegerType()) {
573 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000574 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
575 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000576 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000577 }
John Wiegley01296292011-04-08 18:41:53 +0000578 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000579}
580
Chris Lattner2ce500f2008-07-25 22:25:12 +0000581/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000582/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000583/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000584ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
585 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000586 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000587
John Wiegley01296292011-04-08 18:41:53 +0000588 ExprResult Res = UsualUnaryConversions(E);
589 if (Res.isInvalid())
590 return Owned(E);
591 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000592
Chris Lattner2ce500f2008-07-25 22:25:12 +0000593 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000594 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000595 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
596
John McCall4bb057d2011-08-27 22:06:17 +0000597 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall0562caa2011-08-29 23:55:37 +0000598 // promotion, even on class types, but note:
599 // C++11 [conv.lval]p2:
600 // When an lvalue-to-rvalue conversion occurs in an unevaluated
601 // operand or a subexpression thereof the value contained in the
602 // referenced object is not accessed. Otherwise, if the glvalue
603 // has a class type, the conversion copy-initializes a temporary
604 // of type T from the glvalue and the result of the conversion
605 // is a prvalue for the temporary.
Eli Friedman05e28012012-01-17 02:13:45 +0000606 // FIXME: add some way to gate this entire thing for correctness in
607 // potentially potentially evaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +0000608 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
Eli Friedman05e28012012-01-17 02:13:45 +0000609 ExprResult Temp = PerformCopyInitialization(
610 InitializedEntity::InitializeTemporary(E->getType()),
611 E->getExprLoc(),
612 Owned(E));
613 if (Temp.isInvalid())
614 return ExprError();
615 E = Temp.get();
John McCall29ad95b2011-08-27 01:09:30 +0000616 }
617
John Wiegley01296292011-04-08 18:41:53 +0000618 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000619}
620
Richard Smith55ce3522012-06-25 20:30:08 +0000621/// Determine the degree of POD-ness for an expression.
622/// Incomplete types are considered POD, since this check can be performed
623/// when we're in an unevaluated context.
624Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
Jordan Rose3e0ec582012-07-19 18:10:23 +0000625 if (Ty->isIncompleteType()) {
626 if (Ty->isObjCObjectType())
627 return VAK_Invalid;
Richard Smith55ce3522012-06-25 20:30:08 +0000628 return VAK_Valid;
Jordan Rose3e0ec582012-07-19 18:10:23 +0000629 }
630
631 if (Ty.isCXX98PODType(Context))
632 return VAK_Valid;
633
Richard Smith55ce3522012-06-25 20:30:08 +0000634 // C++0x [expr.call]p7:
635 // Passing a potentially-evaluated argument of class type (Clause 9)
636 // having a non-trivial copy constructor, a non-trivial move constructor,
637 // or a non-trivial destructor, with no corresponding parameter,
638 // is conditionally-supported with implementation-defined semantics.
Richard Smith55ce3522012-06-25 20:30:08 +0000639 if (getLangOpts().CPlusPlus0x && !Ty->isDependentType())
640 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
641 if (Record->hasTrivialCopyConstructor() &&
642 Record->hasTrivialMoveConstructor() &&
643 Record->hasTrivialDestructor())
644 return VAK_ValidInCXX11;
645
646 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
647 return VAK_Valid;
648 return VAK_Invalid;
649}
650
651bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
652 // Don't allow one to pass an Objective-C interface to a vararg.
653 const QualType & Ty = E->getType();
654
655 // Complain about passing non-POD types through varargs.
656 switch (isValidVarArgType(Ty)) {
657 case VAK_Valid:
658 break;
659 case VAK_ValidInCXX11:
660 DiagRuntimeBehavior(E->getLocStart(), 0,
661 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
662 << E->getType() << CT);
663 break;
Jordan Rose3e0ec582012-07-19 18:10:23 +0000664 case VAK_Invalid: {
665 if (Ty->isObjCObjectType())
666 return DiagRuntimeBehavior(E->getLocStart(), 0,
667 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
668 << Ty << CT);
669
Richard Smith55ce3522012-06-25 20:30:08 +0000670 return DiagRuntimeBehavior(E->getLocStart(), 0,
671 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
672 << getLangOpts().CPlusPlus0x << Ty << CT);
673 }
Jordan Rose3e0ec582012-07-19 18:10:23 +0000674 }
Richard Smith55ce3522012-06-25 20:30:08 +0000675 // c++ rules are enforced elsewhere.
676 return false;
677}
678
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000679/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
Jordan Rose3e0ec582012-07-19 18:10:23 +0000680/// will create a trap if the resulting type is not a POD type.
John Wiegley01296292011-04-08 18:41:53 +0000681ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000682 FunctionDecl *FDecl) {
Richard Smith7659b122012-06-27 20:29:39 +0000683 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
John McCall4124c492011-10-17 18:40:02 +0000684 // Strip the unbridged-cast placeholder expression off, if applicable.
685 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
686 (CT == VariadicMethod ||
687 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
688 E = stripARCUnbridgedCast(E);
689
690 // Otherwise, do normal placeholder checking.
691 } else {
692 ExprResult ExprRes = CheckPlaceholderExpr(E);
693 if (ExprRes.isInvalid())
694 return ExprError();
695 E = ExprRes.take();
696 }
697 }
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000698
John McCall4124c492011-10-17 18:40:02 +0000699 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000700 if (ExprRes.isInvalid())
701 return ExprError();
702 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000703
Richard Smith55ce3522012-06-25 20:30:08 +0000704 // Diagnostics regarding non-POD argument types are
705 // emitted along with format string checking in Sema::CheckFunctionCall().
Richard Smith56471fd2012-06-27 20:23:58 +0000706 if (isValidVarArgType(E->getType()) == VAK_Invalid) {
Richard Smith55ce3522012-06-25 20:30:08 +0000707 // Turn this into a trap.
708 CXXScopeSpec SS;
709 SourceLocation TemplateKWLoc;
710 UnqualifiedId Name;
711 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
712 E->getLocStart());
713 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
714 Name, true, false);
715 if (TrapFn.isInvalid())
716 return ExprError();
John McCall31168b02011-06-15 23:02:42 +0000717
Richard Smith55ce3522012-06-25 20:30:08 +0000718 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
719 E->getLocStart(), MultiExprArg(),
720 E->getLocEnd());
721 if (Call.isInvalid())
722 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000723
Richard Smith55ce3522012-06-25 20:30:08 +0000724 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
725 Call.get(), E);
726 if (Comma.isInvalid())
727 return ExprError();
728 return Comma.get();
Douglas Gregor253cadf2011-05-21 16:27:21 +0000729 }
Richard Smith55ce3522012-06-25 20:30:08 +0000730
David Blaikiebbafb8a2012-03-11 07:00:24 +0000731 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000732 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahanianbf482812012-03-02 17:05:03 +0000733 diag::err_call_incomplete_argument))
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000734 return ExprError();
Richard Smith55ce3522012-06-25 20:30:08 +0000735
John Wiegley01296292011-04-08 18:41:53 +0000736 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000737}
738
Richard Trieu7aa58f12011-09-02 20:58:51 +0000739/// \brief Converts an integer to complex float type. Helper function of
740/// UsualArithmeticConversions()
741///
742/// \return false if the integer expression is an integer type and is
743/// successfully converted to the complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000744static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
745 ExprResult &ComplexExpr,
746 QualType IntTy,
747 QualType ComplexTy,
748 bool SkipCast) {
749 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
750 if (SkipCast) return false;
751 if (IntTy->isIntegerType()) {
752 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
753 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
754 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000755 CK_FloatingRealToComplex);
756 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +0000757 assert(IntTy->isComplexIntegerType());
758 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000759 CK_IntegralComplexToFloatingComplex);
760 }
761 return false;
762}
763
764/// \brief Takes two complex float types and converts them to the same type.
765/// Helper function of UsualArithmeticConversions()
766static QualType
Richard Trieu5065cdd2011-09-06 18:25:09 +0000767handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
768 ExprResult &RHS, QualType LHSType,
769 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000770 bool IsCompAssign) {
Richard Trieu5065cdd2011-09-06 18:25:09 +0000771 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000772
773 if (order < 0) {
774 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000775 if (!IsCompAssign)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000776 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
777 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000778 }
779 if (order > 0)
780 // _Complex float -> _Complex double
Richard Trieu5065cdd2011-09-06 18:25:09 +0000781 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
782 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000783}
784
785/// \brief Converts otherExpr to complex float and promotes complexExpr if
786/// necessary. Helper function of UsualArithmeticConversions()
787static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuba63ce62011-09-09 01:45:06 +0000788 ExprResult &ComplexExpr,
789 ExprResult &OtherExpr,
790 QualType ComplexTy,
791 QualType OtherTy,
792 bool ConvertComplexExpr,
793 bool ConvertOtherExpr) {
794 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000795
796 // If just the complexExpr is complex, the otherExpr needs to be converted,
797 // and the complexExpr might need to be promoted.
798 if (order > 0) { // complexExpr is wider
799 // float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000800 if (ConvertOtherExpr) {
801 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
802 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
803 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000804 CK_FloatingRealToComplex);
805 }
Richard Trieuba63ce62011-09-09 01:45:06 +0000806 return ComplexTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000807 }
808
809 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000810 QualType result = (order == 0 ? ComplexTy :
811 S.Context.getComplexType(OtherTy));
Richard Trieu7aa58f12011-09-02 20:58:51 +0000812
813 // double -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000814 if (ConvertOtherExpr)
815 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000816 CK_FloatingRealToComplex);
817
818 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000819 if (ConvertComplexExpr && order < 0)
820 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000821 CK_FloatingComplexCast);
822
823 return result;
824}
825
826/// \brief Handle arithmetic conversion with complex types. Helper function of
827/// UsualArithmeticConversions()
Richard Trieu5065cdd2011-09-06 18:25:09 +0000828static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
829 ExprResult &RHS, QualType LHSType,
830 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000831 bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000832 // if we have an integer operand, the result is the complex type.
Richard Trieu5065cdd2011-09-06 18:25:09 +0000833 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000834 /*skipCast*/false))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000835 return LHSType;
836 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000837 /*skipCast*/IsCompAssign))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000838 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000839
840 // This handles complex/complex, complex/float, or float/complex.
841 // When both operands are complex, the shorter operand is converted to the
842 // type of the longer, and that is the type of the result. This corresponds
843 // to what is done when combining two real floating-point operands.
844 // The fun begins when size promotion occur across type domains.
845 // From H&S 6.3.4: When one operand is complex and the other is a real
846 // floating-point type, the less precise type is converted, within it's
847 // real or complex domain, to the precision of the other type. For example,
848 // when combining a "long double" with a "double _Complex", the
849 // "double _Complex" is promoted to "long double _Complex".
850
Richard Trieu5065cdd2011-09-06 18:25:09 +0000851 bool LHSComplexFloat = LHSType->isComplexType();
852 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000853
854 // If both are complex, just cast to the more precise type.
855 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000856 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
857 LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000858 IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000859
860 // If only one operand is complex, promote it if necessary and convert the
861 // other operand to complex.
862 if (LHSComplexFloat)
863 return handleOtherComplexFloatConversion(
Richard Trieuba63ce62011-09-09 01:45:06 +0000864 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000865 /*convertOtherExpr*/ true);
866
867 assert(RHSComplexFloat);
868 return handleOtherComplexFloatConversion(
Richard Trieu5065cdd2011-09-06 18:25:09 +0000869 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000870 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000871}
872
873/// \brief Hande arithmetic conversion from integer to float. Helper function
874/// of UsualArithmeticConversions()
Richard Trieuba63ce62011-09-09 01:45:06 +0000875static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
876 ExprResult &IntExpr,
877 QualType FloatTy, QualType IntTy,
878 bool ConvertFloat, bool ConvertInt) {
879 if (IntTy->isIntegerType()) {
880 if (ConvertInt)
Richard Trieu7aa58f12011-09-02 20:58:51 +0000881 // Convert intExpr to the lhs floating point type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000882 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000883 CK_IntegralToFloating);
Richard Trieuba63ce62011-09-09 01:45:06 +0000884 return FloatTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000885 }
886
887 // Convert both sides to the appropriate complex float.
Richard Trieuba63ce62011-09-09 01:45:06 +0000888 assert(IntTy->isComplexIntegerType());
889 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000890
891 // _Complex int -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000892 if (ConvertInt)
893 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000894 CK_IntegralComplexToFloatingComplex);
895
896 // float -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000897 if (ConvertFloat)
898 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000899 CK_FloatingRealToComplex);
900
901 return result;
902}
903
904/// \brief Handle arithmethic conversion with floating point types. Helper
905/// function of UsualArithmeticConversions()
Richard Trieucfe3f212011-09-06 18:38:41 +0000906static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
907 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000908 QualType RHSType, bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000909 bool LHSFloat = LHSType->isRealFloatingType();
910 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000911
912 // If we have two real floating types, convert the smaller operand
913 // to the bigger result.
914 if (LHSFloat && RHSFloat) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000915 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000916 if (order > 0) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000917 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
918 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000919 }
920
921 assert(order < 0 && "illegal float comparison");
Richard Trieuba63ce62011-09-09 01:45:06 +0000922 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000923 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
924 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000925 }
926
927 if (LHSFloat)
Richard Trieucfe3f212011-09-06 18:38:41 +0000928 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000929 /*convertFloat=*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000930 /*convertInt=*/ true);
931 assert(RHSFloat);
Richard Trieucfe3f212011-09-06 18:38:41 +0000932 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000933 /*convertInt=*/ true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000934 /*convertFloat=*/!IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000935}
936
937/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000938/// of UsualArithmeticConversions()
Richard Trieu7aa58f12011-09-02 20:58:51 +0000939// FIXME: if the operands are (int, _Complex long), we currently
940// don't promote the complex. Also, signedness?
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000941static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
942 ExprResult &RHS, QualType LHSType,
943 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000944 bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000945 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
946 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000947
Richard Trieucfe3f212011-09-06 18:38:41 +0000948 if (LHSComplexInt && RHSComplexInt) {
949 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
950 RHSComplexInt->getElementType());
Richard Trieu7aa58f12011-09-02 20:58:51 +0000951 assert(order && "inequal types with equal element ordering");
952 if (order > 0) {
953 // _Complex int -> _Complex long
Richard Trieucfe3f212011-09-06 18:38:41 +0000954 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
955 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000956 }
957
Richard Trieuba63ce62011-09-09 01:45:06 +0000958 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000959 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
960 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000961 }
962
Richard Trieucfe3f212011-09-06 18:38:41 +0000963 if (LHSComplexInt) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000964 // int -> _Complex int
Eli Friedman47133be2011-11-12 03:56:23 +0000965 // FIXME: This needs to take integer ranks into account
966 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
967 CK_IntegralCast);
Richard Trieucfe3f212011-09-06 18:38:41 +0000968 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
969 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000970 }
971
Richard Trieucfe3f212011-09-06 18:38:41 +0000972 assert(RHSComplexInt);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000973 // int -> _Complex int
Eli Friedman47133be2011-11-12 03:56:23 +0000974 // FIXME: This needs to take integer ranks into account
975 if (!IsCompAssign) {
976 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
977 CK_IntegralCast);
Richard Trieucfe3f212011-09-06 18:38:41 +0000978 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
Eli Friedman47133be2011-11-12 03:56:23 +0000979 }
Richard Trieucfe3f212011-09-06 18:38:41 +0000980 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000981}
982
983/// \brief Handle integer arithmetic conversions. Helper function of
984/// UsualArithmeticConversions()
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000985static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
986 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000987 QualType RHSType, bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000988 // The rules for this case are in C99 6.3.1.8
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000989 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
990 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
991 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
992 if (LHSSigned == RHSSigned) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000993 // Same signedness; use the higher-ranked type
994 if (order >= 0) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000995 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
996 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000997 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000998 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
999 return RHSType;
1000 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +00001001 // The unsigned type has greater than or equal rank to the
1002 // signed type, so use the unsigned type
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001003 if (RHSSigned) {
1004 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1005 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +00001006 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001007 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1008 return RHSType;
1009 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +00001010 // The two types are different widths; if we are here, that
1011 // means the signed type is larger than the unsigned type, so
1012 // use the signed type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001013 if (LHSSigned) {
1014 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1015 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +00001016 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001017 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1018 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +00001019 } else {
1020 // The signed type is higher-ranked than the unsigned type,
1021 // but isn't actually any bigger (like unsigned int and long
1022 // on most 32-bit systems). Use the unsigned type corresponding
1023 // to the signed type.
1024 QualType result =
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001025 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1026 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuba63ce62011-09-09 01:45:06 +00001027 if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001028 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu7aa58f12011-09-02 20:58:51 +00001029 return result;
1030 }
1031}
1032
Chris Lattner513165e2008-07-25 21:10:04 +00001033/// UsualArithmeticConversions - Performs various conversions that are common to
1034/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +00001035/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +00001036/// responsible for emitting appropriate error diagnostics.
1037/// FIXME: verify the conversion rules for "complex int" are consistent with
1038/// GCC.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001039QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00001040 bool IsCompAssign) {
1041 if (!IsCompAssign) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001042 LHS = UsualUnaryConversions(LHS.take());
1043 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001044 return QualType();
1045 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00001046
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001047 RHS = UsualUnaryConversions(RHS.take());
1048 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001049 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001050
Mike Stump11289f42009-09-09 15:08:12 +00001051 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +00001052 // For example, "const float" and "float" are equivalent.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001053 QualType LHSType =
1054 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1055 QualType RHSType =
1056 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001057
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001058 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1059 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1060 LHSType = AtomicLHS->getValueType();
1061
Douglas Gregora11693b2008-11-12 17:17:38 +00001062 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001063 if (LHSType == RHSType)
1064 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +00001065
1066 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1067 // The caller can deal with this (e.g. pointer + int).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001068 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001069 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001070
John McCalld005ac92010-11-13 08:17:45 +00001071 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001072 QualType LHSUnpromotedType = LHSType;
1073 if (LHSType->isPromotableIntegerType())
1074 LHSType = Context.getPromotedIntegerType(LHSType);
1075 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +00001076 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001077 LHSType = LHSBitfieldPromoteTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00001078 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001079 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +00001080
John McCalld005ac92010-11-13 08:17:45 +00001081 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001082 if (LHSType == RHSType)
1083 return LHSType;
John McCalld005ac92010-11-13 08:17:45 +00001084
1085 // At this point, we have two different arithmetic types.
1086
1087 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001088 if (LHSType->isComplexType() || RHSType->isComplexType())
1089 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001090 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001091
1092 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001093 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1094 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001095 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001096
1097 // Handle GCC complex int extension.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001098 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer499c68b2011-09-06 19:57:14 +00001099 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001100 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001101
1102 // Finally, we have two differing integer types.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001103 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001104 IsCompAssign);
Douglas Gregora11693b2008-11-12 17:17:38 +00001105}
1106
Chris Lattner513165e2008-07-25 21:10:04 +00001107//===----------------------------------------------------------------------===//
1108// Semantic Analysis for various Expression Types
1109//===----------------------------------------------------------------------===//
1110
1111
Peter Collingbourne91147592011-04-15 00:35:48 +00001112ExprResult
1113Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1114 SourceLocation DefaultLoc,
1115 SourceLocation RParenLoc,
1116 Expr *ControllingExpr,
Richard Trieuba63ce62011-09-09 01:45:06 +00001117 MultiTypeArg ArgTypes,
1118 MultiExprArg ArgExprs) {
1119 unsigned NumAssocs = ArgTypes.size();
1120 assert(NumAssocs == ArgExprs.size());
Peter Collingbourne91147592011-04-15 00:35:48 +00001121
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001122 ParsedType *ParsedTypes = ArgTypes.data();
1123 Expr **Exprs = ArgExprs.data();
Peter Collingbourne91147592011-04-15 00:35:48 +00001124
1125 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1126 for (unsigned i = 0; i < NumAssocs; ++i) {
1127 if (ParsedTypes[i])
1128 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1129 else
1130 Types[i] = 0;
1131 }
1132
1133 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1134 ControllingExpr, Types, Exprs,
1135 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +00001136 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +00001137 return ER;
1138}
1139
1140ExprResult
1141Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1142 SourceLocation DefaultLoc,
1143 SourceLocation RParenLoc,
1144 Expr *ControllingExpr,
1145 TypeSourceInfo **Types,
1146 Expr **Exprs,
1147 unsigned NumAssocs) {
1148 bool TypeErrorFound = false,
1149 IsResultDependent = ControllingExpr->isTypeDependent(),
1150 ContainsUnexpandedParameterPack
1151 = ControllingExpr->containsUnexpandedParameterPack();
1152
1153 for (unsigned i = 0; i < NumAssocs; ++i) {
1154 if (Exprs[i]->containsUnexpandedParameterPack())
1155 ContainsUnexpandedParameterPack = true;
1156
1157 if (Types[i]) {
1158 if (Types[i]->getType()->containsUnexpandedParameterPack())
1159 ContainsUnexpandedParameterPack = true;
1160
1161 if (Types[i]->getType()->isDependentType()) {
1162 IsResultDependent = true;
1163 } else {
Benjamin Kramere56f3932011-12-23 17:00:35 +00001164 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbourne91147592011-04-15 00:35:48 +00001165 // complete object type other than a variably modified type."
1166 unsigned D = 0;
1167 if (Types[i]->getType()->isIncompleteType())
1168 D = diag::err_assoc_type_incomplete;
1169 else if (!Types[i]->getType()->isObjectType())
1170 D = diag::err_assoc_type_nonobject;
1171 else if (Types[i]->getType()->isVariablyModifiedType())
1172 D = diag::err_assoc_type_variably_modified;
1173
1174 if (D != 0) {
1175 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1176 << Types[i]->getTypeLoc().getSourceRange()
1177 << Types[i]->getType();
1178 TypeErrorFound = true;
1179 }
1180
Benjamin Kramere56f3932011-12-23 17:00:35 +00001181 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbourne91147592011-04-15 00:35:48 +00001182 // selection shall specify compatible types."
1183 for (unsigned j = i+1; j < NumAssocs; ++j)
1184 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1185 Context.typesAreCompatible(Types[i]->getType(),
1186 Types[j]->getType())) {
1187 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1188 diag::err_assoc_compatible_types)
1189 << Types[j]->getTypeLoc().getSourceRange()
1190 << Types[j]->getType()
1191 << Types[i]->getType();
1192 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1193 diag::note_compat_assoc)
1194 << Types[i]->getTypeLoc().getSourceRange()
1195 << Types[i]->getType();
1196 TypeErrorFound = true;
1197 }
1198 }
1199 }
1200 }
1201 if (TypeErrorFound)
1202 return ExprError();
1203
1204 // If we determined that the generic selection is result-dependent, don't
1205 // try to compute the result expression.
1206 if (IsResultDependent)
1207 return Owned(new (Context) GenericSelectionExpr(
1208 Context, KeyLoc, ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001209 llvm::makeArrayRef(Types, NumAssocs),
1210 llvm::makeArrayRef(Exprs, NumAssocs),
1211 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
Peter Collingbourne91147592011-04-15 00:35:48 +00001212
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001213 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +00001214 unsigned DefaultIndex = -1U;
1215 for (unsigned i = 0; i < NumAssocs; ++i) {
1216 if (!Types[i])
1217 DefaultIndex = i;
1218 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1219 Types[i]->getType()))
1220 CompatIndices.push_back(i);
1221 }
1222
Benjamin Kramere56f3932011-12-23 17:00:35 +00001223 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbourne91147592011-04-15 00:35:48 +00001224 // type compatible with at most one of the types named in its generic
1225 // association list."
1226 if (CompatIndices.size() > 1) {
1227 // We strip parens here because the controlling expression is typically
1228 // parenthesized in macro definitions.
1229 ControllingExpr = ControllingExpr->IgnoreParens();
1230 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1231 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1232 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001233 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +00001234 E = CompatIndices.end(); I != E; ++I) {
1235 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1236 diag::note_compat_assoc)
1237 << Types[*I]->getTypeLoc().getSourceRange()
1238 << Types[*I]->getType();
1239 }
1240 return ExprError();
1241 }
1242
Benjamin Kramere56f3932011-12-23 17:00:35 +00001243 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbourne91147592011-04-15 00:35:48 +00001244 // its controlling expression shall have type compatible with exactly one of
1245 // the types named in its generic association list."
1246 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1247 // We strip parens here because the controlling expression is typically
1248 // parenthesized in macro definitions.
1249 ControllingExpr = ControllingExpr->IgnoreParens();
1250 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1251 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1252 return ExprError();
1253 }
1254
Benjamin Kramere56f3932011-12-23 17:00:35 +00001255 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbourne91147592011-04-15 00:35:48 +00001256 // type name that is compatible with the type of the controlling expression,
1257 // then the result expression of the generic selection is the expression
1258 // in that generic association. Otherwise, the result expression of the
1259 // generic selection is the expression in the default generic association."
1260 unsigned ResultIndex =
1261 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1262
1263 return Owned(new (Context) GenericSelectionExpr(
1264 Context, KeyLoc, ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001265 llvm::makeArrayRef(Types, NumAssocs),
1266 llvm::makeArrayRef(Exprs, NumAssocs),
1267 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
Peter Collingbourne91147592011-04-15 00:35:48 +00001268 ResultIndex));
1269}
1270
Richard Smith75b67d62012-03-08 01:34:56 +00001271/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1272/// location of the token and the offset of the ud-suffix within it.
1273static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1274 unsigned Offset) {
1275 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001276 S.getLangOpts());
Richard Smith75b67d62012-03-08 01:34:56 +00001277}
1278
Richard Smithbcc22fc2012-03-09 08:00:36 +00001279/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1280/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1281static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1282 IdentifierInfo *UDSuffix,
1283 SourceLocation UDSuffixLoc,
1284 ArrayRef<Expr*> Args,
1285 SourceLocation LitEndLoc) {
1286 assert(Args.size() <= 2 && "too many arguments for literal operator");
1287
1288 QualType ArgTy[2];
1289 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1290 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1291 if (ArgTy[ArgIdx]->isArrayType())
1292 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1293 }
1294
1295 DeclarationName OpName =
1296 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1297 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1298 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1299
1300 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1301 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1302 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1303 return ExprError();
1304
1305 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1306}
1307
Steve Naroff83895f72007-09-16 03:34:24 +00001308/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001309/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1310/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1311/// multiple tokens. However, the common case is that StringToks points to one
1312/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001313///
John McCalldadc5752010-08-24 06:29:42 +00001314ExprResult
Richard Smithbcc22fc2012-03-09 08:00:36 +00001315Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1316 Scope *UDLScope) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001317 assert(NumStringToks && "Must have at least one string!");
1318
Chris Lattner8a24e582009-01-16 18:51:42 +00001319 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001320 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001321 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001322
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001323 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001324 for (unsigned i = 0; i != NumStringToks; ++i)
1325 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001326
Chris Lattner36fc8792008-02-11 00:02:17 +00001327 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001328 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001329 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001330 else if (Literal.isUTF16())
1331 StrTy = Context.Char16Ty;
1332 else if (Literal.isUTF32())
1333 StrTy = Context.Char32Ty;
Eli Friedmanfcec6302011-11-01 02:23:42 +00001334 else if (Literal.isPascal())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001335 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001336
Douglas Gregorfb65e592011-07-27 05:40:30 +00001337 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1338 if (Literal.isWide())
1339 Kind = StringLiteral::Wide;
1340 else if (Literal.isUTF8())
1341 Kind = StringLiteral::UTF8;
1342 else if (Literal.isUTF16())
1343 Kind = StringLiteral::UTF16;
1344 else if (Literal.isUTF32())
1345 Kind = StringLiteral::UTF32;
1346
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001347 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001348 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001349 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001350
Chris Lattner36fc8792008-02-11 00:02:17 +00001351 // Get an array type for the string, according to C99 6.4.5. This includes
1352 // the nul terminator character as well as the string length for pascal
1353 // strings.
1354 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001355 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001356 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001357
Chris Lattner5b183d82006-11-10 05:03:26 +00001358 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smithc67fdd42012-03-07 08:35:16 +00001359 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1360 Kind, Literal.Pascal, StrTy,
1361 &StringTokLocs[0],
1362 StringTokLocs.size());
1363 if (Literal.getUDSuffix().empty())
1364 return Owned(Lit);
1365
1366 // We're building a user-defined literal.
1367 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smith75b67d62012-03-08 01:34:56 +00001368 SourceLocation UDSuffixLoc =
1369 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1370 Literal.getUDSuffixOffset());
Richard Smithc67fdd42012-03-07 08:35:16 +00001371
Richard Smithbcc22fc2012-03-09 08:00:36 +00001372 // Make sure we're allowed user-defined literals here.
1373 if (!UDLScope)
1374 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1375
Richard Smithc67fdd42012-03-07 08:35:16 +00001376 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1377 // operator "" X (str, len)
1378 QualType SizeType = Context.getSizeType();
1379 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1380 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1381 StringTokLocs[0]);
1382 Expr *Args[] = { Lit, LenArg };
Richard Smithbcc22fc2012-03-09 08:00:36 +00001383 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1384 Args, StringTokLocs.back());
Chris Lattner5b183d82006-11-10 05:03:26 +00001385}
1386
John McCalldadc5752010-08-24 06:29:42 +00001387ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001388Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001389 SourceLocation Loc,
1390 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001391 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001392 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001393}
1394
John McCallf4cd4f92011-02-09 01:13:10 +00001395/// BuildDeclRefExpr - Build an expression that references a
1396/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001397ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001398Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001399 const DeclarationNameInfo &NameInfo,
1400 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001401 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00001402 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1403 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1404 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1405 CalleeTarget = IdentifyCUDATarget(Callee);
1406 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1407 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1408 << CalleeTarget << D->getIdentifier() << CallerTarget;
1409 Diag(D->getLocation(), diag::note_previous_decl)
1410 << D->getIdentifier();
1411 return ExprError();
1412 }
1413 }
1414
John McCall113bee02012-03-10 09:33:50 +00001415 bool refersToEnclosingScope =
1416 (CurContext != D->getDeclContext() &&
1417 D->getDeclContext()->isFunctionOrMethod());
1418
Eli Friedmanfa0df832012-02-02 03:46:19 +00001419 DeclRefExpr *E = DeclRefExpr::Create(Context,
1420 SS ? SS->getWithLocInContext(Context)
1421 : NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00001422 SourceLocation(),
1423 D, refersToEnclosingScope,
1424 NameInfo, Ty, VK);
Mike Stump11289f42009-09-09 15:08:12 +00001425
Eli Friedmanfa0df832012-02-02 03:46:19 +00001426 MarkDeclRefReferenced(E);
John McCall086a4642010-11-24 05:12:34 +00001427
Jordan Rose657b5f42012-09-28 22:21:35 +00001428 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1429 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1430 DiagnosticsEngine::Level Level =
1431 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1432 E->getLocStart());
1433 if (Level != DiagnosticsEngine::Ignored)
1434 getCurFunction()->recordUseOfWeak(E);
1435 }
1436
John McCall086a4642010-11-24 05:12:34 +00001437 // Just in case we're building an illegal pointer-to-member.
Richard Smithcaf33902011-10-10 18:28:20 +00001438 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1439 if (FD && FD->isBitField())
John McCall086a4642010-11-24 05:12:34 +00001440 E->setObjectKind(OK_BitField);
1441
1442 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001443}
1444
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001445/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001446/// possibly a list of template arguments.
1447///
1448/// If this produces template arguments, it is permitted to call
1449/// DecomposeTemplateName.
1450///
1451/// This actually loses a lot of source location information for
1452/// non-standard name kinds; we should consider preserving that in
1453/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001454void
1455Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1456 TemplateArgumentListInfo &Buffer,
1457 DeclarationNameInfo &NameInfo,
1458 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001459 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1460 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1461 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1462
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001463 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
John McCall10eae182009-11-30 22:42:35 +00001464 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001465 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001466
John McCall3e56fd42010-08-23 07:28:44 +00001467 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001468 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001469 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001470 TemplateArgs = &Buffer;
1471 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001472 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001473 TemplateArgs = 0;
1474 }
1475}
1476
John McCalld681c392009-12-16 08:11:27 +00001477/// Diagnose an empty lookup.
1478///
1479/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001480bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001481 CorrectionCandidateCallback &CCC,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001482 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001483 llvm::ArrayRef<Expr *> Args) {
John McCalld681c392009-12-16 08:11:27 +00001484 DeclarationName Name = R.getLookupName();
1485
John McCalld681c392009-12-16 08:11:27 +00001486 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001487 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001488 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1489 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001490 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001491 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001492 diagnostic_suggest = diag::err_undeclared_use_suggest;
1493 }
John McCalld681c392009-12-16 08:11:27 +00001494
Douglas Gregor598b08f2009-12-31 05:20:13 +00001495 // If the original lookup was an unqualified lookup, fake an
1496 // unqualified lookup. This is useful when (for example) the
1497 // original lookup would not have found something because it was a
1498 // dependent name.
David Blaikiec4c0e8a2012-05-28 01:26:45 +00001499 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1500 ? CurContext : 0;
Francois Pichetde232cb2011-11-25 01:10:54 +00001501 while (DC) {
John McCalld681c392009-12-16 08:11:27 +00001502 if (isa<CXXRecordDecl>(DC)) {
1503 LookupQualifiedName(R, DC);
1504
1505 if (!R.empty()) {
1506 // Don't give errors about ambiguities in this lookup.
1507 R.suppressDiagnostics();
1508
Francois Pichet857f9d62011-11-17 03:44:24 +00001509 // During a default argument instantiation the CurContext points
1510 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1511 // function parameter list, hence add an explicit check.
1512 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1513 ActiveTemplateInstantiations.back().Kind ==
1514 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCalld681c392009-12-16 08:11:27 +00001515 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1516 bool isInstance = CurMethod &&
1517 CurMethod->isInstance() &&
Francois Pichet857f9d62011-11-17 03:44:24 +00001518 DC == CurMethod->getParent() && !isDefaultArgument;
1519
John McCalld681c392009-12-16 08:11:27 +00001520
1521 // Give a code modification hint to insert 'this->'.
1522 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1523 // Actually quite difficult!
Nico Weberdf7dffb2012-06-20 20:21:42 +00001524 if (getLangOpts().MicrosoftMode)
1525 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001526 if (isInstance) {
Nico Weber3c10fb12012-06-22 16:39:39 +00001527 Diag(R.getNameLoc(), diagnostic) << Name
1528 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001529 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1530 CallsUndergoingInstantiation.back()->getCallee());
Nico Weber3c10fb12012-06-22 16:39:39 +00001531
1532
1533 CXXMethodDecl *DepMethod;
1534 if (CurMethod->getTemplatedKind() ==
1535 FunctionDecl::TK_FunctionTemplateSpecialization)
1536 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1537 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1538 else
1539 DepMethod = cast<CXXMethodDecl>(
1540 CurMethod->getInstantiatedFromMemberFunction());
1541 assert(DepMethod && "No template pattern found");
1542
1543 QualType DepThisType = DepMethod->getThisType(Context);
1544 CheckCXXThisCapture(R.getNameLoc());
1545 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1546 R.getNameLoc(), DepThisType, false);
1547 TemplateArgumentListInfo TList;
1548 if (ULE->hasExplicitTemplateArgs())
1549 ULE->copyTemplateArgumentsInto(TList);
1550
1551 CXXScopeSpec SS;
1552 SS.Adopt(ULE->getQualifierLoc());
1553 CXXDependentScopeMemberExpr *DepExpr =
1554 CXXDependentScopeMemberExpr::Create(
1555 Context, DepThis, DepThisType, true, SourceLocation(),
1556 SS.getWithLocInContext(Context),
1557 ULE->getTemplateKeywordLoc(), 0,
1558 R.getLookupNameInfo(),
1559 ULE->hasExplicitTemplateArgs() ? &TList : 0);
1560 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001561 } else {
John McCalld681c392009-12-16 08:11:27 +00001562 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001563 }
John McCalld681c392009-12-16 08:11:27 +00001564
1565 // Do we really want to note all of these?
1566 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1567 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1568
Francois Pichet857f9d62011-11-17 03:44:24 +00001569 // Return true if we are inside a default argument instantiation
1570 // and the found name refers to an instance member function, otherwise
1571 // the function calling DiagnoseEmptyLookup will try to create an
1572 // implicit member call and this is wrong for default argument.
1573 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1574 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1575 return true;
1576 }
1577
John McCalld681c392009-12-16 08:11:27 +00001578 // Tell the callee to try to recover.
1579 return false;
1580 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001581
1582 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001583 }
Francois Pichetde232cb2011-11-25 01:10:54 +00001584
1585 // In Microsoft mode, if we are performing lookup from within a friend
1586 // function definition declared at class scope then we must set
1587 // DC to the lexical parent to be able to search into the parent
1588 // class.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001589 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetde232cb2011-11-25 01:10:54 +00001590 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1591 DC->getLexicalParent()->isRecord())
1592 DC = DC->getLexicalParent();
1593 else
1594 DC = DC->getParent();
John McCalld681c392009-12-16 08:11:27 +00001595 }
1596
Douglas Gregor598b08f2009-12-31 05:20:13 +00001597 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001598 TypoCorrection Corrected;
1599 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001600 S, &SS, CCC))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001601 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1602 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001603 R.setLookupName(Corrected.getCorrection());
1604
Hans Wennborg38198de2011-07-12 08:45:31 +00001605 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001606 if (Corrected.isOverloaded()) {
1607 OverloadCandidateSet OCS(R.getNameLoc());
1608 OverloadCandidateSet::iterator Best;
1609 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1610 CDEnd = Corrected.end();
1611 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001612 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001613 dyn_cast<FunctionTemplateDecl>(*CD))
1614 AddTemplateOverloadCandidate(
1615 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001616 Args, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001617 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1618 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1619 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001620 Args, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001621 }
1622 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1623 case OR_Success:
1624 ND = Best->Function;
1625 break;
1626 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001627 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001628 }
1629 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001630 R.addDecl(ND);
1631 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001632 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001633 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1634 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001635 else
1636 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001637 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001638 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001639 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1640 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001641 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001642 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001643
1644 // Tell the callee to try to recover.
1645 return false;
1646 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001647
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001648 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001649 // FIXME: If we ended up with a typo for a type name or
1650 // Objective-C class name, we're in trouble because the parser
1651 // is in the wrong place to recover. Suggest the typo
1652 // correction, but don't make it a fix-it since we're not going
1653 // to recover well anyway.
1654 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001655 Diag(R.getNameLoc(), diagnostic_suggest)
1656 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001657 else
1658 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001659 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001660 << SS.getRange();
1661
1662 // Don't try to recover; it won't work.
1663 return true;
1664 }
1665 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001666 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001667 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001668 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001669 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001670 else
Douglas Gregor25363982010-01-01 00:15:04 +00001671 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001672 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001673 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001674 return true;
1675 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001676 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001677 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001678
1679 // Emit a special diagnostic for failed member lookups.
1680 // FIXME: computing the declaration context might fail here (?)
1681 if (!SS.isEmpty()) {
1682 Diag(R.getNameLoc(), diag::err_no_member)
1683 << Name << computeDeclContext(SS, false)
1684 << SS.getRange();
1685 return true;
1686 }
1687
John McCalld681c392009-12-16 08:11:27 +00001688 // Give up, we can't recover.
1689 Diag(R.getNameLoc(), diagnostic) << Name;
1690 return true;
1691}
1692
John McCalldadc5752010-08-24 06:29:42 +00001693ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001694 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001695 SourceLocation TemplateKWLoc,
John McCall24d18942010-08-24 22:52:39 +00001696 UnqualifiedId &Id,
1697 bool HasTrailingLParen,
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001698 bool IsAddressOfOperand,
1699 CorrectionCandidateCallback *CCC) {
Richard Trieuba63ce62011-09-09 01:45:06 +00001700 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCalle66edc12009-11-24 19:00:30 +00001701 "cannot be direct & operand and have a trailing lparen");
1702
1703 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001704 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001705
John McCall10eae182009-11-30 22:42:35 +00001706 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001707
1708 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001709 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001710 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001711 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001712
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001713 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001714 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001715 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001716
John McCalle66edc12009-11-24 19:00:30 +00001717 // C++ [temp.dep.expr]p3:
1718 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001719 // -- an identifier that was declared with a dependent type,
1720 // (note: handled after lookup)
1721 // -- a template-id that is dependent,
1722 // (note: handled in BuildTemplateIdExpr)
1723 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001724 // -- a nested-name-specifier that contains a class-name that
1725 // names a dependent type.
1726 // Determine whether this is a member of an unknown specialization;
1727 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001728 bool DependentID = false;
1729 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1730 Name.getCXXNameType()->isDependentType()) {
1731 DependentID = true;
1732 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001733 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001734 if (RequireCompleteDeclContext(SS, DC))
1735 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001736 } else {
1737 DependentID = true;
1738 }
1739 }
1740
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001741 if (DependentID)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001742 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1743 IsAddressOfOperand, TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001744
John McCalle66edc12009-11-24 19:00:30 +00001745 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001746 LookupResult R(*this, NameInfo,
1747 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1748 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001749 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001750 // Lookup the template name again to correctly establish the context in
1751 // which it was found. This is really unfortunate as we already did the
1752 // lookup to determine that it was a template name in the first place. If
1753 // this becomes a performance hit, we can work harder to preserve those
1754 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001755 bool MemberOfUnknownSpecialization;
1756 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1757 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001758
1759 if (MemberOfUnknownSpecialization ||
1760 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001761 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1762 IsAddressOfOperand, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001763 } else {
Benjamin Kramer46921442012-01-20 14:57:34 +00001764 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001765 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001766
Douglas Gregora5226932011-02-04 13:35:07 +00001767 // If the result might be in a dependent base class, this is a dependent
1768 // id-expression.
1769 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001770 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1771 IsAddressOfOperand, TemplateArgs);
1772
John McCalle66edc12009-11-24 19:00:30 +00001773 // If this reference is in an Objective-C method, then we need to do
1774 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001775 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001776 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001777 if (E.isInvalid())
1778 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001779
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001780 if (Expr *Ex = E.takeAs<Expr>())
1781 return Owned(Ex);
Steve Naroffebf4cb42008-06-02 23:03:37 +00001782 }
Chris Lattner59a25942008-03-31 00:36:02 +00001783 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001784
John McCalle66edc12009-11-24 19:00:30 +00001785 if (R.isAmbiguous())
1786 return ExprError();
1787
Douglas Gregor171c45a2009-02-18 21:56:37 +00001788 // Determine whether this name might be a candidate for
1789 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001790 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001791
John McCalle66edc12009-11-24 19:00:30 +00001792 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001793 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001794 // in C90, extension in C99, forbidden in C++).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001795 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
John McCalle66edc12009-11-24 19:00:30 +00001796 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1797 if (D) R.addDecl(D);
1798 }
1799
1800 // If this name wasn't predeclared and if this is not a function
1801 // call, diagnose the problem.
1802 if (R.empty()) {
Francois Pichetd8e4e412011-09-24 10:38:05 +00001803
1804 // In Microsoft mode, if we are inside a template class member function
1805 // and we can't resolve an identifier then assume the identifier is type
1806 // dependent. The goal is to postpone name lookup to instantiation time
1807 // to be able to search into type dependent base classes.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001808 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetd8e4e412011-09-24 10:38:05 +00001809 isa<CXXMethodDecl>(CurContext))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001810 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1811 IsAddressOfOperand, TemplateArgs);
Francois Pichetd8e4e412011-09-24 10:38:05 +00001812
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001813 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001814 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCalld681c392009-12-16 08:11:27 +00001815 return ExprError();
1816
1817 assert(!R.empty() &&
1818 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001819
1820 // If we found an Objective-C instance variable, let
1821 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001822 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001823 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1824 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001825 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanian44653702011-09-23 23:11:38 +00001826 // In a hopelessly buggy code, Objective-C instance variable
1827 // lookup fails and no expression will be built to reference it.
1828 if (!E.isInvalid() && !E.get())
1829 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001830 return E;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001831 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001832 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001833 }
Mike Stump11289f42009-09-09 15:08:12 +00001834
John McCalle66edc12009-11-24 19:00:30 +00001835 // This is guaranteed from this point on.
1836 assert(!R.empty() || ADL);
1837
John McCall2d74de92009-12-01 22:10:20 +00001838 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001839 // C++ [class.mfct.non-static]p3:
1840 // When an id-expression that is not part of a class member access
1841 // syntax and not used to form a pointer to member is used in the
1842 // body of a non-static member function of class X, if name lookup
1843 // resolves the name in the id-expression to a non-static non-type
1844 // member of some class C, the id-expression is transformed into a
1845 // class member access expression using (*this) as the
1846 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001847 //
1848 // But we don't actually need to do this for '&' operands if R
1849 // resolved to a function or overloaded function set, because the
1850 // expression is ill-formed if it actually works out to be a
1851 // non-static member function:
1852 //
1853 // C++ [expr.ref]p4:
1854 // Otherwise, if E1.E2 refers to a non-static member function. . .
1855 // [t]he expression can be used only as the left-hand operand of a
1856 // member function call.
1857 //
1858 // There are other safeguards against such uses, but it's important
1859 // to get this right here so that we don't end up making a
1860 // spuriously dependent expression if we're inside a dependent
1861 // instance method.
John McCall57500772009-12-16 12:17:52 +00001862 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001863 bool MightBeImplicitMember;
Richard Trieuba63ce62011-09-09 01:45:06 +00001864 if (!IsAddressOfOperand)
John McCall8d08b9b2010-08-27 09:08:28 +00001865 MightBeImplicitMember = true;
1866 else if (!SS.isEmpty())
1867 MightBeImplicitMember = false;
1868 else if (R.isOverloadedResult())
1869 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001870 else if (R.isUnresolvableResult())
1871 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001872 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001873 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1874 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001875
1876 if (MightBeImplicitMember)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001877 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1878 R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001879 }
1880
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001881 if (TemplateArgs || TemplateKWLoc.isValid())
1882 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001883
John McCalle66edc12009-11-24 19:00:30 +00001884 return BuildDeclarationNameExpr(SS, R, ADL);
1885}
1886
John McCall10eae182009-11-30 22:42:35 +00001887/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1888/// declaration name, generally during template instantiation.
1889/// There's a large number of things which don't need to be done along
1890/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001891ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001892Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001893 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001894 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001895 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001896 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1897 NameInfo, /*TemplateArgs=*/0);
John McCalle66edc12009-11-24 19:00:30 +00001898
John McCall0b66eb32010-05-01 00:40:08 +00001899 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001900 return ExprError();
1901
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001902 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001903 LookupQualifiedName(R, DC);
1904
1905 if (R.isAmbiguous())
1906 return ExprError();
1907
1908 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001909 Diag(NameInfo.getLoc(), diag::err_no_member)
1910 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001911 return ExprError();
1912 }
1913
1914 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1915}
1916
1917/// LookupInObjCMethod - The parser has read a name in, and Sema has
1918/// detected that we're currently inside an ObjC method. Perform some
1919/// additional lookup.
1920///
1921/// Ideally, most of this would be done by lookup, but there's
1922/// actually quite a lot of extra work involved.
1923///
1924/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001925ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001926Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001927 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001928 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001929 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001930
John McCalle66edc12009-11-24 19:00:30 +00001931 // There are two cases to handle here. 1) scoped lookup could have failed,
1932 // in which case we should look for an ivar. 2) scoped lookup could have
1933 // found a decl, but that decl is outside the current instance method (i.e.
1934 // a global variable). In these two cases, we do a lookup for an ivar with
1935 // this name, if the lookup sucedes, we replace it our current decl.
1936
1937 // If we're in a class method, we don't normally want to look for
1938 // ivars. But if we don't find anything else, and there's an
1939 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001940 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001941
1942 bool LookForIvars;
1943 if (Lookup.empty())
1944 LookForIvars = true;
1945 else if (IsClassMethod)
1946 LookForIvars = false;
1947 else
1948 LookForIvars = (Lookup.isSingleResult() &&
1949 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001950 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001951 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001952 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001953 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis4e8b1362011-10-19 02:25:16 +00001954 ObjCIvarDecl *IV = 0;
1955 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCalle66edc12009-11-24 19:00:30 +00001956 // Diagnose using an ivar in a class method.
1957 if (IsClassMethod)
1958 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1959 << IV->getDeclName());
1960
1961 // If we're referencing an invalid decl, just return this as a silent
1962 // error node. The error diagnostic was already emitted on the decl.
1963 if (IV->isInvalidDecl())
1964 return ExprError();
1965
1966 // Check if referencing a field with __attribute__((deprecated)).
1967 if (DiagnoseUseOfDecl(IV, Loc))
1968 return ExprError();
1969
1970 // Diagnose the use of an ivar outside of the declaring class.
1971 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001972 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001973 !getLangOpts().DebuggerSupport)
John McCalle66edc12009-11-24 19:00:30 +00001974 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1975
1976 // FIXME: This should use a new expr for a direct reference, don't
1977 // turn this into Self->ivar, just return a BareIVarExpr or something.
1978 IdentifierInfo &II = Context.Idents.get("self");
1979 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001980 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001981 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001982 CXXScopeSpec SelfScopeSpec;
Abramo Bagnara7945c982012-01-27 09:46:47 +00001983 SourceLocation TemplateKWLoc;
1984 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001985 SelfName, false, false);
1986 if (SelfExpr.isInvalid())
1987 return ExprError();
1988
John Wiegley01296292011-04-08 18:41:53 +00001989 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1990 if (SelfExpr.isInvalid())
1991 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001992
Eli Friedmanfa0df832012-02-02 03:46:19 +00001993 MarkAnyDeclReferenced(Loc, IV);
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00001994
1995 ObjCMethodFamily MF = CurMethod->getMethodFamily();
1996 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize)
1997 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
Jordan Rose657b5f42012-09-28 22:21:35 +00001998
1999 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2000 Loc,
2001 SelfExpr.take(),
2002 true, true);
2003
2004 if (getLangOpts().ObjCAutoRefCount) {
2005 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2006 DiagnosticsEngine::Level Level =
2007 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2008 if (Level != DiagnosticsEngine::Ignored)
2009 getCurFunction()->recordUseOfWeak(Result);
2010 }
Fariborz Jahanian4a675082012-10-03 17:55:29 +00002011 if (CurContext->isClosure())
2012 Diag(Loc, diag::warn_implicitly_retains_self)
2013 << FixItHint::CreateInsertion(Loc, "self->");
Jordan Rose657b5f42012-09-28 22:21:35 +00002014 }
2015
2016 return Owned(Result);
John McCalle66edc12009-11-24 19:00:30 +00002017 }
Chris Lattner87313662010-04-12 05:10:17 +00002018 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00002019 // We should warn if a local variable hides an ivar.
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00002020 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2021 ObjCInterfaceDecl *ClassDeclared;
2022 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2023 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor0b144e12011-12-15 00:29:59 +00002024 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00002025 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2026 }
John McCalle66edc12009-11-24 19:00:30 +00002027 }
Fariborz Jahanian028b9e12011-12-20 22:21:08 +00002028 } else if (Lookup.isSingleResult() &&
2029 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2030 // If accessing a stand-alone ivar in a class method, this is an error.
2031 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2032 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2033 << IV->getDeclName());
John McCalle66edc12009-11-24 19:00:30 +00002034 }
2035
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002036 if (Lookup.empty() && II && AllowBuiltinCreation) {
2037 // FIXME. Consolidate this with similar code in LookupName.
2038 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002039 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002040 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2041 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2042 S, Lookup.isForRedeclaration(),
2043 Lookup.getNameLoc());
2044 if (D) Lookup.addDecl(D);
2045 }
2046 }
2047 }
John McCalle66edc12009-11-24 19:00:30 +00002048 // Sentinel value saying that we didn't do anything special.
2049 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00002050}
John McCalld14a8642009-11-21 08:51:07 +00002051
John McCall16df1e52010-03-30 21:47:33 +00002052/// \brief Cast a base object to a member's actual type.
2053///
2054/// Logically this happens in three phases:
2055///
2056/// * First we cast from the base type to the naming class.
2057/// The naming class is the class into which we were looking
2058/// when we found the member; it's the qualifier type if a
2059/// qualifier was provided, and otherwise it's the base type.
2060///
2061/// * Next we cast from the naming class to the declaring class.
2062/// If the member we found was brought into a class's scope by
2063/// a using declaration, this is that class; otherwise it's
2064/// the class declaring the member.
2065///
2066/// * Finally we cast from the declaring class to the "true"
2067/// declaring class of the member. This conversion does not
2068/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00002069ExprResult
2070Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002071 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002072 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002073 NamedDecl *Member) {
2074 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2075 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00002076 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002077
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002078 QualType DestRecordType;
2079 QualType DestType;
2080 QualType FromRecordType;
2081 QualType FromType = From->getType();
2082 bool PointerConversions = false;
2083 if (isa<FieldDecl>(Member)) {
2084 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002085
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002086 if (FromType->getAs<PointerType>()) {
2087 DestType = Context.getPointerType(DestRecordType);
2088 FromRecordType = FromType->getPointeeType();
2089 PointerConversions = true;
2090 } else {
2091 DestType = DestRecordType;
2092 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002093 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002094 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2095 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00002096 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002097
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002098 DestType = Method->getThisType(Context);
2099 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002100
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002101 if (FromType->getAs<PointerType>()) {
2102 FromRecordType = FromType->getPointeeType();
2103 PointerConversions = true;
2104 } else {
2105 FromRecordType = FromType;
2106 DestType = DestRecordType;
2107 }
2108 } else {
2109 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00002110 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002111 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002112
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002113 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00002114 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002115
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002116 // If the unqualified types are the same, no conversion is necessary.
2117 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002118 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002119
John McCall16df1e52010-03-30 21:47:33 +00002120 SourceRange FromRange = From->getSourceRange();
2121 SourceLocation FromLoc = FromRange.getBegin();
2122
Eli Friedmanbe4b3632011-09-27 21:58:52 +00002123 ExprValueKind VK = From->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002124
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002125 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002126 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002127 // class name.
2128 //
2129 // If the member was a qualified name and the qualified referred to a
2130 // specific base subobject type, we'll cast to that intermediate type
2131 // first and then to the object in which the member is declared. That allows
2132 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2133 //
2134 // class Base { public: int x; };
2135 // class Derived1 : public Base { };
2136 // class Derived2 : public Base { };
2137 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2138 //
2139 // void VeryDerived::f() {
2140 // x = 17; // error: ambiguous base subobjects
2141 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2142 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002143 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002144 QualType QType = QualType(Qualifier->getAsType(), 0);
2145 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2146 assert(QType->isRecordType() && "lookup done with non-record type");
2147
2148 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2149
2150 // In C++98, the qualifier type doesn't actually have to be a base
2151 // type of the object type, in which case we just ignore it.
2152 // Otherwise build the appropriate casts.
2153 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002154 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002155 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002156 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002157 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002158
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002159 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002160 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002161 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2162 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002163
2164 FromType = QType;
2165 FromRecordType = QRecordType;
2166
2167 // If the qualifier type was the same as the destination type,
2168 // we're done.
2169 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002170 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002171 }
2172 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002173
John McCall16df1e52010-03-30 21:47:33 +00002174 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002175
John McCall16df1e52010-03-30 21:47:33 +00002176 // If we actually found the member through a using declaration, cast
2177 // down to the using declaration's type.
2178 //
2179 // Pointer equality is fine here because only one declaration of a
2180 // class ever has member declarations.
2181 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2182 assert(isa<UsingShadowDecl>(FoundDecl));
2183 QualType URecordType = Context.getTypeDeclType(
2184 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2185
2186 // We only need to do this if the naming-class to declaring-class
2187 // conversion is non-trivial.
2188 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2189 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002190 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002191 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002192 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002193 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002194
John McCall16df1e52010-03-30 21:47:33 +00002195 QualType UType = URecordType;
2196 if (PointerConversions)
2197 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002198 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2199 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002200 FromType = UType;
2201 FromRecordType = URecordType;
2202 }
2203
2204 // We don't do access control for the conversion from the
2205 // declaring class to the true declaring class.
2206 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002207 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002208
John McCallcf142162010-08-07 06:22:56 +00002209 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002210 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2211 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002212 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002213 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002214
John Wiegley01296292011-04-08 18:41:53 +00002215 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2216 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002217}
Douglas Gregor3256d042009-06-30 15:47:41 +00002218
John McCalle66edc12009-11-24 19:00:30 +00002219bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002220 const LookupResult &R,
2221 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002222 // Only when used directly as the postfix-expression of a call.
2223 if (!HasTrailingLParen)
2224 return false;
2225
2226 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002227 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002228 return false;
2229
2230 // Only in C++ or ObjC++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002231 if (!getLangOpts().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002232 return false;
2233
2234 // Turn off ADL when we find certain kinds of declarations during
2235 // normal lookup:
2236 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2237 NamedDecl *D = *I;
2238
2239 // C++0x [basic.lookup.argdep]p3:
2240 // -- a declaration of a class member
2241 // Since using decls preserve this property, we check this on the
2242 // original decl.
John McCall57500772009-12-16 12:17:52 +00002243 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002244 return false;
2245
2246 // C++0x [basic.lookup.argdep]p3:
2247 // -- a block-scope function declaration that is not a
2248 // using-declaration
2249 // NOTE: we also trigger this for function templates (in fact, we
2250 // don't check the decl type at all, since all other decl types
2251 // turn off ADL anyway).
2252 if (isa<UsingShadowDecl>(D))
2253 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2254 else if (D->getDeclContext()->isFunctionOrMethod())
2255 return false;
2256
2257 // C++0x [basic.lookup.argdep]p3:
2258 // -- a declaration that is neither a function or a function
2259 // template
2260 // And also for builtin functions.
2261 if (isa<FunctionDecl>(D)) {
2262 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2263
2264 // But also builtin functions.
2265 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2266 return false;
2267 } else if (!isa<FunctionTemplateDecl>(D))
2268 return false;
2269 }
2270
2271 return true;
2272}
2273
2274
John McCalld14a8642009-11-21 08:51:07 +00002275/// Diagnoses obvious problems with the use of the given declaration
2276/// as an expression. This is only actually called for lookups that
2277/// were not overloaded, and it doesn't promise that the declaration
2278/// will in fact be used.
2279static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002280 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002281 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2282 return true;
2283 }
2284
2285 if (isa<ObjCInterfaceDecl>(D)) {
2286 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2287 return true;
2288 }
2289
2290 if (isa<NamespaceDecl>(D)) {
2291 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2292 return true;
2293 }
2294
2295 return false;
2296}
2297
John McCalldadc5752010-08-24 06:29:42 +00002298ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002299Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002300 LookupResult &R,
2301 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002302 // If this is a single, fully-resolved result and we don't need ADL,
2303 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002304 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002305 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2306 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002307
2308 // We only need to check the declaration if there's exactly one
2309 // result, because in the overloaded case the results can only be
2310 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002311 if (R.isSingleResult() &&
2312 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002313 return ExprError();
2314
John McCall58cc69d2010-01-27 01:50:18 +00002315 // Otherwise, just build an unresolved lookup expression. Suppress
2316 // any lookup-related diagnostics; we'll hash these out later, when
2317 // we've picked a target.
2318 R.suppressDiagnostics();
2319
John McCalld14a8642009-11-21 08:51:07 +00002320 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002321 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002322 SS.getWithLocInContext(Context),
2323 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002324 NeedsADL, R.isOverloadedResult(),
2325 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002326
2327 return Owned(ULE);
2328}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002329
John McCalld14a8642009-11-21 08:51:07 +00002330/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002331ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002332Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002333 const DeclarationNameInfo &NameInfo,
2334 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002335 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002336 assert(!isa<FunctionTemplateDecl>(D) &&
2337 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002338
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002339 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002340 if (CheckDeclInExpr(*this, Loc, D))
2341 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002342
Douglas Gregore7488b92009-12-01 16:58:18 +00002343 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2344 // Specifically diagnose references to class templates that are missing
2345 // a template argument list.
2346 Diag(Loc, diag::err_template_decl_ref)
2347 << Template << SS.getRange();
2348 Diag(Template->getLocation(), diag::note_template_decl_here);
2349 return ExprError();
2350 }
2351
2352 // Make sure that we're referring to a value.
2353 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2354 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002355 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002356 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002357 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002358 return ExprError();
2359 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002360
Douglas Gregor171c45a2009-02-18 21:56:37 +00002361 // Check whether this declaration can be used. Note that we suppress
2362 // this check when we're going to perform argument-dependent lookup
2363 // on this function name, because this might not be the function
2364 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002365 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002366 return ExprError();
2367
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002368 // Only create DeclRefExpr's for valid Decl's.
2369 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002370 return ExprError();
2371
John McCallf3a88602011-02-03 08:15:49 +00002372 // Handle members of anonymous structs and unions. If we got here,
2373 // and the reference is to a class member indirect field, then this
2374 // must be the subject of a pointer-to-member expression.
2375 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2376 if (!indirectField->isCXXClassMember())
2377 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2378 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002379
Eli Friedman9bb33f52012-02-03 02:04:35 +00002380 {
John McCallf4cd4f92011-02-09 01:13:10 +00002381 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002382 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002383
2384 switch (D->getKind()) {
2385 // Ignore all the non-ValueDecl kinds.
2386#define ABSTRACT_DECL(kind)
2387#define VALUE(type, base)
2388#define DECL(type, base) \
2389 case Decl::type:
2390#include "clang/AST/DeclNodes.inc"
2391 llvm_unreachable("invalid value decl kind");
John McCallf4cd4f92011-02-09 01:13:10 +00002392
2393 // These shouldn't make it here.
2394 case Decl::ObjCAtDefsField:
2395 case Decl::ObjCIvar:
2396 llvm_unreachable("forming non-member reference to ivar?");
John McCallf4cd4f92011-02-09 01:13:10 +00002397
2398 // Enum constants are always r-values and never references.
2399 // Unresolved using declarations are dependent.
2400 case Decl::EnumConstant:
2401 case Decl::UnresolvedUsingValue:
2402 valueKind = VK_RValue;
2403 break;
2404
2405 // Fields and indirect fields that got here must be for
2406 // pointer-to-member expressions; we just call them l-values for
2407 // internal consistency, because this subexpression doesn't really
2408 // exist in the high-level semantics.
2409 case Decl::Field:
2410 case Decl::IndirectField:
David Blaikiebbafb8a2012-03-11 07:00:24 +00002411 assert(getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002412 "building reference to field in C?");
2413
2414 // These can't have reference type in well-formed programs, but
2415 // for internal consistency we do this anyway.
2416 type = type.getNonReferenceType();
2417 valueKind = VK_LValue;
2418 break;
2419
2420 // Non-type template parameters are either l-values or r-values
2421 // depending on the type.
2422 case Decl::NonTypeTemplateParm: {
2423 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2424 type = reftype->getPointeeType();
2425 valueKind = VK_LValue; // even if the parameter is an r-value reference
2426 break;
2427 }
2428
2429 // For non-references, we need to strip qualifiers just in case
2430 // the template parameter was declared as 'const int' or whatever.
2431 valueKind = VK_RValue;
2432 type = type.getUnqualifiedType();
2433 break;
2434 }
2435
2436 case Decl::Var:
2437 // In C, "extern void blah;" is valid and is an r-value.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002438 if (!getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002439 !type.hasQualifiers() &&
2440 type->isVoidType()) {
2441 valueKind = VK_RValue;
2442 break;
2443 }
2444 // fallthrough
2445
2446 case Decl::ImplicitParam:
Douglas Gregor812d8f62012-02-18 05:51:20 +00002447 case Decl::ParmVar: {
John McCallf4cd4f92011-02-09 01:13:10 +00002448 // These are always l-values.
2449 valueKind = VK_LValue;
2450 type = type.getNonReferenceType();
Eli Friedman9bb33f52012-02-03 02:04:35 +00002451
Douglas Gregor812d8f62012-02-18 05:51:20 +00002452 // FIXME: Does the addition of const really only apply in
2453 // potentially-evaluated contexts? Since the variable isn't actually
2454 // captured in an unevaluated context, it seems that the answer is no.
David Blaikie131fcb42012-08-06 22:47:24 +00002455 if (!isUnevaluatedContext()) {
Douglas Gregor812d8f62012-02-18 05:51:20 +00002456 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2457 if (!CapturedType.isNull())
2458 type = CapturedType;
2459 }
2460
John McCallf4cd4f92011-02-09 01:13:10 +00002461 break;
Douglas Gregor812d8f62012-02-18 05:51:20 +00002462 }
2463
John McCallf4cd4f92011-02-09 01:13:10 +00002464 case Decl::Function: {
Eli Friedman34866c72012-08-31 00:14:07 +00002465 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2466 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2467 type = Context.BuiltinFnTy;
2468 valueKind = VK_RValue;
2469 break;
2470 }
2471 }
2472
John McCall2979fe02011-04-12 00:42:48 +00002473 const FunctionType *fty = type->castAs<FunctionType>();
2474
2475 // If we're referring to a function with an __unknown_anytype
2476 // result type, make the entire expression __unknown_anytype.
2477 if (fty->getResultType() == Context.UnknownAnyTy) {
2478 type = Context.UnknownAnyTy;
2479 valueKind = VK_RValue;
2480 break;
2481 }
2482
John McCallf4cd4f92011-02-09 01:13:10 +00002483 // Functions are l-values in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002484 if (getLangOpts().CPlusPlus) {
John McCallf4cd4f92011-02-09 01:13:10 +00002485 valueKind = VK_LValue;
2486 break;
2487 }
2488
2489 // C99 DR 316 says that, if a function type comes from a
2490 // function definition (without a prototype), that type is only
2491 // used for checking compatibility. Therefore, when referencing
2492 // the function, we pretend that we don't have the full function
2493 // type.
John McCall2979fe02011-04-12 00:42:48 +00002494 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2495 isa<FunctionProtoType>(fty))
2496 type = Context.getFunctionNoProtoType(fty->getResultType(),
2497 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002498
2499 // Functions are r-values in C.
2500 valueKind = VK_RValue;
2501 break;
2502 }
2503
2504 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002505 // If we're referring to a method with an __unknown_anytype
2506 // result type, make the entire expression __unknown_anytype.
2507 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002508 if (const FunctionProtoType *proto
2509 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002510 if (proto->getResultType() == Context.UnknownAnyTy) {
2511 type = Context.UnknownAnyTy;
2512 valueKind = VK_RValue;
2513 break;
2514 }
2515
John McCallf4cd4f92011-02-09 01:13:10 +00002516 // C++ methods are l-values if static, r-values if non-static.
2517 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2518 valueKind = VK_LValue;
2519 break;
2520 }
2521 // fallthrough
2522
2523 case Decl::CXXConversion:
2524 case Decl::CXXDestructor:
2525 case Decl::CXXConstructor:
2526 valueKind = VK_RValue;
2527 break;
2528 }
2529
2530 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2531 }
Chris Lattner17ed4872006-11-20 04:58:19 +00002532}
Chris Lattnere168f762006-11-10 05:29:30 +00002533
John McCall2979fe02011-04-12 00:42:48 +00002534ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002535 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002536
Chris Lattnere168f762006-11-10 05:29:30 +00002537 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002538 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002539 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2540 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
Nico Weber3a691a32012-06-23 02:07:59 +00002541 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
Chris Lattner6307f192008-08-10 01:53:14 +00002542 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002543 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002544
Chris Lattnera81a0272008-01-12 08:14:25 +00002545 // Pre-defined identifiers are of type char[x], where x is the length of the
2546 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002547
Anders Carlsson2fb08242009-09-08 18:24:21 +00002548 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002549 if (!currentDecl && getCurBlock())
2550 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002551 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002552 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002553 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002554 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002555
Anders Carlsson0b209a82009-09-11 01:22:35 +00002556 QualType ResTy;
2557 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2558 ResTy = Context.DependentTy;
2559 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002560 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002561
Anders Carlsson0b209a82009-09-11 01:22:35 +00002562 llvm::APInt LengthI(32, Length + 1);
Nico Weber3052abd2012-06-29 16:39:58 +00002563 if (IT == PredefinedExpr::LFunction)
Nico Weber3a691a32012-06-23 02:07:59 +00002564 ResTy = Context.WCharTy.withConst();
2565 else
2566 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002567 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2568 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002569 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002570}
2571
Richard Smithbcc22fc2012-03-09 08:00:36 +00002572ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002573 SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002574 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002575 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002576 if (Invalid)
2577 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002578
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002579 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002580 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002581 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002582 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002583
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002584 QualType Ty;
Seth Cantrell02f86052012-01-18 12:27:06 +00002585 if (Literal.isWide())
2586 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002587 else if (Literal.isUTF16())
Seth Cantrell02f86052012-01-18 12:27:06 +00002588 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002589 else if (Literal.isUTF32())
Seth Cantrell02f86052012-01-18 12:27:06 +00002590 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002591 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell02f86052012-01-18 12:27:06 +00002592 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002593 else
2594 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002595
Douglas Gregorfb65e592011-07-27 05:40:30 +00002596 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2597 if (Literal.isWide())
2598 Kind = CharacterLiteral::Wide;
2599 else if (Literal.isUTF16())
2600 Kind = CharacterLiteral::UTF16;
2601 else if (Literal.isUTF32())
2602 Kind = CharacterLiteral::UTF32;
2603
Richard Smith75b67d62012-03-08 01:34:56 +00002604 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2605 Tok.getLocation());
2606
2607 if (Literal.getUDSuffix().empty())
2608 return Owned(Lit);
2609
2610 // We're building a user-defined literal.
2611 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2612 SourceLocation UDSuffixLoc =
2613 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2614
Richard Smithbcc22fc2012-03-09 08:00:36 +00002615 // Make sure we're allowed user-defined literals here.
2616 if (!UDLScope)
2617 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2618
Richard Smith75b67d62012-03-08 01:34:56 +00002619 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2620 // operator "" X (ch)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002621 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2622 llvm::makeArrayRef(&Lit, 1),
2623 Tok.getLocation());
Steve Naroffae4143e2007-04-26 20:39:23 +00002624}
2625
Ted Kremeneke65b0862012-03-06 20:05:56 +00002626ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2627 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2628 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2629 Context.IntTy, Loc));
2630}
2631
Richard Smith39570d002012-03-08 08:45:32 +00002632static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2633 QualType Ty, SourceLocation Loc) {
2634 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2635
2636 using llvm::APFloat;
2637 APFloat Val(Format);
2638
2639 APFloat::opStatus result = Literal.GetFloatValue(Val);
2640
2641 // Overflow is always an error, but underflow is only an error if
2642 // we underflowed to zero (APFloat reports denormals as underflow).
2643 if ((result & APFloat::opOverflow) ||
2644 ((result & APFloat::opUnderflow) && Val.isZero())) {
2645 unsigned diagnostic;
2646 SmallString<20> buffer;
2647 if (result & APFloat::opOverflow) {
2648 diagnostic = diag::warn_float_overflow;
2649 APFloat::getLargest(Format).toString(buffer);
2650 } else {
2651 diagnostic = diag::warn_float_underflow;
2652 APFloat::getSmallest(Format).toString(buffer);
2653 }
2654
2655 S.Diag(Loc, diagnostic)
2656 << Ty
2657 << StringRef(buffer.data(), buffer.size());
2658 }
2659
2660 bool isExact = (result == APFloat::opOK);
2661 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2662}
2663
Richard Smithbcc22fc2012-03-09 08:00:36 +00002664ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002665 // Fast path for a single digit (which is quite common). A single digit
Richard Smithbcc22fc2012-03-09 08:00:36 +00002666 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Steve Narofff2fb89e2007-03-13 20:29:44 +00002667 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002668 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002669 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Steve Narofff2fb89e2007-03-13 20:29:44 +00002670 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002671
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002672 SmallString<128> SpellingBuffer;
2673 // NumericLiteralParser wants to overread by one character. Add padding to
2674 // the buffer in case the token is copied to the buffer. If getSpelling()
2675 // returns a StringRef to the memory buffer, it should have a null char at
2676 // the EOF, so it is also safe.
2677 SpellingBuffer.resize(Tok.getLength() + 1);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002678
Chris Lattner67ca9252007-05-21 01:08:44 +00002679 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002680 bool Invalid = false;
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002681 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002682 if (Invalid)
2683 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002684
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002685 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002686 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002687 return ExprError();
2688
Richard Smith39570d002012-03-08 08:45:32 +00002689 if (Literal.hasUDSuffix()) {
2690 // We're building a user-defined literal.
2691 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2692 SourceLocation UDSuffixLoc =
2693 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2694
Richard Smithbcc22fc2012-03-09 08:00:36 +00002695 // Make sure we're allowed user-defined literals here.
2696 if (!UDLScope)
2697 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smith39570d002012-03-08 08:45:32 +00002698
Richard Smithbcc22fc2012-03-09 08:00:36 +00002699 QualType CookedTy;
Richard Smith39570d002012-03-08 08:45:32 +00002700 if (Literal.isFloatingLiteral()) {
2701 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2702 // long double, the literal is treated as a call of the form
2703 // operator "" X (f L)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002704 CookedTy = Context.LongDoubleTy;
Richard Smith39570d002012-03-08 08:45:32 +00002705 } else {
2706 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2707 // unsigned long long, the literal is treated as a call of the form
2708 // operator "" X (n ULL)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002709 CookedTy = Context.UnsignedLongLongTy;
Richard Smith39570d002012-03-08 08:45:32 +00002710 }
2711
Richard Smithbcc22fc2012-03-09 08:00:36 +00002712 DeclarationName OpName =
2713 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2714 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2715 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2716
2717 // Perform literal operator lookup to determine if we're building a raw
2718 // literal or a cooked one.
2719 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2720 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2721 /*AllowRawAndTemplate*/true)) {
2722 case LOLR_Error:
2723 return ExprError();
2724
2725 case LOLR_Cooked: {
2726 Expr *Lit;
2727 if (Literal.isFloatingLiteral()) {
2728 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2729 } else {
2730 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2731 if (Literal.GetIntegerValue(ResultVal))
2732 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2733 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2734 Tok.getLocation());
2735 }
2736 return BuildLiteralOperatorCall(R, OpNameInfo,
2737 llvm::makeArrayRef(&Lit, 1),
2738 Tok.getLocation());
2739 }
2740
2741 case LOLR_Raw: {
2742 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2743 // literal is treated as a call of the form
2744 // operator "" X ("n")
2745 SourceLocation TokLoc = Tok.getLocation();
2746 unsigned Length = Literal.getUDSuffixOffset();
2747 QualType StrTy = Context.getConstantArrayType(
2748 Context.CharTy, llvm::APInt(32, Length + 1),
2749 ArrayType::Normal, 0);
2750 Expr *Lit = StringLiteral::Create(
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002751 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
Richard Smithbcc22fc2012-03-09 08:00:36 +00002752 /*Pascal*/false, StrTy, &TokLoc, 1);
2753 return BuildLiteralOperatorCall(R, OpNameInfo,
2754 llvm::makeArrayRef(&Lit, 1), TokLoc);
2755 }
2756
2757 case LOLR_Template:
2758 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2759 // template), L is treated as a call fo the form
2760 // operator "" X <'c1', 'c2', ... 'ck'>()
2761 // where n is the source character sequence c1 c2 ... ck.
2762 TemplateArgumentListInfo ExplicitArgs;
2763 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2764 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2765 llvm::APSInt Value(CharBits, CharIsUnsigned);
2766 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002767 Value = TokSpelling[I];
Benjamin Kramer6003ad52012-06-07 15:09:51 +00002768 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smithbcc22fc2012-03-09 08:00:36 +00002769 TemplateArgumentLocInfo ArgInfo;
2770 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2771 }
2772 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2773 Tok.getLocation(), &ExplicitArgs);
2774 }
2775
2776 llvm_unreachable("unexpected literal operator lookup result");
Richard Smith39570d002012-03-08 08:45:32 +00002777 }
2778
Chris Lattner1c20a172007-08-26 03:42:43 +00002779 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002780
Chris Lattner1c20a172007-08-26 03:42:43 +00002781 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002782 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002783 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002784 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002785 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002786 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002787 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002788 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002789
Richard Smith39570d002012-03-08 08:45:32 +00002790 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002791
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002792 if (Ty == Context.DoubleTy) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002793 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002794 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002795 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002796 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002797 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002798 }
2799 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002800 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002801 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002802 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002803 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002804
Dmitri Gribenko1cd23052012-09-24 18:19:21 +00002805 // 'long long' is a C99 or C++11 feature.
2806 if (!getLangOpts().C99 && Literal.isLongLong) {
2807 if (getLangOpts().CPlusPlus)
2808 Diag(Tok.getLocation(),
2809 getLangOpts().CPlusPlus0x ?
2810 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
2811 else
2812 Diag(Tok.getLocation(), diag::ext_c99_longlong);
2813 }
Neil Boothac582c52007-08-29 22:00:19 +00002814
Chris Lattner67ca9252007-05-21 01:08:44 +00002815 // Get the value in the widest-possible width.
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002816 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2817 // The microsoft literal suffix extensions support 128-bit literals, which
2818 // may be wider than [u]intmax_t.
2819 if (Literal.isMicrosoftInteger && MaxWidth < 128)
2820 MaxWidth = 128;
2821 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002822
Chris Lattner67ca9252007-05-21 01:08:44 +00002823 if (Literal.GetIntegerValue(ResultVal)) {
2824 // If this value didn't fit into uintmax_t, warn and force to ull.
2825 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002826 Ty = Context.UnsignedLongLongTy;
2827 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002828 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002829 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002830 // If this value fits into a ULL, try to figure out what else it fits into
2831 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002832
Chris Lattner67ca9252007-05-21 01:08:44 +00002833 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2834 // be an unsigned int.
2835 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2836
2837 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002838 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002839 if (!Literal.isLong && !Literal.isLongLong) {
2840 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00002841 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002842
Chris Lattner67ca9252007-05-21 01:08:44 +00002843 // Does it fit in a unsigned int?
2844 if (ResultVal.isIntN(IntSize)) {
2845 // Does it fit in a signed int?
2846 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002847 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002848 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002849 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002850 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002851 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002852 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002853
Chris Lattner67ca9252007-05-21 01:08:44 +00002854 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002855 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002856 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002857
Chris Lattner67ca9252007-05-21 01:08:44 +00002858 // Does it fit in a unsigned long?
2859 if (ResultVal.isIntN(LongSize)) {
2860 // Does it fit in a signed long?
2861 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002862 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002863 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002864 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002865 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002866 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002867 }
2868
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002869 // Check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002870 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002871 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002872
Chris Lattner67ca9252007-05-21 01:08:44 +00002873 // Does it fit in a unsigned long long?
2874 if (ResultVal.isIntN(LongLongSize)) {
2875 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002876 // To be compatible with MSVC, hex integer literals ending with the
2877 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002878 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00002879 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002880 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002881 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002882 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002883 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002884 }
2885 }
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002886
2887 // If it doesn't fit in unsigned long long, and we're using Microsoft
2888 // extensions, then its a 128-bit integer literal.
2889 if (Ty.isNull() && Literal.isMicrosoftInteger) {
2890 if (Literal.isUnsigned)
2891 Ty = Context.UnsignedInt128Ty;
2892 else
2893 Ty = Context.Int128Ty;
2894 Width = 128;
2895 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002896
Chris Lattner67ca9252007-05-21 01:08:44 +00002897 // If we still couldn't decide a type, we probably have something that
2898 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002899 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002900 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002901 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00002902 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002903 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002904
Chris Lattner55258cf2008-05-09 05:59:00 +00002905 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002906 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002907 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002908 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002909 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002910
Chris Lattner1c20a172007-08-26 03:42:43 +00002911 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2912 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002913 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002914 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002915
2916 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002917}
2918
Richard Trieuba63ce62011-09-09 01:45:06 +00002919ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002920 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002921 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002922}
2923
Chandler Carruth62da79c2011-05-26 08:53:12 +00002924static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2925 SourceLocation Loc,
2926 SourceRange ArgRange) {
2927 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2928 // scalar or vector data type argument..."
2929 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2930 // type (C99 6.2.5p18) or void.
2931 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2932 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2933 << T << ArgRange;
2934 return true;
2935 }
2936
2937 assert((T->isVoidType() || !T->isIncompleteType()) &&
2938 "Scalar types should always be complete");
2939 return false;
2940}
2941
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002942static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2943 SourceLocation Loc,
2944 SourceRange ArgRange,
2945 UnaryExprOrTypeTrait TraitKind) {
2946 // C99 6.5.3.4p1:
2947 if (T->isFunctionType()) {
2948 // alignof(function) is allowed as an extension.
2949 if (TraitKind == UETT_SizeOf)
2950 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2951 return false;
2952 }
2953
2954 // Allow sizeof(void)/alignof(void) as an extension.
2955 if (T->isVoidType()) {
2956 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2957 return false;
2958 }
2959
2960 return true;
2961}
2962
2963static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2964 SourceLocation Loc,
2965 SourceRange ArgRange,
2966 UnaryExprOrTypeTrait TraitKind) {
John McCallf2538342012-07-31 05:14:30 +00002967 // Reject sizeof(interface) and sizeof(interface<proto>) if the
2968 // runtime doesn't allow it.
2969 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002970 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2971 << T << (TraitKind == UETT_SizeOf)
2972 << ArgRange;
2973 return true;
2974 }
2975
2976 return false;
2977}
2978
Chandler Carruth14502c22011-05-26 08:53:10 +00002979/// \brief Check the constrains on expression operands to unary type expression
2980/// and type traits.
2981///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002982/// Completes any types necessary and validates the constraints on the operand
2983/// expression. The logic mostly mirrors the type-based overload, but may modify
2984/// the expression as it completes the type for that expression through template
2985/// instantiation, etc.
Richard Trieuba63ce62011-09-09 01:45:06 +00002986bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth14502c22011-05-26 08:53:10 +00002987 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002988 QualType ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002989
2990 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2991 // the result is the size of the referenced type."
2992 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2993 // result shall be the alignment of the referenced type."
2994 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2995 ExprTy = Ref->getPointeeType();
2996
2997 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002998 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2999 E->getSourceRange());
Chandler Carruth7c430c02011-05-27 01:33:31 +00003000
3001 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00003002 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3003 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00003004 return false;
3005
Richard Trieuba63ce62011-09-09 01:45:06 +00003006 if (RequireCompleteExprType(E,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003007 diag::err_sizeof_alignof_incomplete_type,
3008 ExprKind, E->getSourceRange()))
Chandler Carruth7c430c02011-05-27 01:33:31 +00003009 return true;
3010
3011 // Completeing the expression's type may have changed it.
Richard Trieuba63ce62011-09-09 01:45:06 +00003012 ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00003013 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3014 ExprTy = Ref->getPointeeType();
3015
Richard Trieuba63ce62011-09-09 01:45:06 +00003016 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3017 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00003018 return true;
3019
Nico Weber0870deb2011-06-15 02:47:03 +00003020 if (ExprKind == UETT_SizeOf) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003021 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Weber0870deb2011-06-15 02:47:03 +00003022 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3023 QualType OType = PVD->getOriginalType();
3024 QualType Type = PVD->getType();
3025 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003026 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Weber0870deb2011-06-15 02:47:03 +00003027 << Type << OType;
3028 Diag(PVD->getLocation(), diag::note_declared_at);
3029 }
3030 }
3031 }
3032 }
3033
Chandler Carruth7c430c02011-05-27 01:33:31 +00003034 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00003035}
3036
3037/// \brief Check the constraints on operands to unary expression and type
3038/// traits.
3039///
3040/// This will complete any types necessary, and validate the various constraints
3041/// on those operands.
3042///
Steve Naroff71b59a92007-06-04 22:22:31 +00003043/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00003044/// C99 6.3.2.1p[2-4] all state:
3045/// Except when it is the operand of the sizeof operator ...
3046///
3047/// C++ [expr.sizeof]p4
3048/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3049/// standard conversions are not applied to the operand of sizeof.
3050///
3051/// This policy is followed for all of the unary trait expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00003052bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00003053 SourceLocation OpLoc,
3054 SourceRange ExprRange,
3055 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003056 if (ExprType->isDependentType())
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003057 return false;
3058
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003059 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3060 // the result is the size of the referenced type."
3061 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3062 // result shall be the alignment of the referenced type."
Richard Trieuba63ce62011-09-09 01:45:06 +00003063 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3064 ExprType = Ref->getPointeeType();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003065
Chandler Carruth62da79c2011-05-26 08:53:12 +00003066 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00003067 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003068
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003069 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00003070 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003071 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00003072 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003073
Richard Trieuba63ce62011-09-09 01:45:06 +00003074 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003075 diag::err_sizeof_alignof_incomplete_type,
3076 ExprKind, ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00003077 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003078
Richard Trieuba63ce62011-09-09 01:45:06 +00003079 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003080 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00003081 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003082
Chris Lattner62975a72009-04-24 00:30:45 +00003083 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00003084}
3085
Chandler Carruth14502c22011-05-26 08:53:10 +00003086static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00003087 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003088
Mike Stump11289f42009-09-09 15:08:12 +00003089 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00003090 if (isa<DeclRefExpr>(E))
3091 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003092
3093 // Cannot know anything else if the expression is dependent.
3094 if (E->isTypeDependent())
3095 return false;
3096
Douglas Gregor71235ec2009-05-02 02:18:30 +00003097 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003098 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3099 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003100 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00003101 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00003102
3103 // Alignment of a field access is always okay, so long as it isn't a
3104 // bit-field.
3105 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00003106 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003107 return false;
3108
Chandler Carruth14502c22011-05-26 08:53:10 +00003109 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003110}
3111
Chandler Carruth14502c22011-05-26 08:53:10 +00003112bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00003113 E = E->IgnoreParens();
3114
3115 // Cannot know anything else if the expression is dependent.
3116 if (E->isTypeDependent())
3117 return false;
3118
Chandler Carruth14502c22011-05-26 08:53:10 +00003119 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00003120}
3121
Douglas Gregor0950e412009-03-13 21:01:28 +00003122/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00003123ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003124Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3125 SourceLocation OpLoc,
3126 UnaryExprOrTypeTrait ExprKind,
3127 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00003128 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00003129 return ExprError();
3130
John McCallbcd03502009-12-07 02:54:59 +00003131 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00003132
Douglas Gregor0950e412009-03-13 21:01:28 +00003133 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00003134 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00003135 return ExprError();
3136
3137 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003138 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3139 Context.getSizeType(),
3140 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003141}
3142
3143/// \brief Build a sizeof or alignof expression given an expression
3144/// operand.
John McCalldadc5752010-08-24 06:29:42 +00003145ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00003146Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3147 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00003148 ExprResult PE = CheckPlaceholderExpr(E);
3149 if (PE.isInvalid())
3150 return ExprError();
3151
3152 E = PE.get();
3153
Douglas Gregor0950e412009-03-13 21:01:28 +00003154 // Verify that the operand is valid.
3155 bool isInvalid = false;
3156 if (E->isTypeDependent()) {
3157 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003158 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003159 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003160 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003161 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00003162 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00003163 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00003164 isInvalid = true;
3165 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00003166 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00003167 }
3168
3169 if (isInvalid)
3170 return ExprError();
3171
Eli Friedmane0afc982012-01-21 01:01:51 +00003172 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3173 PE = TranformToPotentiallyEvaluated(E);
3174 if (PE.isInvalid()) return ExprError();
3175 E = PE.take();
3176 }
3177
Douglas Gregor0950e412009-03-13 21:01:28 +00003178 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00003179 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00003180 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00003181 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003182}
3183
Peter Collingbournee190dee2011-03-11 19:24:49 +00003184/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3185/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00003186/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00003187ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003188Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003189 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00003190 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00003191 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003192 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00003193
Richard Trieuba63ce62011-09-09 01:45:06 +00003194 if (IsType) {
John McCallbcd03502009-12-07 02:54:59 +00003195 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00003196 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003197 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00003198 }
Sebastian Redl6f282892008-11-11 17:56:53 +00003199
Douglas Gregor0950e412009-03-13 21:01:28 +00003200 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00003201 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003202 return Result;
Chris Lattnere168f762006-11-10 05:29:30 +00003203}
3204
John Wiegley01296292011-04-08 18:41:53 +00003205static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003206 bool IsReal) {
John Wiegley01296292011-04-08 18:41:53 +00003207 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00003208 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00003209
John McCall34376a62010-12-04 03:47:34 +00003210 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00003211 if (V.get()->getObjectKind() != OK_Ordinary) {
3212 V = S.DefaultLvalueConversion(V.take());
3213 if (V.isInvalid())
3214 return QualType();
3215 }
John McCall34376a62010-12-04 03:47:34 +00003216
Chris Lattnere267f5d2007-08-26 05:39:26 +00003217 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00003218 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00003219 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00003220
Chris Lattnere267f5d2007-08-26 05:39:26 +00003221 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00003222 if (V.get()->getType()->isArithmeticType())
3223 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003224
John McCall36226622010-10-12 02:09:17 +00003225 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00003226 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00003227 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003228 if (PR.get() != V.get()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003229 V = PR;
Richard Trieuba63ce62011-09-09 01:45:06 +00003230 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall36226622010-10-12 02:09:17 +00003231 }
3232
Chris Lattnere267f5d2007-08-26 05:39:26 +00003233 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00003234 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuba63ce62011-09-09 01:45:06 +00003235 << (IsReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00003236 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00003237}
3238
3239
Chris Lattnere168f762006-11-10 05:29:30 +00003240
John McCalldadc5752010-08-24 06:29:42 +00003241ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003242Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003243 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00003244 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00003245 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003246 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003247 case tok::plusplus: Opc = UO_PostInc; break;
3248 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003249 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003250
Sebastian Redla9351792012-02-11 23:51:47 +00003251 // Since this might is a postfix expression, get rid of ParenListExprs.
3252 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3253 if (Result.isInvalid()) return ExprError();
3254 Input = Result.take();
3255
John McCallb268a282010-08-23 23:25:46 +00003256 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003257}
3258
John McCallf2538342012-07-31 05:14:30 +00003259/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3260///
3261/// \return true on error
3262static bool checkArithmeticOnObjCPointer(Sema &S,
3263 SourceLocation opLoc,
3264 Expr *op) {
3265 assert(op->getType()->isObjCObjectPointerType());
3266 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3267 return false;
3268
3269 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3270 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3271 << op->getSourceRange();
3272 return true;
3273}
3274
John McCalldadc5752010-08-24 06:29:42 +00003275ExprResult
John McCallb268a282010-08-23 23:25:46 +00003276Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3277 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003278 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003279 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003280 if (Result.isInvalid()) return ExprError();
3281 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003282
John McCallb268a282010-08-23 23:25:46 +00003283 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003284
David Blaikiebbafb8a2012-03-11 07:00:24 +00003285 if (getLangOpts().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003286 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003287 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003288 Context.DependentTy,
3289 VK_LValue, OK_Ordinary,
3290 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003291 }
3292
David Blaikiebbafb8a2012-03-11 07:00:24 +00003293 if (getLangOpts().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003294 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003295 LHSExp->getType()->isEnumeralType() ||
3296 RHSExp->getType()->isRecordType() ||
Ted Kremeneke65b0862012-03-06 20:05:56 +00003297 RHSExp->getType()->isEnumeralType()) &&
3298 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCallb268a282010-08-23 23:25:46 +00003299 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003300 }
3301
John McCallb268a282010-08-23 23:25:46 +00003302 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003303}
3304
John McCalldadc5752010-08-24 06:29:42 +00003305ExprResult
John McCallb268a282010-08-23 23:25:46 +00003306Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003307 Expr *Idx, SourceLocation RLoc) {
John McCallb268a282010-08-23 23:25:46 +00003308 Expr *LHSExp = Base;
3309 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003310
Chris Lattner36d572b2007-07-16 00:14:47 +00003311 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003312 if (!LHSExp->getType()->getAs<VectorType>()) {
3313 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3314 if (Result.isInvalid())
3315 return ExprError();
3316 LHSExp = Result.take();
3317 }
3318 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3319 if (Result.isInvalid())
3320 return ExprError();
3321 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003322
Chris Lattner36d572b2007-07-16 00:14:47 +00003323 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003324 ExprValueKind VK = VK_LValue;
3325 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003326
Steve Naroffc1aadb12007-03-28 21:49:40 +00003327 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003328 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003329 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003330 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003331 Expr *BaseExpr, *IndexExpr;
3332 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003333 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3334 BaseExpr = LHSExp;
3335 IndexExpr = RHSExp;
3336 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003337 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003338 BaseExpr = LHSExp;
3339 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003340 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003341 } else if (const ObjCObjectPointerType *PTy =
John McCallf2538342012-07-31 05:14:30 +00003342 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003343 BaseExpr = LHSExp;
3344 IndexExpr = RHSExp;
John McCallf2538342012-07-31 05:14:30 +00003345
3346 // Use custom logic if this should be the pseudo-object subscript
3347 // expression.
3348 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3349 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3350
Steve Naroff7cae42b2009-07-10 23:34:53 +00003351 ResultType = PTy->getPointeeType();
John McCallf2538342012-07-31 05:14:30 +00003352 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3353 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3354 << ResultType << BaseExpr->getSourceRange();
3355 return ExprError();
3356 }
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00003357 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3358 // Handle the uncommon case of "123[Ptr]".
3359 BaseExpr = RHSExp;
3360 IndexExpr = LHSExp;
3361 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003362 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003363 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003364 // Handle the uncommon case of "123[Ptr]".
3365 BaseExpr = RHSExp;
3366 IndexExpr = LHSExp;
3367 ResultType = PTy->getPointeeType();
John McCallf2538342012-07-31 05:14:30 +00003368 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3369 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3370 << ResultType << BaseExpr->getSourceRange();
3371 return ExprError();
3372 }
John McCall9dd450b2009-09-21 23:43:11 +00003373 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003374 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003375 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003376 VK = LHSExp->getValueKind();
3377 if (VK != VK_RValue)
3378 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003379
Chris Lattner36d572b2007-07-16 00:14:47 +00003380 // FIXME: need to deal with const...
3381 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003382 } else if (LHSTy->isArrayType()) {
3383 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003384 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003385 // wasn't promoted because of the C90 rule that doesn't
3386 // allow promoting non-lvalue arrays. Warn, then
3387 // force the promotion here.
3388 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3389 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003390 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3391 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003392 LHSTy = LHSExp->getType();
3393
3394 BaseExpr = LHSExp;
3395 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003396 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003397 } else if (RHSTy->isArrayType()) {
3398 // Same as previous, except for 123[f().a] case
3399 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3400 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003401 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3402 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003403 RHSTy = RHSExp->getType();
3404
3405 BaseExpr = RHSExp;
3406 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003407 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003408 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003409 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3410 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003411 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003412 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003413 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003414 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3415 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003416
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003417 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003418 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3419 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003420 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3421
Douglas Gregorac1fb652009-03-24 19:52:54 +00003422 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003423 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3424 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003425 // incomplete types are not object types.
3426 if (ResultType->isFunctionType()) {
3427 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3428 << ResultType << BaseExpr->getSourceRange();
3429 return ExprError();
3430 }
Mike Stump11289f42009-09-09 15:08:12 +00003431
David Blaikiebbafb8a2012-03-11 07:00:24 +00003432 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003433 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003434 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3435 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003436
3437 // C forbids expressions of unqualified void type from being l-values.
3438 // See IsCForbiddenLValueType.
3439 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003440 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003441 RequireCompleteType(LLoc, ResultType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003442 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003443 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003444
John McCall4bc41ae2010-11-18 19:01:18 +00003445 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003446 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003447
Mike Stump4e1f26a2009-02-19 03:04:26 +00003448 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003449 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003450}
3451
John McCalldadc5752010-08-24 06:29:42 +00003452ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003453 FunctionDecl *FD,
3454 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003455 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003456 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003457 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003458 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003459 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003460 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003461 return ExprError();
3462 }
3463
3464 if (Param->hasUninstantiatedDefaultArg()) {
3465 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003466
Richard Smith505df232012-07-22 23:45:10 +00003467 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3468 Param);
3469
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003470 // Instantiate the expression.
3471 MultiLevelTemplateArgumentList ArgList
3472 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003473
Nico Weber44887f62010-11-29 18:19:25 +00003474 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003475 = ArgList.getInnermost();
Richard Smith80934652012-07-16 01:09:10 +00003476 InstantiatingTemplate Inst(*this, CallLoc, Param,
3477 ArrayRef<TemplateArgument>(Innermost.first,
3478 Innermost.second));
Richard Smith8a874c92012-07-08 02:38:24 +00003479 if (Inst)
3480 return ExprError();
Anders Carlsson355933d2009-08-25 03:49:14 +00003481
Nico Weber44887f62010-11-29 18:19:25 +00003482 ExprResult Result;
3483 {
3484 // C++ [dcl.fct.default]p5:
3485 // The names in the [default argument] expression are bound, and
3486 // the semantic constraints are checked, at the point where the
3487 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003488 ContextRAII SavedContext(*this, FD);
Douglas Gregora86bc002012-02-16 21:36:18 +00003489 LocalInstantiationScope Local(*this);
Nico Weber44887f62010-11-29 18:19:25 +00003490 Result = SubstExpr(UninstExpr, ArgList);
3491 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003492 if (Result.isInvalid())
3493 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003494
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003495 // Check the expression as an initializer for the parameter.
3496 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003497 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003498 InitializationKind Kind
3499 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003500 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003501 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003502
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003503 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003504 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003505 if (Result.isInvalid())
3506 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003507
David Blaikief68e8092012-04-30 18:21:31 +00003508 Expr *Arg = Result.takeAs<Expr>();
David Blaikie18e9ac72012-05-15 21:57:38 +00003509 CheckImplicitConversions(Arg, Param->getOuterLocStart());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003510 // Build the default argument expression.
David Blaikief68e8092012-04-30 18:21:31 +00003511 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson355933d2009-08-25 03:49:14 +00003512 }
3513
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003514 // If the default expression creates temporaries, we need to
3515 // push them to the current stack of expression temporaries so they'll
3516 // be properly destroyed.
3517 // FIXME: We should really be rebuilding the default argument with new
3518 // bound temporaries; see the comment in PR5810.
John McCall28fc7092011-11-10 05:35:25 +00003519 // We don't need to do that with block decls, though, because
3520 // blocks in default argument expression can never capture anything.
3521 if (isa<ExprWithCleanups>(Param->getInit())) {
3522 // Set the "needs cleanups" bit regardless of whether there are
3523 // any explicit objects.
John McCall31168b02011-06-15 23:02:42 +00003524 ExprNeedsCleanups = true;
John McCall28fc7092011-11-10 05:35:25 +00003525
3526 // Append all the objects to the cleanup list. Right now, this
3527 // should always be a no-op, because blocks in default argument
3528 // expressions should never be able to capture anything.
3529 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3530 "default argument expression has capturing blocks?");
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003531 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003532
3533 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003534 // Just mark all of the declarations in this potentially-evaluated expression
3535 // as being "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +00003536 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3537 /*SkipLocalVariables=*/true);
Douglas Gregor033f6752009-12-23 23:03:06 +00003538 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003539}
3540
Richard Smith55ce3522012-06-25 20:30:08 +00003541
3542Sema::VariadicCallType
3543Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3544 Expr *Fn) {
3545 if (Proto && Proto->isVariadic()) {
3546 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3547 return VariadicConstructor;
3548 else if (Fn && Fn->getType()->isBlockPointerType())
3549 return VariadicBlock;
3550 else if (FDecl) {
3551 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3552 if (Method->isInstance())
3553 return VariadicMethod;
3554 }
3555 return VariadicFunction;
3556 }
3557 return VariadicDoesNotApply;
3558}
3559
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003560/// ConvertArgumentsForCall - Converts the arguments specified in
3561/// Args/NumArgs to the parameter types of the function FDecl with
3562/// function prototype Proto. Call is the call expression itself, and
3563/// Fn is the function expression. For a C++ member function, this
3564/// routine does not attempt to convert the object argument. Returns
3565/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003566bool
3567Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003568 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003569 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003570 Expr **Args, unsigned NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003571 SourceLocation RParenLoc,
3572 bool IsExecConfig) {
John McCallbebede42011-02-26 05:39:39 +00003573 // Bail out early if calling a builtin with custom typechecking.
3574 // We don't need to do this in the
3575 if (FDecl)
3576 if (unsigned ID = FDecl->getBuiltinID())
3577 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3578 return false;
3579
Mike Stump4e1f26a2009-02-19 03:04:26 +00003580 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003581 // assignment, to the types of the corresponding parameter, ...
3582 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003583 bool Invalid = false;
Peter Collingbourne740afe22011-10-02 23:49:20 +00003584 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003585 unsigned FnKind = Fn->getType()->isBlockPointerType()
3586 ? 1 /* block */
3587 : (IsExecConfig ? 3 /* kernel function (exec config) */
3588 : 0 /* function */);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003589
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003590 // If too few arguments are available (and we don't have default
3591 // arguments for the remaining parameters), don't make the call.
3592 if (NumArgs < NumArgsInProto) {
Peter Collingbourne740afe22011-10-02 23:49:20 +00003593 if (NumArgs < MinArgs) {
Richard Smith10ff50d2012-05-11 05:16:41 +00003594 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3595 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3596 ? diag::err_typecheck_call_too_few_args_one
3597 : diag::err_typecheck_call_too_few_args_at_least_one)
3598 << FnKind
3599 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3600 else
3601 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3602 ? diag::err_typecheck_call_too_few_args
3603 : diag::err_typecheck_call_too_few_args_at_least)
3604 << FnKind
3605 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003606
3607 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003608 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003609 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3610 << FDecl;
3611
3612 return true;
3613 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003614 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003615 }
3616
3617 // If too many are passed and not variadic, error on the extras and drop
3618 // them.
3619 if (NumArgs > NumArgsInProto) {
3620 if (!Proto->isVariadic()) {
Richard Smithd72da152012-05-15 06:21:54 +00003621 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3622 Diag(Args[NumArgsInProto]->getLocStart(),
3623 MinArgs == NumArgsInProto
3624 ? diag::err_typecheck_call_too_many_args_one
3625 : diag::err_typecheck_call_too_many_args_at_most_one)
3626 << FnKind
3627 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3628 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3629 Args[NumArgs-1]->getLocEnd());
3630 else
3631 Diag(Args[NumArgsInProto]->getLocStart(),
3632 MinArgs == NumArgsInProto
3633 ? diag::err_typecheck_call_too_many_args
3634 : diag::err_typecheck_call_too_many_args_at_most)
3635 << FnKind
3636 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3637 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3638 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003639
3640 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003641 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003642 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3643 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003644
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003645 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003646 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003647 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003648 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003649 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003650 SmallVector<Expr *, 8> AllArgs;
Richard Smith55ce3522012-06-25 20:30:08 +00003651 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3652
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003653 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003654 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003655 if (Invalid)
3656 return true;
3657 unsigned TotalNumArgs = AllArgs.size();
3658 for (unsigned i = 0; i < TotalNumArgs; ++i)
3659 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003660
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003661 return false;
3662}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003663
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003664bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3665 FunctionDecl *FDecl,
3666 const FunctionProtoType *Proto,
3667 unsigned FirstProtoArg,
3668 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003669 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003670 VariadicCallType CallType,
3671 bool AllowExplicit) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003672 unsigned NumArgsInProto = Proto->getNumArgs();
3673 unsigned NumArgsToCheck = NumArgs;
3674 bool Invalid = false;
3675 if (NumArgs != NumArgsInProto)
3676 // Use default arguments for missing arguments
3677 NumArgsToCheck = NumArgsInProto;
3678 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003679 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003680 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003681 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003682
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003683 Expr *Arg;
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003684 ParmVarDecl *Param;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003685 if (ArgIx < NumArgs) {
3686 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003687
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003688 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedman3164fb12009-03-22 22:00:50 +00003689 ProtoArgType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003690 diag::err_call_incomplete_argument, Arg))
Eli Friedman3164fb12009-03-22 22:00:50 +00003691 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003692
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003693 // Pass the argument
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003694 Param = 0;
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003695 if (FDecl && i < FDecl->getNumParams())
3696 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003697
John McCall4124c492011-10-17 18:40:02 +00003698 // Strip the unbridged-cast placeholder expression off, if applicable.
3699 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3700 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3701 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3702 Arg = stripARCUnbridgedCast(Arg);
3703
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003704 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003705 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003706 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3707 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003708 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003709 SourceLocation(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00003710 Owned(Arg),
3711 /*TopLevelOfInitList=*/false,
3712 AllowExplicit);
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003713 if (ArgE.isInvalid())
3714 return true;
3715
3716 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003717 } else {
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003718 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003719
John McCalldadc5752010-08-24 06:29:42 +00003720 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003721 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003722 if (ArgExpr.isInvalid())
3723 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003724
Anders Carlsson355933d2009-08-25 03:49:14 +00003725 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003726 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003727
3728 // Check for array bounds violations for each argument to the call. This
3729 // check only triggers warnings when the argument isn't a more complex Expr
3730 // with its own checking, such as a BinaryOperator.
3731 CheckArrayAccess(Arg);
3732
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003733 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3734 CheckStaticArrayArgument(CallLoc, Param, Arg);
3735
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003736 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003737 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003738
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003739 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003740 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003741 // Assume that extern "C" functions with variadic arguments that
3742 // return __unknown_anytype aren't *really* variadic.
3743 if (Proto->getResultType() == Context.UnknownAnyTy &&
3744 FDecl && FDecl->isExternC()) {
3745 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3746 ExprResult arg;
3747 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3748 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3749 else
3750 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3751 Invalid |= arg.isInvalid();
3752 AllArgs.push_back(arg.take());
3753 }
3754
3755 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3756 } else {
3757 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003758 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3759 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003760 Invalid |= Arg.isInvalid();
3761 AllArgs.push_back(Arg.take());
3762 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003763 }
Ted Kremenekd41f3462011-09-26 23:36:13 +00003764
3765 // Check for array bounds violations.
3766 for (unsigned i = ArgIx; i != NumArgs; ++i)
3767 CheckArrayAccess(Args[i]);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003768 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003769 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003770}
3771
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003772static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3773 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3774 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3775 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3776 << ATL->getLocalSourceRange();
3777}
3778
3779/// CheckStaticArrayArgument - If the given argument corresponds to a static
3780/// array parameter, check that it is non-null, and that if it is formed by
3781/// array-to-pointer decay, the underlying array is sufficiently large.
3782///
3783/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3784/// array type derivation, then for each call to the function, the value of the
3785/// corresponding actual argument shall provide access to the first element of
3786/// an array with at least as many elements as specified by the size expression.
3787void
3788Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3789 ParmVarDecl *Param,
3790 const Expr *ArgExpr) {
3791 // Static array parameters are not supported in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003792 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003793 return;
3794
3795 QualType OrigTy = Param->getOriginalType();
3796
3797 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3798 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3799 return;
3800
3801 if (ArgExpr->isNullPointerConstant(Context,
3802 Expr::NPC_NeverValueDependent)) {
3803 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3804 DiagnoseCalleeStaticArrayParam(*this, Param);
3805 return;
3806 }
3807
3808 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3809 if (!CAT)
3810 return;
3811
3812 const ConstantArrayType *ArgCAT =
3813 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3814 if (!ArgCAT)
3815 return;
3816
3817 if (ArgCAT->getSize().ult(CAT->getSize())) {
3818 Diag(CallLoc, diag::warn_static_array_too_small)
3819 << ArgExpr->getSourceRange()
3820 << (unsigned) ArgCAT->getSize().getZExtValue()
3821 << (unsigned) CAT->getSize().getZExtValue();
3822 DiagnoseCalleeStaticArrayParam(*this, Param);
3823 }
3824}
3825
John McCall2979fe02011-04-12 00:42:48 +00003826/// Given a function expression of unknown-any type, try to rebuild it
3827/// to have a function type.
3828static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3829
Steve Naroff83895f72007-09-16 03:34:24 +00003830/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003831/// This provides the location of the left/right parens and a list of comma
3832/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003833ExprResult
John McCallb268a282010-08-23 23:25:46 +00003834Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003835 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003836 Expr *ExecConfig, bool IsExecConfig) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003837 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003838 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003839 if (Result.isInvalid()) return ExprError();
3840 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003841
David Blaikiebbafb8a2012-03-11 07:00:24 +00003842 if (getLangOpts().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003843 // If this is a pseudo-destructor expression, build the call immediately.
3844 if (isa<CXXPseudoDestructorExpr>(Fn)) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003845 if (!ArgExprs.empty()) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003846 // Pseudo-destructor calls should not have any arguments.
3847 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003848 << FixItHint::CreateRemoval(
Benjamin Kramerc215e762012-08-24 11:54:20 +00003849 SourceRange(ArgExprs[0]->getLocStart(),
3850 ArgExprs.back()->getLocEnd()));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003851 }
Mike Stump11289f42009-09-09 15:08:12 +00003852
Benjamin Kramerc215e762012-08-24 11:54:20 +00003853 return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(),
3854 Context.VoidTy, VK_RValue,
3855 RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003856 }
Mike Stump11289f42009-09-09 15:08:12 +00003857
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003858 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003859 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003860 // FIXME: Will need to cache the results of name lookup (including ADL) in
3861 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003862 bool Dependent = false;
3863 if (Fn->isTypeDependent())
3864 Dependent = true;
Benjamin Kramerc215e762012-08-24 11:54:20 +00003865 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003866 Dependent = true;
3867
Peter Collingbourne41f85462011-02-09 21:07:24 +00003868 if (Dependent) {
3869 if (ExecConfig) {
3870 return Owned(new (Context) CUDAKernelCallExpr(
Benjamin Kramerc215e762012-08-24 11:54:20 +00003871 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003872 Context.DependentTy, VK_RValue, RParenLoc));
3873 } else {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003874 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003875 Context.DependentTy, VK_RValue,
3876 RParenLoc));
3877 }
3878 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003879
3880 // Determine whether this is a call to an object (C++ [over.call.object]).
3881 if (Fn->getType()->isRecordType())
Benjamin Kramerc215e762012-08-24 11:54:20 +00003882 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
3883 ArgExprs.data(),
3884 ArgExprs.size(), RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003885
John McCall2979fe02011-04-12 00:42:48 +00003886 if (Fn->getType() == Context.UnknownAnyTy) {
3887 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3888 if (result.isInvalid()) return ExprError();
3889 Fn = result.take();
3890 }
3891
John McCall0009fcc2011-04-26 20:42:42 +00003892 if (Fn->getType() == Context.BoundMemberTy) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003893 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3894 ArgExprs.size(), RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003895 }
John McCall0009fcc2011-04-26 20:42:42 +00003896 }
John McCall10eae182009-11-30 22:42:35 +00003897
John McCall0009fcc2011-04-26 20:42:42 +00003898 // Check for overloaded calls. This can happen even in C due to extensions.
3899 if (Fn->getType() == Context.OverloadTy) {
3900 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3901
Douglas Gregorcda22702011-10-13 18:10:35 +00003902 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregorf4a06c22011-10-13 18:26:27 +00003903 if (!find.HasFormOfMemberPointer) {
John McCall0009fcc2011-04-26 20:42:42 +00003904 OverloadExpr *ovl = find.Expression;
3905 if (isa<UnresolvedLookupExpr>(ovl)) {
3906 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
Benjamin Kramerc215e762012-08-24 11:54:20 +00003907 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(),
3908 ArgExprs.size(), RParenLoc, ExecConfig);
John McCall0009fcc2011-04-26 20:42:42 +00003909 } else {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003910 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3911 ArgExprs.size(), RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003912 }
3913 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003914 }
3915
Douglas Gregore254f902009-02-04 00:32:51 +00003916 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregord8fb1e32011-12-01 01:37:36 +00003917 if (Fn->getType() == Context.UnknownAnyTy) {
3918 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3919 if (result.isInvalid()) return ExprError();
3920 Fn = result.take();
3921 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003922
Eli Friedmane14b1992009-12-26 03:35:45 +00003923 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003924
John McCall57500772009-12-16 12:17:52 +00003925 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003926 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3927 if (UnOp->getOpcode() == UO_AddrOf)
3928 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3929
John McCall57500772009-12-16 12:17:52 +00003930 if (isa<DeclRefExpr>(NakedFn))
3931 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003932 else if (isa<MemberExpr>(NakedFn))
3933 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003934
Benjamin Kramerc215e762012-08-24 11:54:20 +00003935 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(),
3936 ArgExprs.size(), RParenLoc, ExecConfig,
3937 IsExecConfig);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003938}
3939
3940ExprResult
3941Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003942 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbourne41f85462011-02-09 21:07:24 +00003943 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3944 if (!ConfigDecl)
3945 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3946 << "cudaConfigureCall");
3947 QualType ConfigQTy = ConfigDecl->getType();
3948
3949 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCall113bee02012-03-10 09:33:50 +00003950 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedmanfa0df832012-02-02 03:46:19 +00003951 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003952
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003953 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3954 /*IsExecConfig=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003955}
3956
Tanya Lattner55808c12011-06-04 00:47:47 +00003957/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3958///
3959/// __builtin_astype( value, dst type )
3960///
Richard Trieuba63ce62011-09-09 01:45:06 +00003961ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00003962 SourceLocation BuiltinLoc,
3963 SourceLocation RParenLoc) {
3964 ExprValueKind VK = VK_RValue;
3965 ExprObjectKind OK = OK_Ordinary;
Richard Trieuba63ce62011-09-09 01:45:06 +00003966 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3967 QualType SrcTy = E->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00003968 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3969 return ExprError(Diag(BuiltinLoc,
3970 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003971 << DstTy
3972 << SrcTy
Richard Trieuba63ce62011-09-09 01:45:06 +00003973 << E->getSourceRange());
3974 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieucfc491d2011-08-02 04:35:43 +00003975 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003976}
3977
John McCall57500772009-12-16 12:17:52 +00003978/// BuildResolvedCallExpr - Build a call to a resolved expression,
3979/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003980/// unary-convert to an expression of function-pointer or
3981/// block-pointer type.
3982///
3983/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003984ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003985Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3986 SourceLocation LParenLoc,
3987 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003988 SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003989 Expr *Config, bool IsExecConfig) {
John McCall2d74de92009-12-01 22:10:20 +00003990 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
Eli Friedman34866c72012-08-31 00:14:07 +00003991 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
John McCall2d74de92009-12-01 22:10:20 +00003992
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003993 // Promote the function operand.
Eli Friedman34866c72012-08-31 00:14:07 +00003994 // We special-case function promotion here because we only allow promoting
3995 // builtin functions to function pointers in the callee of a call.
3996 ExprResult Result;
3997 if (BuiltinID &&
3998 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
3999 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4000 CK_BuiltinFnToFnPtr).take();
4001 } else {
4002 Result = UsualUnaryConversions(Fn);
4003 }
John Wiegley01296292011-04-08 18:41:53 +00004004 if (Result.isInvalid())
4005 return ExprError();
4006 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004007
Chris Lattner08464942007-12-28 05:29:59 +00004008 // Make the call expr early, before semantic checks. This guarantees cleanup
4009 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00004010 CallExpr *TheCall;
Eric Christopher13586ab2012-05-30 01:14:28 +00004011 if (Config)
Peter Collingbourne41f85462011-02-09 21:07:24 +00004012 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4013 cast<CallExpr>(Config),
Benjamin Kramerc215e762012-08-24 11:54:20 +00004014 llvm::makeArrayRef(Args,NumArgs),
Peter Collingbourne41f85462011-02-09 21:07:24 +00004015 Context.BoolTy,
4016 VK_RValue,
4017 RParenLoc);
Eric Christopher13586ab2012-05-30 01:14:28 +00004018 else
Peter Collingbourne41f85462011-02-09 21:07:24 +00004019 TheCall = new (Context) CallExpr(Context, Fn,
Benjamin Kramerc215e762012-08-24 11:54:20 +00004020 llvm::makeArrayRef(Args, NumArgs),
Peter Collingbourne41f85462011-02-09 21:07:24 +00004021 Context.BoolTy,
4022 VK_RValue,
4023 RParenLoc);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004024
John McCallbebede42011-02-26 05:39:39 +00004025 // Bail out early if calling a builtin with custom typechecking.
4026 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4027 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4028
John McCall31996342011-04-07 08:22:57 +00004029 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004030 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00004031 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004032 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4033 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00004034 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00004035 if (FuncT == 0)
4036 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4037 << Fn->getType() << Fn->getSourceRange());
4038 } else if (const BlockPointerType *BPT =
4039 Fn->getType()->getAs<BlockPointerType>()) {
4040 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4041 } else {
John McCall31996342011-04-07 08:22:57 +00004042 // Handle calls to expressions of unknown-any type.
4043 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00004044 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00004045 if (rewrite.isInvalid()) return ExprError();
4046 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00004047 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00004048 goto retry;
4049 }
4050
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004051 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4052 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00004053 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004054
David Blaikiebbafb8a2012-03-11 07:00:24 +00004055 if (getLangOpts().CUDA) {
Peter Collingbourne4b66c472011-02-23 01:53:29 +00004056 if (Config) {
4057 // CUDA: Kernel calls must be to global functions
4058 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4059 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4060 << FDecl->getName() << Fn->getSourceRange());
4061
4062 // CUDA: Kernel function must have 'void' return type
4063 if (!FuncT->getResultType()->isVoidType())
4064 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4065 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne34a20b02011-10-02 23:49:15 +00004066 } else {
4067 // CUDA: Calls to global functions must be configured
4068 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4069 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4070 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne4b66c472011-02-23 01:53:29 +00004071 }
4072 }
4073
Eli Friedman3164fb12009-03-22 22:00:50 +00004074 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004075 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004076 Fn->getLocStart(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004077 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00004078 return ExprError();
4079
Chris Lattner08464942007-12-28 05:29:59 +00004080 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004081 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00004082 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004083
Richard Smith55ce3522012-06-25 20:30:08 +00004084 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4085 if (Proto) {
John McCallb268a282010-08-23 23:25:46 +00004086 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00004087 RParenLoc, IsExecConfig))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004088 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00004089 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004090 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004091
Douglas Gregord8e97de2009-04-02 15:37:10 +00004092 if (FDecl) {
4093 // Check if we have too few/too many template arguments, based
4094 // on our knowledge of the function definition.
4095 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00004096 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Richard Smith55ce3522012-06-25 20:30:08 +00004097 Proto = Def->getType()->getAs<FunctionProtoType>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00004098 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004099 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4100 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004101 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00004102
4103 // If the function we're calling isn't a function prototype, but we have
4104 // a function prototype from a prior declaratiom, use that prototype.
4105 if (!FDecl->hasPrototype())
4106 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00004107 }
4108
Steve Naroff0b661582007-08-28 23:30:39 +00004109 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00004110 for (unsigned i = 0; i != NumArgs; i++) {
4111 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00004112
4113 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004114 InitializedEntity Entity
4115 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00004116 Proto->getArgType(i),
4117 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00004118 ExprResult ArgE = PerformCopyInitialization(Entity,
4119 SourceLocation(),
4120 Owned(Arg));
4121 if (ArgE.isInvalid())
4122 return true;
4123
4124 Arg = ArgE.takeAs<Expr>();
4125
4126 } else {
John Wiegley01296292011-04-08 18:41:53 +00004127 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4128
4129 if (ArgE.isInvalid())
4130 return true;
4131
4132 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00004133 }
4134
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004135 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor83025412010-10-26 05:45:40 +00004136 Arg->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004137 diag::err_call_incomplete_argument, Arg))
Douglas Gregor83025412010-10-26 05:45:40 +00004138 return ExprError();
4139
Chris Lattner08464942007-12-28 05:29:59 +00004140 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00004141 }
Steve Naroffae4143e2007-04-26 20:39:23 +00004142 }
Chris Lattner08464942007-12-28 05:29:59 +00004143
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004144 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4145 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004146 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4147 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004148
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00004149 // Check for sentinels
4150 if (NDecl)
4151 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004152
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004153 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004154 if (FDecl) {
Richard Smith55ce3522012-06-25 20:30:08 +00004155 if (CheckFunctionCall(FDecl, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004156 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004157
John McCallbebede42011-02-26 05:39:39 +00004158 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00004159 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004160 } else if (NDecl) {
Richard Smith55ce3522012-06-25 20:30:08 +00004161 if (CheckBlockCall(NDecl, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004162 return ExprError();
4163 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004164
John McCallb268a282010-08-23 23:25:46 +00004165 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00004166}
4167
John McCalldadc5752010-08-24 06:29:42 +00004168ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004169Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004170 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00004171 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00004172 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00004173 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00004174
4175 TypeSourceInfo *TInfo;
4176 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4177 if (!TInfo)
4178 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4179
John McCallb268a282010-08-23 23:25:46 +00004180 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00004181}
4182
John McCalldadc5752010-08-24 06:29:42 +00004183ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00004184Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00004185 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00004186 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00004187
Eli Friedman37a186d2008-05-20 05:22:08 +00004188 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004189 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004190 diag::err_illegal_decl_array_incomplete_type,
4191 SourceRange(LParenLoc,
4192 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004193 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00004194 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004195 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuba63ce62011-09-09 01:45:06 +00004196 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00004197 } else if (!literalType->isDependentType() &&
4198 RequireCompleteType(LParenLoc, literalType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004199 diag::err_typecheck_decl_incomplete_type,
4200 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004201 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00004202
Douglas Gregor85dabae2009-12-16 01:38:02 +00004203 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00004204 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004205 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00004206 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl0501c632012-02-12 16:37:36 +00004207 SourceRange(LParenLoc, RParenLoc),
4208 /*InitList=*/true);
Richard Trieuba63ce62011-09-09 01:45:06 +00004209 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004210 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4211 &literalType);
Eli Friedmana553d4a2009-12-22 02:35:53 +00004212 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004213 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004214 LiteralExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00004215
Chris Lattner79413952008-12-04 23:50:19 +00004216 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00004217 if (isFileScope) { // 6.5.2.5p3
Richard Trieuba63ce62011-09-09 01:45:06 +00004218 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004219 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004220 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004221
John McCall7decc9e2010-11-18 06:31:45 +00004222 // In C, compound literals are l-values for some reason.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004223 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00004224
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00004225 return MaybeBindToTemporary(
4226 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuba63ce62011-09-09 01:45:06 +00004227 VK, LiteralExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004228}
4229
John McCalldadc5752010-08-24 06:29:42 +00004230ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004231Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004232 SourceLocation RBraceLoc) {
John McCall526ab472011-10-25 17:37:35 +00004233 // Immediately handle non-overload placeholders. Overloads can be
4234 // resolved contextually, but everything else here can't.
Benjamin Kramerc215e762012-08-24 11:54:20 +00004235 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4236 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4237 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
John McCall526ab472011-10-25 17:37:35 +00004238
4239 // Ignore failures; dropping the entire initializer list because
4240 // of one failure would be terrible for indexing/etc.
4241 if (result.isInvalid()) continue;
4242
Benjamin Kramerc215e762012-08-24 11:54:20 +00004243 InitArgList[I] = result.take();
John McCall526ab472011-10-25 17:37:35 +00004244 }
4245 }
4246
Steve Naroff30d242c2007-09-15 18:49:24 +00004247 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004248 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004249
Benjamin Kramerc215e762012-08-24 11:54:20 +00004250 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4251 RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004252 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004253 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004254}
4255
John McCallcd78e802011-09-10 01:16:55 +00004256/// Do an explicit extend of the given block pointer if we're in ARC.
4257static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4258 assert(E.get()->getType()->isBlockPointerType());
4259 assert(E.get()->isRValue());
4260
4261 // Only do this in an r-value context.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004262 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallcd78e802011-09-10 01:16:55 +00004263
4264 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall2d637d22011-09-10 06:18:15 +00004265 CK_ARCExtendBlockObject, E.get(),
John McCallcd78e802011-09-10 01:16:55 +00004266 /*base path*/ 0, VK_RValue);
4267 S.ExprNeedsCleanups = true;
4268}
4269
4270/// Prepare a conversion of the given expression to an ObjC object
4271/// pointer type.
4272CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4273 QualType type = E.get()->getType();
4274 if (type->isObjCObjectPointerType()) {
4275 return CK_BitCast;
4276 } else if (type->isBlockPointerType()) {
4277 maybeExtendBlockObject(*this, E);
4278 return CK_BlockPointerToObjCPointerCast;
4279 } else {
4280 assert(type->isPointerType());
4281 return CK_CPointerToObjCPointerCast;
4282 }
4283}
4284
John McCalld7646252010-11-14 08:17:51 +00004285/// Prepares for a scalar cast, performing all the necessary stages
4286/// except the final cast and returning the kind required.
John McCall9776e432011-10-06 23:25:11 +00004287CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00004288 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4289 // Also, callers should have filtered out the invalid cases with
4290 // pointers. Everything else should be possible.
4291
John Wiegley01296292011-04-08 18:41:53 +00004292 QualType SrcTy = Src.get()->getType();
John McCall9776e432011-10-06 23:25:11 +00004293 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004294 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004295
John McCall9320b872011-09-09 05:25:32 +00004296 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00004297 case Type::STK_MemberPointer:
4298 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00004299
John McCall9320b872011-09-09 05:25:32 +00004300 case Type::STK_CPointer:
4301 case Type::STK_BlockPointer:
4302 case Type::STK_ObjCObjectPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004303 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004304 case Type::STK_CPointer:
4305 return CK_BitCast;
4306 case Type::STK_BlockPointer:
4307 return (SrcKind == Type::STK_BlockPointer
4308 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4309 case Type::STK_ObjCObjectPointer:
4310 if (SrcKind == Type::STK_ObjCObjectPointer)
4311 return CK_BitCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004312 if (SrcKind == Type::STK_CPointer)
John McCall9320b872011-09-09 05:25:32 +00004313 return CK_CPointerToObjCPointerCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004314 maybeExtendBlockObject(*this, Src);
4315 return CK_BlockPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00004316 case Type::STK_Bool:
4317 return CK_PointerToBoolean;
4318 case Type::STK_Integral:
4319 return CK_PointerToIntegral;
4320 case Type::STK_Floating:
4321 case Type::STK_FloatingComplex:
4322 case Type::STK_IntegralComplex:
4323 case Type::STK_MemberPointer:
4324 llvm_unreachable("illegal cast from pointer");
4325 }
David Blaikie8a40f702012-01-17 06:56:22 +00004326 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004327
John McCall8cb679e2010-11-15 09:13:47 +00004328 case Type::STK_Bool: // casting from bool is like casting from an integer
4329 case Type::STK_Integral:
4330 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004331 case Type::STK_CPointer:
4332 case Type::STK_ObjCObjectPointer:
4333 case Type::STK_BlockPointer:
John McCall9776e432011-10-06 23:25:11 +00004334 if (Src.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00004335 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004336 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004337 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004338 case Type::STK_Bool:
4339 return CK_IntegralToBoolean;
4340 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004341 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004342 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004343 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004344 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004345 Src = ImpCastExprToType(Src.take(),
4346 DestTy->castAs<ComplexType>()->getElementType(),
4347 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004348 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004349 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004350 Src = ImpCastExprToType(Src.take(),
4351 DestTy->castAs<ComplexType>()->getElementType(),
4352 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00004353 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004354 case Type::STK_MemberPointer:
4355 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004356 }
David Blaikie8a40f702012-01-17 06:56:22 +00004357 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004358
John McCall8cb679e2010-11-15 09:13:47 +00004359 case Type::STK_Floating:
4360 switch (DestTy->getScalarTypeKind()) {
4361 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004362 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004363 case Type::STK_Bool:
4364 return CK_FloatingToBoolean;
4365 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004366 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004367 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004368 Src = ImpCastExprToType(Src.take(),
4369 DestTy->castAs<ComplexType>()->getElementType(),
4370 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004371 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004372 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004373 Src = ImpCastExprToType(Src.take(),
4374 DestTy->castAs<ComplexType>()->getElementType(),
4375 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00004376 return CK_IntegralRealToComplex;
John McCall9320b872011-09-09 05:25:32 +00004377 case Type::STK_CPointer:
4378 case Type::STK_ObjCObjectPointer:
4379 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004380 llvm_unreachable("valid float->pointer cast?");
4381 case Type::STK_MemberPointer:
4382 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004383 }
David Blaikie8a40f702012-01-17 06:56:22 +00004384 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004385
John McCall8cb679e2010-11-15 09:13:47 +00004386 case Type::STK_FloatingComplex:
4387 switch (DestTy->getScalarTypeKind()) {
4388 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004389 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004390 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004391 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004392 case Type::STK_Floating: {
John McCall9776e432011-10-06 23:25:11 +00004393 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4394 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004395 return CK_FloatingComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004396 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004397 return CK_FloatingCast;
4398 }
John McCall8cb679e2010-11-15 09:13:47 +00004399 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004400 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004401 case Type::STK_Integral:
John McCall9776e432011-10-06 23:25:11 +00004402 Src = ImpCastExprToType(Src.take(),
4403 SrcTy->castAs<ComplexType>()->getElementType(),
4404 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004405 return CK_FloatingToIntegral;
John McCall9320b872011-09-09 05:25:32 +00004406 case Type::STK_CPointer:
4407 case Type::STK_ObjCObjectPointer:
4408 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004409 llvm_unreachable("valid complex float->pointer cast?");
4410 case Type::STK_MemberPointer:
4411 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004412 }
David Blaikie8a40f702012-01-17 06:56:22 +00004413 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004414
John McCall8cb679e2010-11-15 09:13:47 +00004415 case Type::STK_IntegralComplex:
4416 switch (DestTy->getScalarTypeKind()) {
4417 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004418 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004419 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004420 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004421 case Type::STK_Integral: {
John McCall9776e432011-10-06 23:25:11 +00004422 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4423 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004424 return CK_IntegralComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004425 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004426 return CK_IntegralCast;
4427 }
John McCall8cb679e2010-11-15 09:13:47 +00004428 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004429 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004430 case Type::STK_Floating:
John McCall9776e432011-10-06 23:25:11 +00004431 Src = ImpCastExprToType(Src.take(),
4432 SrcTy->castAs<ComplexType>()->getElementType(),
4433 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004434 return CK_IntegralToFloating;
John McCall9320b872011-09-09 05:25:32 +00004435 case Type::STK_CPointer:
4436 case Type::STK_ObjCObjectPointer:
4437 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004438 llvm_unreachable("valid complex int->pointer cast?");
4439 case Type::STK_MemberPointer:
4440 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004441 }
David Blaikie8a40f702012-01-17 06:56:22 +00004442 llvm_unreachable("Should have returned before this");
Anders Carlsson094c4592009-10-18 18:12:03 +00004443 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004444
John McCalld7646252010-11-14 08:17:51 +00004445 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson094c4592009-10-18 18:12:03 +00004446}
4447
Anders Carlsson525b76b2009-10-16 02:48:28 +00004448bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004449 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004450 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004451
Anders Carlssonde71adf2007-11-27 05:51:55 +00004452 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004453 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004454 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004455 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004456 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004457 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004458 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004459 } else
4460 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004461 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004462 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004463
John McCalle3027922010-08-25 11:45:40 +00004464 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004465 return false;
4466}
4467
John Wiegley01296292011-04-08 18:41:53 +00004468ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4469 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004470 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004471
Anders Carlsson43d70f82009-10-16 05:23:41 +00004472 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004473
Nate Begemanc8961a42009-06-27 22:05:55 +00004474 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4475 // an ExtVectorType.
Tobias Grosser766bcc22011-09-22 13:03:14 +00004476 // In OpenCL, casts between vectors of different types are not allowed.
4477 // (See OpenCL 6.2).
Nate Begemanc69b7402009-06-26 00:50:28 +00004478 if (SrcTy->isVectorType()) {
Tobias Grosser766bcc22011-09-22 13:03:14 +00004479 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikiebbafb8a2012-03-11 07:00:24 +00004480 || (getLangOpts().OpenCL &&
Tobias Grosser766bcc22011-09-22 13:03:14 +00004481 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004482 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004483 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004484 return ExprError();
4485 }
John McCalle3027922010-08-25 11:45:40 +00004486 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004487 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004488 }
4489
Nate Begemanbd956c42009-06-28 02:36:38 +00004490 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004491 // conversion will take place first from scalar to elt type, and then
4492 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004493 if (SrcTy->isPointerType())
4494 return Diag(R.getBegin(),
4495 diag::err_invalid_conversion_between_vector_and_scalar)
4496 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004497
4498 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004499 ExprResult CastExprRes = Owned(CastExpr);
John McCall9776e432011-10-06 23:25:11 +00004500 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley01296292011-04-08 18:41:53 +00004501 if (CastExprRes.isInvalid())
4502 return ExprError();
4503 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004504
John McCalle3027922010-08-25 11:45:40 +00004505 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004506 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004507}
4508
John McCalldadc5752010-08-24 06:29:42 +00004509ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004510Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4511 Declarator &D, ParsedType &Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004512 SourceLocation RParenLoc, Expr *CastExpr) {
4513 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004514 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004515
Richard Trieuba63ce62011-09-09 01:45:06 +00004516 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004517 if (D.isInvalidType())
4518 return ExprError();
4519
David Blaikiebbafb8a2012-03-11 07:00:24 +00004520 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004521 // Check that there are no default arguments (C++ only).
4522 CheckExtraCXXDefaultArguments(D);
4523 }
4524
John McCall42856de2011-10-01 05:17:03 +00004525 checkUnusedDeclAttributes(D);
4526
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004527 QualType castType = castTInfo->getType();
4528 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004529
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004530 bool isVectorLiteral = false;
4531
4532 // Check for an altivec or OpenCL literal,
4533 // i.e. all the elements are integer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00004534 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4535 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004536 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser0a3a22f2011-09-21 18:28:29 +00004537 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004538 if (PLE && PLE->getNumExprs() == 0) {
4539 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4540 return ExprError();
4541 }
4542 if (PE || PLE->getNumExprs() == 1) {
4543 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4544 if (!E->getType()->isVectorType())
4545 isVectorLiteral = true;
4546 }
4547 else
4548 isVectorLiteral = true;
4549 }
4550
4551 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4552 // then handle it as such.
4553 if (isVectorLiteral)
Richard Trieuba63ce62011-09-09 01:45:06 +00004554 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004555
Nate Begeman5ec4b312009-08-10 23:49:36 +00004556 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004557 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4558 // sequence of BinOp comma operators.
Richard Trieuba63ce62011-09-09 01:45:06 +00004559 if (isa<ParenListExpr>(CastExpr)) {
4560 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004561 if (Result.isInvalid()) return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004562 CastExpr = Result.take();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004563 }
John McCallebe54742010-01-15 18:56:44 +00004564
Richard Trieuba63ce62011-09-09 01:45:06 +00004565 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallebe54742010-01-15 18:56:44 +00004566}
4567
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004568ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4569 SourceLocation RParenLoc, Expr *E,
4570 TypeSourceInfo *TInfo) {
4571 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4572 "Expected paren or paren list expression");
4573
4574 Expr **exprs;
4575 unsigned numExprs;
4576 Expr *subExpr;
4577 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4578 exprs = PE->getExprs();
4579 numExprs = PE->getNumExprs();
4580 } else {
4581 subExpr = cast<ParenExpr>(E)->getSubExpr();
4582 exprs = &subExpr;
4583 numExprs = 1;
4584 }
4585
4586 QualType Ty = TInfo->getType();
4587 assert(Ty->isVectorType() && "Expected vector type");
4588
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004589 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004590 const VectorType *VTy = Ty->getAs<VectorType>();
4591 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4592
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004593 // '(...)' form of vector initialization in AltiVec: the number of
4594 // initializers must be one or must match the size of the vector.
4595 // If a single value is specified in the initializer then it will be
4596 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004597 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004598 // The number of initializers must be one or must match the size of the
4599 // vector. If a single value is specified in the initializer then it will
4600 // be replicated to all the components of the vector
4601 if (numExprs == 1) {
4602 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004603 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4604 if (Literal.isInvalid())
4605 return ExprError();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004606 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004607 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004608 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4609 }
4610 else if (numExprs < numElems) {
4611 Diag(E->getExprLoc(),
4612 diag::err_incorrect_number_of_vector_initializers);
4613 return ExprError();
4614 }
4615 else
Benjamin Kramer8001f742012-02-14 12:06:21 +00004616 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004617 }
Tanya Lattner83559382011-07-15 23:07:01 +00004618 else {
4619 // For OpenCL, when the number of initializers is a single value,
4620 // it will be replicated to all components of the vector.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004621 if (getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +00004622 VTy->getVectorKind() == VectorType::GenericVector &&
4623 numExprs == 1) {
4624 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004625 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4626 if (Literal.isInvalid())
4627 return ExprError();
Tanya Lattner83559382011-07-15 23:07:01 +00004628 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004629 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner83559382011-07-15 23:07:01 +00004630 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4631 }
4632
Benjamin Kramer8001f742012-02-14 12:06:21 +00004633 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner83559382011-07-15 23:07:01 +00004634 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004635 // FIXME: This means that pretty-printing the final AST will produce curly
4636 // braces instead of the original commas.
4637 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00004638 initExprs, RParenLoc);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004639 initE->setType(Ty);
4640 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4641}
4642
Sebastian Redla9351792012-02-11 23:51:47 +00004643/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4644/// the ParenListExpr into a sequence of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004645ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004646Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4647 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004648 if (!E)
Richard Trieuba63ce62011-09-09 01:45:06 +00004649 return Owned(OrigExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004650
John McCalldadc5752010-08-24 06:29:42 +00004651 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004652
Nate Begeman5ec4b312009-08-10 23:49:36 +00004653 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004654 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4655 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004656
John McCallb268a282010-08-23 23:25:46 +00004657 if (Result.isInvalid()) return ExprError();
4658
4659 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004660}
4661
Sebastian Redla9351792012-02-11 23:51:47 +00004662ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4663 SourceLocation R,
4664 MultiExprArg Val) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00004665 assert(Val.data() != 0 && "ActOnParenOrParenListExpr() missing expr list");
4666 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004667 return Owned(expr);
4668}
4669
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004670/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004671/// constant and the other is not a pointer. Returns true if a diagnostic is
4672/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00004673bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004674 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004675 Expr *NullExpr = LHSExpr;
4676 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004677 Expr::NullPointerConstantKind NullKind =
4678 NullExpr->isNullPointerConstant(Context,
4679 Expr::NPC_ValueDependentIsNotNull);
4680
4681 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004682 NullExpr = RHSExpr;
4683 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004684 NullKind =
4685 NullExpr->isNullPointerConstant(Context,
4686 Expr::NPC_ValueDependentIsNotNull);
4687 }
4688
4689 if (NullKind == Expr::NPCK_NotNull)
4690 return false;
4691
David Blaikie1c7c8f72012-08-08 17:33:31 +00004692 if (NullKind == Expr::NPCK_ZeroExpression)
4693 return false;
4694
4695 if (NullKind == Expr::NPCK_ZeroLiteral) {
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004696 // In this case, check to make sure that we got here from a "NULL"
4697 // string in the source code.
4698 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004699 SourceLocation loc = NullExpr->getExprLoc();
4700 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004701 return false;
4702 }
4703
4704 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4705 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4706 << NonPointerExpr->getType() << DiagType
4707 << NonPointerExpr->getSourceRange();
4708 return true;
4709}
4710
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004711/// \brief Return false if the condition expression is valid, true otherwise.
4712static bool checkCondition(Sema &S, Expr *Cond) {
4713 QualType CondTy = Cond->getType();
4714
4715 // C99 6.5.15p2
4716 if (CondTy->isScalarType()) return false;
4717
4718 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004719 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004720 return false;
4721
4722 // Emit the proper error message.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004723 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004724 diag::err_typecheck_cond_expect_scalar :
4725 diag::err_typecheck_cond_expect_scalar_or_vector)
4726 << CondTy;
4727 return true;
4728}
4729
4730/// \brief Return false if the two expressions can be converted to a vector,
4731/// true otherwise
4732static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4733 ExprResult &RHS,
4734 QualType CondTy) {
4735 // Both operands should be of scalar type.
4736 if (!LHS.get()->getType()->isScalarType()) {
4737 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4738 << CondTy;
4739 return true;
4740 }
4741 if (!RHS.get()->getType()->isScalarType()) {
4742 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4743 << CondTy;
4744 return true;
4745 }
4746
4747 // Implicity convert these scalars to the type of the condition.
4748 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4749 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4750 return false;
4751}
4752
4753/// \brief Handle when one or both operands are void type.
4754static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4755 ExprResult &RHS) {
4756 Expr *LHSExpr = LHS.get();
4757 Expr *RHSExpr = RHS.get();
4758
4759 if (!LHSExpr->getType()->isVoidType())
4760 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4761 << RHSExpr->getSourceRange();
4762 if (!RHSExpr->getType()->isVoidType())
4763 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4764 << LHSExpr->getSourceRange();
4765 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4766 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4767 return S.Context.VoidTy;
4768}
4769
4770/// \brief Return false if the NullExpr can be promoted to PointerTy,
4771/// true otherwise.
4772static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4773 QualType PointerTy) {
4774 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4775 !NullExpr.get()->isNullPointerConstant(S.Context,
4776 Expr::NPC_ValueDependentIsNull))
4777 return true;
4778
4779 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4780 return false;
4781}
4782
4783/// \brief Checks compatibility between two pointers and return the resulting
4784/// type.
4785static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4786 ExprResult &RHS,
4787 SourceLocation Loc) {
4788 QualType LHSTy = LHS.get()->getType();
4789 QualType RHSTy = RHS.get()->getType();
4790
4791 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4792 // Two identical pointers types are always compatible.
4793 return LHSTy;
4794 }
4795
4796 QualType lhptee, rhptee;
4797
4798 // Get the pointee types.
John McCall9320b872011-09-09 05:25:32 +00004799 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4800 lhptee = LHSBTy->getPointeeType();
4801 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004802 } else {
John McCall9320b872011-09-09 05:25:32 +00004803 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4804 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004805 }
4806
Eli Friedman57a75392012-04-05 22:30:04 +00004807 // C99 6.5.15p6: If both operands are pointers to compatible types or to
4808 // differently qualified versions of compatible types, the result type is
4809 // a pointer to an appropriately qualified version of the composite
4810 // type.
4811
4812 // Only CVR-qualifiers exist in the standard, and the differently-qualified
4813 // clause doesn't make sense for our extensions. E.g. address space 2 should
4814 // be incompatible with address space 3: they may live on different devices or
4815 // anything.
4816 Qualifiers lhQual = lhptee.getQualifiers();
4817 Qualifiers rhQual = rhptee.getQualifiers();
4818
4819 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4820 lhQual.removeCVRQualifiers();
4821 rhQual.removeCVRQualifiers();
4822
4823 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4824 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4825
4826 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4827
4828 if (CompositeTy.isNull()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004829 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4830 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4831 << RHS.get()->getSourceRange();
4832 // In this situation, we assume void* type. No especially good
4833 // reason, but this is what gcc does, and we do have to pick
4834 // to get a consistent AST.
4835 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4836 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4837 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4838 return incompatTy;
4839 }
4840
4841 // The pointer types are compatible.
Eli Friedman57a75392012-04-05 22:30:04 +00004842 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4843 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004844
Eli Friedman57a75392012-04-05 22:30:04 +00004845 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4846 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4847 return ResultTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004848}
4849
4850/// \brief Return the resulting type when the operands are both block pointers.
4851static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4852 ExprResult &LHS,
4853 ExprResult &RHS,
4854 SourceLocation Loc) {
4855 QualType LHSTy = LHS.get()->getType();
4856 QualType RHSTy = RHS.get()->getType();
4857
4858 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4859 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4860 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4861 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4862 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4863 return destType;
4864 }
4865 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4866 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4867 << RHS.get()->getSourceRange();
4868 return QualType();
4869 }
4870
4871 // We have 2 block pointer types.
4872 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4873}
4874
4875/// \brief Return the resulting type when the operands are both pointers.
4876static QualType
4877checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4878 ExprResult &RHS,
4879 SourceLocation Loc) {
4880 // get the pointer types
4881 QualType LHSTy = LHS.get()->getType();
4882 QualType RHSTy = RHS.get()->getType();
4883
4884 // get the "pointed to" types
4885 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4886 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4887
4888 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4889 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4890 // Figure out necessary qualifiers (C99 6.5.15p6)
4891 QualType destPointee
4892 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4893 QualType destType = S.Context.getPointerType(destPointee);
4894 // Add qualifiers if necessary.
4895 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4896 // Promote to void*.
4897 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4898 return destType;
4899 }
4900 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4901 QualType destPointee
4902 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4903 QualType destType = S.Context.getPointerType(destPointee);
4904 // Add qualifiers if necessary.
4905 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4906 // Promote to void*.
4907 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4908 return destType;
4909 }
4910
4911 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4912}
4913
4914/// \brief Return false if the first expression is not an integer and the second
4915/// expression is not a pointer, true otherwise.
4916static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4917 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004918 bool IsIntFirstExpr) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004919 if (!PointerExpr->getType()->isPointerType() ||
4920 !Int.get()->getType()->isIntegerType())
4921 return false;
4922
Richard Trieuba63ce62011-09-09 01:45:06 +00004923 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4924 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004925
4926 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4927 << Expr1->getType() << Expr2->getType()
4928 << Expr1->getSourceRange() << Expr2->getSourceRange();
4929 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4930 CK_IntegralToPointer);
4931 return true;
4932}
4933
Richard Trieud33e46e2011-09-06 20:06:39 +00004934/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4935/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004936/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004937QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4938 ExprResult &RHS, ExprValueKind &VK,
4939 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004940 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004941
Richard Trieud33e46e2011-09-06 20:06:39 +00004942 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4943 if (!LHSResult.isUsable()) return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004944 LHS = LHSResult;
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004945
Richard Trieud33e46e2011-09-06 20:06:39 +00004946 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4947 if (!RHSResult.isUsable()) return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004948 RHS = RHSResult;
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004949
Sebastian Redl1a99f442009-04-16 17:51:27 +00004950 // C++ is sufficiently different to merit its own checker.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004951 if (getLangOpts().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004952 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004953
4954 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004955 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004956
John Wiegley01296292011-04-08 18:41:53 +00004957 Cond = UsualUnaryConversions(Cond.take());
4958 if (Cond.isInvalid())
4959 return QualType();
4960 LHS = UsualUnaryConversions(LHS.take());
4961 if (LHS.isInvalid())
4962 return QualType();
4963 RHS = UsualUnaryConversions(RHS.take());
4964 if (RHS.isInvalid())
4965 return QualType();
4966
4967 QualType CondTy = Cond.get()->getType();
4968 QualType LHSTy = LHS.get()->getType();
4969 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004970
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004971 // first, check the condition.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004972 if (checkCondition(*this, Cond.get()))
4973 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004974
Chris Lattnere2949f42008-01-06 22:42:25 +00004975 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004976 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004977 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004978
Nate Begemanabb5a732010-09-20 22:41:17 +00004979 // OpenCL: If the condition is a vector, and both operands are scalar,
4980 // attempt to implicity convert them to the vector type to act like the
4981 // built in select.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004982 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004983 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begemanabb5a732010-09-20 22:41:17 +00004984 return QualType();
Nate Begemanabb5a732010-09-20 22:41:17 +00004985
Chris Lattnere2949f42008-01-06 22:42:25 +00004986 // If both operands have arithmetic type, do the usual arithmetic conversions
4987 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004988 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4989 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004990 if (LHS.isInvalid() || RHS.isInvalid())
4991 return QualType();
4992 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004993 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004994
Chris Lattnere2949f42008-01-06 22:42:25 +00004995 // If both operands are the same structure or union type, the result is that
4996 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004997 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4998 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004999 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005000 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00005001 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00005002 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00005003 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005004 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005005
Chris Lattnere2949f42008-01-06 22:42:25 +00005006 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00005007 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00005008 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005009 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00005010 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005011
Steve Naroff039ad3c2008-01-08 01:11:38 +00005012 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5013 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005014 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5015 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005016
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005017 // All objective-c pointer type analysis is done here.
5018 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5019 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005020 if (LHS.isInvalid() || RHS.isInvalid())
5021 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005022 if (!compositeType.isNull())
5023 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005024
5025
Steve Naroff05efa972009-07-01 14:36:47 +00005026 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005027 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5028 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5029 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005030
Steve Naroff05efa972009-07-01 14:36:47 +00005031 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005032 if (LHSTy->isPointerType() && RHSTy->isPointerType())
5033 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5034 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00005035
John McCalle84af4e2010-11-13 01:35:44 +00005036 // GCC compatibility: soften pointer/integer mismatch. Note that
5037 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005038 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5039 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00005040 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005041 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5042 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00005043 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00005044
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005045 // Emit a better diagnostic if one of the expressions is a null pointer
5046 // constant and the other is not a pointer type. In this case, the user most
5047 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005048 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005049 return QualType();
5050
Chris Lattnere2949f42008-01-06 22:42:25 +00005051 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00005052 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00005053 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5054 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005055 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00005056}
5057
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005058/// FindCompositeObjCPointerType - Helper method to find composite type of
5059/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00005060QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00005061 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005062 QualType LHSTy = LHS.get()->getType();
5063 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005064
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005065 // Handle things like Class and struct objc_class*. Here we case the result
5066 // to the pseudo-builtin, because that will be implicitly cast back to the
5067 // redefinition type if an attempt is made to access its fields.
5068 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005069 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005070 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005071 return LHSTy;
5072 }
5073 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005074 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005075 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005076 return RHSTy;
5077 }
5078 // And the same for struct objc_object* / id
5079 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005080 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005081 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005082 return LHSTy;
5083 }
5084 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005085 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005086 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005087 return RHSTy;
5088 }
5089 // And the same for struct objc_selector* / SEL
5090 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00005091 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005092 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005093 return LHSTy;
5094 }
5095 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00005096 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005097 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005098 return RHSTy;
5099 }
5100 // Check constraints for Objective-C object pointers types.
5101 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005102
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005103 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5104 // Two identical object pointer types are always compatible.
5105 return LHSTy;
5106 }
John McCall9320b872011-09-09 05:25:32 +00005107 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5108 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005109 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005110
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005111 // If both operands are interfaces and either operand can be
5112 // assigned to the other, use that type as the composite
5113 // type. This allows
5114 // xxx ? (A*) a : (B*) b
5115 // where B is a subclass of A.
5116 //
5117 // Additionally, as for assignment, if either type is 'id'
5118 // allow silent coercion. Finally, if the types are
5119 // incompatible then make sure to use 'id' as the composite
5120 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005121
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005122 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5123 // It could return the composite type.
5124 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5125 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5126 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5127 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5128 } else if ((LHSTy->isObjCQualifiedIdType() ||
5129 RHSTy->isObjCQualifiedIdType()) &&
5130 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5131 // Need to handle "id<xx>" explicitly.
5132 // GCC allows qualified id and any Objective-C type to devolve to
5133 // id. Currently localizing to here until clear this should be
5134 // part of ObjCQualifiedIdTypesAreCompatible.
5135 compositeType = Context.getObjCIdType();
5136 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5137 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005138 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005139 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5140 ;
5141 else {
5142 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5143 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00005144 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005145 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00005146 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5147 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005148 return incompatTy;
5149 }
5150 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00005151 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5152 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005153 return compositeType;
5154 }
5155 // Check Objective-C object pointer types and 'void *'
5156 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005157 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00005158 // ARC forbids the implicit conversion of object pointers to 'void *',
5159 // so these types are not compatible.
5160 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5161 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5162 LHS = RHS = true;
5163 return QualType();
5164 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005165 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5166 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5167 QualType destPointee
5168 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5169 QualType destType = Context.getPointerType(destPointee);
5170 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005171 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005172 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005173 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005174 return destType;
5175 }
5176 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005177 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00005178 // ARC forbids the implicit conversion of object pointers to 'void *',
5179 // so these types are not compatible.
5180 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5181 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5182 LHS = RHS = true;
5183 return QualType();
5184 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005185 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5186 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5187 QualType destPointee
5188 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5189 QualType destType = Context.getPointerType(destPointee);
5190 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005191 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005192 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005193 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005194 return destType;
5195 }
5196 return QualType();
5197}
5198
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005199/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005200/// ParenRange in parentheses.
5201static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005202 const PartialDiagnostic &Note,
5203 SourceRange ParenRange) {
5204 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5205 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5206 EndLoc.isValid()) {
5207 Self.Diag(Loc, Note)
5208 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5209 << FixItHint::CreateInsertion(EndLoc, ")");
5210 } else {
5211 // We can't display the parentheses, so just show the bare note.
5212 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005213 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005214}
5215
5216static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5217 return Opc >= BO_Mul && Opc <= BO_Shr;
5218}
5219
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005220/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5221/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00005222/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5223/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005224static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00005225 Expr **RHSExprs) {
Hans Wennborgbe207b32011-09-12 12:07:30 +00005226 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5227 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005228 E = E->IgnoreConversionOperator();
Hans Wennborgbe207b32011-09-12 12:07:30 +00005229 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005230
5231 // Built-in binary operator.
5232 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5233 if (IsArithmeticOp(OP->getOpcode())) {
5234 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00005235 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005236 return true;
5237 }
5238 }
5239
5240 // Overloaded operator.
5241 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5242 if (Call->getNumArgs() != 2)
5243 return false;
5244
5245 // Make sure this is really a binary operator that is safe to pass into
5246 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5247 OverloadedOperatorKind OO = Call->getOperator();
5248 if (OO < OO_Plus || OO > OO_Arrow)
5249 return false;
5250
5251 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5252 if (IsArithmeticOp(OpKind)) {
5253 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00005254 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005255 return true;
5256 }
5257 }
5258
5259 return false;
5260}
5261
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005262static bool IsLogicOp(BinaryOperatorKind Opc) {
5263 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5264}
5265
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005266/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5267/// or is a logical expression such as (x==y) which has int type, but is
5268/// commonly interpreted as boolean.
5269static bool ExprLooksBoolean(Expr *E) {
5270 E = E->IgnoreParenImpCasts();
5271
5272 if (E->getType()->isBooleanType())
5273 return true;
5274 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5275 return IsLogicOp(OP->getOpcode());
5276 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5277 return OP->getOpcode() == UO_LNot;
5278
5279 return false;
5280}
5281
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005282/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5283/// and binary operator are mixed in a way that suggests the programmer assumed
5284/// the conditional operator has higher precedence, for example:
5285/// "int x = a + someBinaryCondition ? 1 : 2".
5286static void DiagnoseConditionalPrecedence(Sema &Self,
5287 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005288 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00005289 Expr *LHSExpr,
5290 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005291 BinaryOperatorKind CondOpcode;
5292 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005293
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005294 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005295 return;
5296 if (!ExprLooksBoolean(CondRHS))
5297 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005298
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005299 // The condition is an arithmetic binary expression, with a right-
5300 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005301
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005302 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005303 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005304 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005305
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005306 SuggestParentheses(Self, OpLoc,
David Blaikiedac86fd2012-10-08 01:19:49 +00005307 Self.PDiag(diag::note_precedence_silence)
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005308 << BinaryOperator::getOpcodeStr(CondOpcode),
5309 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00005310
5311 SuggestParentheses(Self, OpLoc,
5312 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00005313 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005314}
5315
Steve Naroff83895f72007-09-16 03:34:24 +00005316/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005317/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005318ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005319 SourceLocation ColonLoc,
5320 Expr *CondExpr, Expr *LHSExpr,
5321 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005322 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5323 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005324 OpaqueValueExpr *opaqueValue = 0;
5325 Expr *commonExpr = 0;
5326 if (LHSExpr == 0) {
5327 commonExpr = CondExpr;
5328
5329 // We usually want to apply unary conversions *before* saving, except
5330 // in the special case of a C++ l-value conditional.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005331 if (!(getLangOpts().CPlusPlus
John McCallc07a0c72011-02-17 10:25:35 +00005332 && !commonExpr->isTypeDependent()
5333 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5334 && commonExpr->isGLValue()
5335 && commonExpr->isOrdinaryOrBitFieldObject()
5336 && RHSExpr->isOrdinaryOrBitFieldObject()
5337 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005338 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5339 if (commonRes.isInvalid())
5340 return ExprError();
5341 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00005342 }
5343
5344 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5345 commonExpr->getType(),
5346 commonExpr->getValueKind(),
Douglas Gregor2d5aea02012-02-23 22:17:26 +00005347 commonExpr->getObjectKind(),
5348 commonExpr);
John McCallc07a0c72011-02-17 10:25:35 +00005349 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005350 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005351
John McCall7decc9e2010-11-18 06:31:45 +00005352 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005353 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005354 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5355 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005356 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005357 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5358 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005359 return ExprError();
5360
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005361 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5362 RHS.get());
5363
John McCallc07a0c72011-02-17 10:25:35 +00005364 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005365 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5366 LHS.take(), ColonLoc,
5367 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005368
5369 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005370 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005371 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5372 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005373}
5374
John McCallaba90822011-01-31 23:13:11 +00005375// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005376// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005377// routine is it effectively iqnores the qualifiers on the top level pointee.
5378// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5379// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005380static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005381checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5382 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5383 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005384
Steve Naroff1f4d7272007-05-11 04:00:31 +00005385 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005386 const Type *lhptee, *rhptee;
5387 Qualifiers lhq, rhq;
Richard Trieua871b972011-09-06 20:21:22 +00005388 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5389 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005390
John McCallaba90822011-01-31 23:13:11 +00005391 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005392
5393 // C99 6.5.16.1p1: This following citation is common to constraints
5394 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5395 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005396 Qualifiers lq;
5397
John McCall31168b02011-06-15 23:02:42 +00005398 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5399 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5400 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5401 // Ignore lifetime for further calculation.
5402 lhq.removeObjCLifetime();
5403 rhq.removeObjCLifetime();
5404 }
5405
John McCall4fff8f62011-02-01 00:10:29 +00005406 if (!lhq.compatiblyIncludes(rhq)) {
5407 // Treat address-space mismatches as fatal. TODO: address subspaces
5408 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5409 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5410
John McCall31168b02011-06-15 23:02:42 +00005411 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005412 // and from void*.
John McCall18ce25e2012-02-08 00:46:36 +00005413 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCall31168b02011-06-15 23:02:42 +00005414 .compatiblyIncludes(
John McCall18ce25e2012-02-08 00:46:36 +00005415 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall78535952011-03-26 02:56:45 +00005416 && (lhptee->isVoidType() || rhptee->isVoidType()))
5417 ; // keep old
5418
John McCall31168b02011-06-15 23:02:42 +00005419 // Treat lifetime mismatches as fatal.
5420 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5421 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5422
John McCall4fff8f62011-02-01 00:10:29 +00005423 // For GCC compatibility, other qualifier mismatches are treated
5424 // as still compatible in C.
5425 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5426 }
Steve Naroff3f597292007-05-11 22:18:03 +00005427
Mike Stump4e1f26a2009-02-19 03:04:26 +00005428 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5429 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005430 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005431 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005432 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005433 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005434
Chris Lattner0a788432008-01-03 22:56:36 +00005435 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005436 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005437 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005438 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005439
Chris Lattner0a788432008-01-03 22:56:36 +00005440 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005441 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005442 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005443
5444 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005445 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005446 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005447 }
John McCall4fff8f62011-02-01 00:10:29 +00005448
Mike Stump4e1f26a2009-02-19 03:04:26 +00005449 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005450 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005451 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5452 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005453 // Check if the pointee types are compatible ignoring the sign.
5454 // We explicitly check for char so that we catch "char" vs
5455 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005456 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005457 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005458 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005459 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005460
Chris Lattnerec3a1562009-10-17 20:33:28 +00005461 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005462 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005463 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005464 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005465
John McCall4fff8f62011-02-01 00:10:29 +00005466 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005467 // Types are compatible ignoring the sign. Qualifier incompatibility
5468 // takes priority over sign incompatibility because the sign
5469 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005470 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005471 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005472
John McCallaba90822011-01-31 23:13:11 +00005473 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005474 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005475
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005476 // If we are a multi-level pointer, it's possible that our issue is simply
5477 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5478 // the eventual target type is the same and the pointers have the same
5479 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005480 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005481 do {
John McCall4fff8f62011-02-01 00:10:29 +00005482 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5483 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005484 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005485
John McCall4fff8f62011-02-01 00:10:29 +00005486 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005487 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005488 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005489
Eli Friedman80160bd2009-03-22 23:59:44 +00005490 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005491 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005492 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00005493 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005494 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5495 return Sema::IncompatiblePointer;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005496 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005497}
5498
John McCallaba90822011-01-31 23:13:11 +00005499/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005500/// block pointer types are compatible or whether a block and normal pointer
5501/// are compatible. It is more restrict than comparing two function pointer
5502// types.
John McCallaba90822011-01-31 23:13:11 +00005503static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005504checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5505 QualType RHSType) {
5506 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5507 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005508
Steve Naroff081c7422008-09-04 15:10:53 +00005509 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005510
Steve Naroff081c7422008-09-04 15:10:53 +00005511 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00005512 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5513 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005514
John McCallaba90822011-01-31 23:13:11 +00005515 // In C++, the types have to match exactly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005516 if (S.getLangOpts().CPlusPlus)
John McCallaba90822011-01-31 23:13:11 +00005517 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005518
John McCallaba90822011-01-31 23:13:11 +00005519 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005520
Steve Naroff081c7422008-09-04 15:10:53 +00005521 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005522 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5523 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005524
Richard Trieua871b972011-09-06 20:21:22 +00005525 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005526 return Sema::IncompatibleBlockPointer;
5527
Steve Naroff081c7422008-09-04 15:10:53 +00005528 return ConvTy;
5529}
5530
John McCallaba90822011-01-31 23:13:11 +00005531/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005532/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005533static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005534checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5535 QualType RHSType) {
5536 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5537 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005538
Richard Trieua871b972011-09-06 20:21:22 +00005539 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005540 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00005541 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5542 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005543 return Sema::IncompatiblePointer;
5544 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005545 }
Richard Trieua871b972011-09-06 20:21:22 +00005546 if (RHSType->isObjCBuiltinType()) {
Richard Trieua871b972011-09-06 20:21:22 +00005547 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5548 !LHSType->isObjCQualifiedClassType())
Fariborz Jahaniand923eb02011-09-15 20:40:18 +00005549 return Sema::IncompatiblePointer;
John McCallaba90822011-01-31 23:13:11 +00005550 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005551 }
Richard Trieua871b972011-09-06 20:21:22 +00005552 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5553 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005554
Fariborz Jahaniane74d47e2012-01-12 22:12:08 +00005555 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5556 // make an exception for id<P>
5557 !LHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005558 return Sema::CompatiblePointerDiscardsQualifiers;
5559
Richard Trieua871b972011-09-06 20:21:22 +00005560 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005561 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00005562 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005563 return Sema::IncompatibleObjCQualifiedId;
5564 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005565}
5566
John McCall29600e12010-11-16 02:32:08 +00005567Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005568Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00005569 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00005570 // Fake up an opaque expression. We don't actually care about what
5571 // cast operations are required, so if CheckAssignmentConstraints
5572 // adds casts to this they'll be wasted, but fortunately that doesn't
5573 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00005574 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5575 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00005576 CastKind K = CK_Invalid;
5577
Richard Trieua871b972011-09-06 20:21:22 +00005578 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall29600e12010-11-16 02:32:08 +00005579}
5580
Mike Stump4e1f26a2009-02-19 03:04:26 +00005581/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5582/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005583/// pointers. Here are some objectionable examples that GCC considers warnings:
5584///
5585/// int a, *pint;
5586/// short *pshort;
5587/// struct foo *pfoo;
5588///
5589/// pint = pshort; // warning: assignment from incompatible pointer type
5590/// a = pint; // warning: assignment makes integer from pointer without a cast
5591/// pint = a; // warning: assignment makes pointer from integer without a cast
5592/// pint = pfoo; // warning: assignment from incompatible pointer type
5593///
5594/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005595/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005596///
John McCall8cb679e2010-11-15 09:13:47 +00005597/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005598Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00005599Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCall8cb679e2010-11-15 09:13:47 +00005600 CastKind &Kind) {
Richard Trieude4958f2011-09-06 20:30:53 +00005601 QualType RHSType = RHS.get()->getType();
5602 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00005603
Chris Lattnera52c2f22008-01-04 23:18:45 +00005604 // Get canonical types. We're not formatting these types, just comparing
5605 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00005606 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5607 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005608
Eli Friedman0dfb8892011-10-06 23:00:33 +00005609
John McCalle5255932011-01-31 22:28:28 +00005610 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00005611 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00005612 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005613 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005614 }
5615
Eli Friedman93ee5ca2012-06-16 02:19:17 +00005616 // If we have an atomic type, try a non-atomic assignment, then just add an
5617 // atomic qualification step.
David Chisnallfa35df62012-01-16 17:27:18 +00005618 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman93ee5ca2012-06-16 02:19:17 +00005619 Sema::AssignConvertType result =
5620 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5621 if (result != Compatible)
5622 return result;
5623 if (Kind != CK_NoOp)
5624 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5625 Kind = CK_NonAtomicToAtomic;
5626 return Compatible;
David Chisnallfa35df62012-01-16 17:27:18 +00005627 }
5628
Douglas Gregor6b754842008-10-28 00:22:11 +00005629 // If the left-hand side is a reference type, then we are in a
5630 // (rare!) case where we've allowed the use of references in C,
5631 // e.g., as a parameter type in a built-in function. In this case,
5632 // just make sure that the type referenced is compatible with the
5633 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00005634 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00005635 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00005636 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5637 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005638 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005639 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005640 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005641 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005642 }
John McCalle5255932011-01-31 22:28:28 +00005643
Nate Begemanbd956c42009-06-28 02:36:38 +00005644 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5645 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005646 if (LHSType->isExtVectorType()) {
5647 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005648 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00005649 if (RHSType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005650 // CK_VectorSplat does T -> vector T, so first cast to the
5651 // element type.
Richard Trieude4958f2011-09-06 20:30:53 +00005652 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5653 if (elType != RHSType) {
John McCall9776e432011-10-06 23:25:11 +00005654 Kind = PrepareScalarCast(RHS, elType);
Richard Trieude4958f2011-09-06 20:30:53 +00005655 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005656 }
5657 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005658 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005659 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005660 }
Mike Stump11289f42009-09-09 15:08:12 +00005661
John McCalle5255932011-01-31 22:28:28 +00005662 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005663 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5664 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005665 // Allow assignments of an AltiVec vector type to an equivalent GCC
5666 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00005667 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00005668 Kind = CK_BitCast;
5669 return Compatible;
5670 }
5671
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005672 // If we are allowing lax vector conversions, and LHS and RHS are both
5673 // vectors, the total size only needs to be the same. This is a bitcast;
5674 // no bits are changed but the result type is different.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005675 if (getLangOpts().LaxVectorConversions &&
Richard Trieude4958f2011-09-06 20:30:53 +00005676 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall3065d042010-11-15 10:08:00 +00005677 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005678 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005679 }
Chris Lattner881a2122008-01-04 23:32:24 +00005680 }
5681 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005682 }
Eli Friedman3360d892008-05-30 18:07:22 +00005683
John McCalle5255932011-01-31 22:28:28 +00005684 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00005685 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00005686 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCall9776e432011-10-06 23:25:11 +00005687 Kind = PrepareScalarCast(RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005688 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005689 }
Eli Friedman3360d892008-05-30 18:07:22 +00005690
John McCalle5255932011-01-31 22:28:28 +00005691 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005692 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005693 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005694 if (isa<PointerType>(RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005695 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005696 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005697 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005698
John McCalle5255932011-01-31 22:28:28 +00005699 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005700 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00005701 Kind = CK_IntegralToPointer; // FIXME: null?
5702 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005703 }
John McCalle5255932011-01-31 22:28:28 +00005704
5705 // C pointers are not compatible with ObjC object pointers,
5706 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005707 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005708 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00005709 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall9320b872011-09-09 05:25:32 +00005710 Kind = CK_BitCast;
John McCalle5255932011-01-31 22:28:28 +00005711 return Compatible;
5712 }
5713
5714 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005715 if (RHSType->isObjCClassType() &&
5716 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005717 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00005718 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005719 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005720 }
Douglas Gregor486b74e2011-09-27 16:10:05 +00005721
John McCalle5255932011-01-31 22:28:28 +00005722 Kind = CK_BitCast;
5723 return IncompatiblePointer;
5724 }
5725
5726 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00005727 if (RHSType->getAs<BlockPointerType>()) {
5728 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00005729 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005730 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005731 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005732 }
John McCalle5255932011-01-31 22:28:28 +00005733
Steve Naroff081c7422008-09-04 15:10:53 +00005734 return Incompatible;
5735 }
5736
John McCalle5255932011-01-31 22:28:28 +00005737 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005738 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005739 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005740 if (RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00005741 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005742 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00005743 }
5744
5745 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005746 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005747 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005748 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005749 }
5750
John McCalle5255932011-01-31 22:28:28 +00005751 // id -> T^
David Blaikiebbafb8a2012-03-11 07:00:24 +00005752 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00005753 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005754 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005755 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005756
John McCalle5255932011-01-31 22:28:28 +00005757 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005758 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005759 if (RHSPT->getPointeeType()->isVoidType()) {
5760 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005761 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005762 }
John McCall8cb679e2010-11-15 09:13:47 +00005763
Chris Lattnera52c2f22008-01-04 23:18:45 +00005764 return Incompatible;
5765 }
5766
John McCalle5255932011-01-31 22:28:28 +00005767 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005768 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005769 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00005770 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00005771 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005772 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00005773 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikiebbafb8a2012-03-11 07:00:24 +00005774 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005775 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00005776 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005777 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005778 return result;
John McCalle5255932011-01-31 22:28:28 +00005779 }
5780
5781 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005782 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005783 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005784 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005785 }
5786
John McCalle5255932011-01-31 22:28:28 +00005787 // In general, C pointers are not compatible with ObjC object pointers,
5788 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005789 if (isa<PointerType>(RHSType)) {
John McCall9320b872011-09-09 05:25:32 +00005790 Kind = CK_CPointerToObjCPointerCast;
5791
John McCalle5255932011-01-31 22:28:28 +00005792 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00005793 if (RHSType->isVoidPointerType()) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005794 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005795 }
5796
5797 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005798 if (LHSType->isObjCClassType() &&
5799 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005800 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00005801 return Compatible;
5802 }
5803
Steve Naroffaccc4882009-07-20 17:56:53 +00005804 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005805 }
John McCalle5255932011-01-31 22:28:28 +00005806
5807 // T^ -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005808 if (RHSType->isBlockPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00005809 maybeExtendBlockObject(*this, RHS);
John McCall9320b872011-09-09 05:25:32 +00005810 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005811 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005812 }
5813
Steve Naroff7cae42b2009-07-10 23:34:53 +00005814 return Incompatible;
5815 }
John McCalle5255932011-01-31 22:28:28 +00005816
5817 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005818 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005819 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005820 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005821 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005822 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005823 }
Eli Friedman3360d892008-05-30 18:07:22 +00005824
John McCalle5255932011-01-31 22:28:28 +00005825 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005826 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005827 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005828 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005829 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005830
Chris Lattnera52c2f22008-01-04 23:18:45 +00005831 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005832 }
John McCalle5255932011-01-31 22:28:28 +00005833
5834 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005835 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005836 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005837 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005838 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005839 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005840 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005841
John McCalle5255932011-01-31 22:28:28 +00005842 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005843 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005844 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005845 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005846 }
5847
Steve Naroff7cae42b2009-07-10 23:34:53 +00005848 return Incompatible;
5849 }
Eli Friedman3360d892008-05-30 18:07:22 +00005850
John McCalle5255932011-01-31 22:28:28 +00005851 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00005852 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5853 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005854 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005855 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005856 }
Bill Wendling216423b2007-05-30 06:30:29 +00005857 }
John McCalle5255932011-01-31 22:28:28 +00005858
Steve Naroff98cf3e92007-06-06 18:38:38 +00005859 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005860}
5861
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005862/// \brief Constructs a transparent union from an expression that is
5863/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005864static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5865 ExprResult &EResult, QualType UnionType,
5866 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005867 // Build an initializer list that designates the appropriate member
5868 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005869 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005870 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00005871 E, SourceLocation());
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005872 Initializer->setType(UnionType);
5873 Initializer->setInitializedFieldInUnion(Field);
5874
5875 // Build a compound literal constructing a value of the transparent
5876 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005877 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005878 EResult = S.Owned(
5879 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5880 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005881}
5882
5883Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005884Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00005885 ExprResult &RHS) {
5886 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005887
Mike Stump11289f42009-09-09 15:08:12 +00005888 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005889 // transparent_union GCC extension.
5890 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005891 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005892 return Incompatible;
5893
5894 // The field to initialize within the transparent union.
5895 RecordDecl *UD = UT->getDecl();
5896 FieldDecl *InitField = 0;
5897 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005898 for (RecordDecl::field_iterator it = UD->field_begin(),
5899 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005900 it != itend; ++it) {
5901 if (it->getType()->isPointerType()) {
5902 // If the transparent union contains a pointer type, we allow:
5903 // 1) void pointer
5904 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00005905 if (RHSType->isPointerType())
John McCall9320b872011-09-09 05:25:32 +00005906 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieueb299142011-09-06 20:40:12 +00005907 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie40ed2972012-06-06 20:45:41 +00005908 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005909 break;
5910 }
Mike Stump11289f42009-09-09 15:08:12 +00005911
Richard Trieueb299142011-09-06 20:40:12 +00005912 if (RHS.get()->isNullPointerConstant(Context,
5913 Expr::NPC_ValueDependentIsNull)) {
5914 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5915 CK_NullToPointer);
David Blaikie40ed2972012-06-06 20:45:41 +00005916 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005917 break;
5918 }
5919 }
5920
John McCall8cb679e2010-11-15 09:13:47 +00005921 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00005922 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005923 == Compatible) {
Richard Trieueb299142011-09-06 20:40:12 +00005924 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie40ed2972012-06-06 20:45:41 +00005925 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005926 break;
5927 }
5928 }
5929
5930 if (!InitField)
5931 return Incompatible;
5932
Richard Trieueb299142011-09-06 20:40:12 +00005933 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005934 return Compatible;
5935}
5936
Chris Lattner9bad62c2008-01-04 18:04:52 +00005937Sema::AssignConvertType
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005938Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5939 bool Diagnose) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005940 if (getLangOpts().CPlusPlus) {
Eli Friedman0dfb8892011-10-06 23:00:33 +00005941 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005942 // C++ 5.17p3: If the left operand is not of class type, the
5943 // expression is implicitly converted (C++ 4) to the
5944 // cv-unqualified type of the left operand.
Sebastian Redlcc152642011-10-16 18:19:06 +00005945 ExprResult Res;
5946 if (Diagnose) {
5947 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5948 AA_Assigning);
5949 } else {
5950 ImplicitConversionSequence ICS =
5951 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5952 /*SuppressUserConversions=*/false,
5953 /*AllowExplicit=*/false,
5954 /*InOverloadResolution=*/false,
5955 /*CStyle=*/false,
5956 /*AllowObjCWritebackConversion=*/false);
5957 if (ICS.isFailure())
5958 return Incompatible;
5959 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5960 ICS, AA_Assigning);
5961 }
John Wiegley01296292011-04-08 18:41:53 +00005962 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005963 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005964 Sema::AssignConvertType result = Compatible;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005965 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieueb299142011-09-06 20:40:12 +00005966 !CheckObjCARCUnavailableWeakConversion(LHSType,
5967 RHS.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005968 result = IncompatibleObjCWeakRef;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005969 RHS = Res;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005970 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005971 }
5972
5973 // FIXME: Currently, we fall through and treat C++ classes like C
5974 // structures.
Eli Friedman0dfb8892011-10-06 23:00:33 +00005975 // FIXME: We also fall through for atomics; not sure what should
5976 // happen there, though.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005977 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005978
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005979 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5980 // a null pointer constant.
Richard Trieueb299142011-09-06 20:40:12 +00005981 if ((LHSType->isPointerType() ||
5982 LHSType->isObjCObjectPointerType() ||
5983 LHSType->isBlockPointerType())
5984 && RHS.get()->isNullPointerConstant(Context,
5985 Expr::NPC_ValueDependentIsNull)) {
5986 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005987 return Compatible;
5988 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005989
Chris Lattnere6dcd502007-10-16 02:55:40 +00005990 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005991 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005992 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005993 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005994 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005995 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00005996 if (!LHSType->isReferenceType()) {
5997 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5998 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005999 return Incompatible;
6000 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006001
John McCall8cb679e2010-11-15 09:13:47 +00006002 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006003 Sema::AssignConvertType result =
Richard Trieueb299142011-09-06 20:40:12 +00006004 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006005
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006006 // C99 6.5.16.1p2: The value of the right operand is converted to the
6007 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00006008 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6009 // so that we can use references in built-in functions even in C.
6010 // The getNonReferenceType() call makes sure that the resulting expression
6011 // does not have reference type.
Richard Trieueb299142011-09-06 20:40:12 +00006012 if (result != Incompatible && RHS.get()->getType() != LHSType)
6013 RHS = ImpCastExprToType(RHS.take(),
6014 LHSType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006015 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006016}
6017
Richard Trieueb299142011-09-06 20:40:12 +00006018QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6019 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006020 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00006021 << LHS.get()->getType() << RHS.get()->getType()
6022 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00006023 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00006024}
6025
Richard Trieu859d23f2011-09-06 21:01:04 +00006026QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006027 SourceLocation Loc, bool IsCompAssign) {
Richard Smith508ebf32011-10-28 03:31:48 +00006028 if (!IsCompAssign) {
6029 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6030 if (LHS.isInvalid())
6031 return QualType();
6032 }
6033 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6034 if (RHS.isInvalid())
6035 return QualType();
6036
Mike Stump4e1f26a2009-02-19 03:04:26 +00006037 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006038 // For example, "const float" and "float" are equivalent.
Richard Trieu859d23f2011-09-06 21:01:04 +00006039 QualType LHSType =
6040 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6041 QualType RHSType =
6042 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006043
Nate Begeman191a6b12008-07-14 18:02:46 +00006044 // If the vector types are identical, return.
Richard Trieu859d23f2011-09-06 21:01:04 +00006045 if (LHSType == RHSType)
6046 return LHSType;
Nate Begeman330aaa72007-12-30 02:59:45 +00006047
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006048 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu859d23f2011-09-06 21:01:04 +00006049 if (LHSType->isVectorType() && RHSType->isVectorType() &&
6050 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6051 if (LHSType->isExtVectorType()) {
6052 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6053 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00006054 }
6055
Richard Trieuba63ce62011-09-09 01:45:06 +00006056 if (!IsCompAssign)
Richard Trieu859d23f2011-09-06 21:01:04 +00006057 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6058 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006059 }
6060
David Blaikiebbafb8a2012-03-11 07:00:24 +00006061 if (getLangOpts().LaxVectorConversions &&
Richard Trieu859d23f2011-09-06 21:01:04 +00006062 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00006063 // If we are allowing lax vector conversions, and LHS and RHS are both
6064 // vectors, the total size only needs to be the same. This is a
6065 // bitcast; no bits are changed but the result type is different.
6066 // FIXME: Should we really be allowing this?
Richard Trieu859d23f2011-09-06 21:01:04 +00006067 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6068 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00006069 }
6070
Nate Begemanbd956c42009-06-28 02:36:38 +00006071 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6072 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6073 bool swapped = false;
Richard Trieuba63ce62011-09-09 01:45:06 +00006074 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006075 swapped = true;
Richard Trieu859d23f2011-09-06 21:01:04 +00006076 std::swap(RHS, LHS);
6077 std::swap(RHSType, LHSType);
Nate Begemanbd956c42009-06-28 02:36:38 +00006078 }
Mike Stump11289f42009-09-09 15:08:12 +00006079
Nate Begeman886448d2009-06-28 19:12:57 +00006080 // Handle the case of an ext vector and scalar.
Richard Trieu859d23f2011-09-06 21:01:04 +00006081 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006082 QualType EltTy = LV->getElementType();
Richard Trieu859d23f2011-09-06 21:01:04 +00006083 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6084 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00006085 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00006086 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00006087 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00006088 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6089 if (swapped) std::swap(RHS, LHS);
6090 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00006091 }
6092 }
Richard Trieu859d23f2011-09-06 21:01:04 +00006093 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6094 RHSType->isRealFloatingType()) {
6095 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00006096 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00006097 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00006098 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00006099 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6100 if (swapped) std::swap(RHS, LHS);
6101 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00006102 }
Nate Begeman330aaa72007-12-30 02:59:45 +00006103 }
6104 }
Mike Stump11289f42009-09-09 15:08:12 +00006105
Nate Begeman886448d2009-06-28 19:12:57 +00006106 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu859d23f2011-09-06 21:01:04 +00006107 if (swapped) std::swap(RHS, LHS);
Chris Lattner377d1f82008-11-18 22:52:51 +00006108 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu859d23f2011-09-06 21:01:04 +00006109 << LHS.get()->getType() << RHS.get()->getType()
6110 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00006111 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00006112}
6113
Richard Trieuf8916e12011-09-16 00:53:10 +00006114// checkArithmeticNull - Detect when a NULL constant is used improperly in an
6115// expression. These are mainly cases where the null pointer is used as an
6116// integer instead of a pointer.
6117static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6118 SourceLocation Loc, bool IsCompare) {
6119 // The canonical way to check for a GNU null is with isNullPointerConstant,
6120 // but we use a bit of a hack here for speed; this is a relatively
6121 // hot path, and isNullPointerConstant is slow.
6122 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6123 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6124
6125 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6126
6127 // Avoid analyzing cases where the result will either be invalid (and
6128 // diagnosed as such) or entirely valid and not something to warn about.
6129 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6130 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6131 return;
6132
6133 // Comparison operations would not make sense with a null pointer no matter
6134 // what the other expression is.
6135 if (!IsCompare) {
6136 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6137 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6138 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6139 return;
6140 }
6141
6142 // The rest of the operations only make sense with a null pointer
6143 // if the other expression is a pointer.
6144 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6145 NonNullType->canDecayToPointerType())
6146 return;
6147
6148 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6149 << LHSNull /* LHS is NULL */ << NonNullType
6150 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6151}
6152
Richard Trieu859d23f2011-09-06 21:01:04 +00006153QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006154 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006155 bool IsCompAssign, bool IsDiv) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006156 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6157
Richard Trieu859d23f2011-09-06 21:01:04 +00006158 if (LHS.get()->getType()->isVectorType() ||
6159 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006160 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006161
Richard Trieuba63ce62011-09-09 01:45:06 +00006162 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006163 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006164 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006165
David Chisnallfa35df62012-01-16 17:27:18 +00006166
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006167 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu859d23f2011-09-06 21:01:04 +00006168 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006169
Chris Lattnerfaa54172010-01-12 21:23:57 +00006170 // Check for division by zero.
Richard Trieuba63ce62011-09-09 01:45:06 +00006171 if (IsDiv &&
Richard Trieu859d23f2011-09-06 21:01:04 +00006172 RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00006173 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00006174 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6175 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006176
Chris Lattnerfaa54172010-01-12 21:23:57 +00006177 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006178}
6179
Chris Lattnerfaa54172010-01-12 21:23:57 +00006180QualType Sema::CheckRemainderOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00006181 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006182 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6183
Richard Trieu859d23f2011-09-06 21:01:04 +00006184 if (LHS.get()->getType()->isVectorType() ||
6185 RHS.get()->getType()->isVectorType()) {
6186 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6187 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00006188 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006189 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006190 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006191
Richard Trieuba63ce62011-09-09 01:45:06 +00006192 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006193 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006194 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006195
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006196 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu859d23f2011-09-06 21:01:04 +00006197 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006198
Chris Lattnerfaa54172010-01-12 21:23:57 +00006199 // Check for remainder by zero.
Richard Trieu859d23f2011-09-06 21:01:04 +00006200 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00006201 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00006202 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6203 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006204
Chris Lattnerfaa54172010-01-12 21:23:57 +00006205 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006206}
6207
Chandler Carruthc9332212011-06-27 08:02:19 +00006208/// \brief Diagnose invalid arithmetic on two void pointers.
6209static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006210 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006211 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006212 ? diag::err_typecheck_pointer_arith_void_type
6213 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006214 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6215 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00006216}
6217
6218/// \brief Diagnose invalid arithmetic on a void pointer.
6219static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6220 Expr *Pointer) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006221 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006222 ? diag::err_typecheck_pointer_arith_void_type
6223 : diag::ext_gnu_void_ptr)
6224 << 0 /* one pointer */ << Pointer->getSourceRange();
6225}
6226
6227/// \brief Diagnose invalid arithmetic on two function pointers.
6228static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6229 Expr *LHS, Expr *RHS) {
6230 assert(LHS->getType()->isAnyPointerType());
6231 assert(RHS->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006232 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006233 ? diag::err_typecheck_pointer_arith_function_type
6234 : diag::ext_gnu_ptr_func_arith)
6235 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6236 // We only show the second type if it differs from the first.
6237 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6238 RHS->getType())
6239 << RHS->getType()->getPointeeType()
6240 << LHS->getSourceRange() << RHS->getSourceRange();
6241}
6242
6243/// \brief Diagnose invalid arithmetic on a function pointer.
6244static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6245 Expr *Pointer) {
6246 assert(Pointer->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006247 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006248 ? diag::err_typecheck_pointer_arith_function_type
6249 : diag::ext_gnu_ptr_func_arith)
6250 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6251 << 0 /* one pointer, so only one type */
6252 << Pointer->getSourceRange();
6253}
6254
Richard Trieu993f3ab2011-09-12 18:08:02 +00006255/// \brief Emit error if Operand is incomplete pointer type
Richard Trieuaba22802011-09-02 02:15:37 +00006256///
6257/// \returns True if pointer has incomplete type
6258static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6259 Expr *Operand) {
John McCallf2538342012-07-31 05:14:30 +00006260 assert(Operand->getType()->isAnyPointerType() &&
6261 !Operand->getType()->isDependentType());
6262 QualType PointeeTy = Operand->getType()->getPointeeType();
6263 return S.RequireCompleteType(Loc, PointeeTy,
6264 diag::err_typecheck_arithmetic_incomplete_type,
6265 PointeeTy, Operand->getSourceRange());
Richard Trieuaba22802011-09-02 02:15:37 +00006266}
6267
Chandler Carruthc9332212011-06-27 08:02:19 +00006268/// \brief Check the validity of an arithmetic pointer operand.
6269///
6270/// If the operand has pointer type, this code will check for pointer types
6271/// which are invalid in arithmetic operations. These will be diagnosed
6272/// appropriately, including whether or not the use is supported as an
6273/// extension.
6274///
6275/// \returns True when the operand is valid to use (even if as an extension).
6276static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6277 Expr *Operand) {
6278 if (!Operand->getType()->isAnyPointerType()) return true;
6279
6280 QualType PointeeTy = Operand->getType()->getPointeeType();
6281 if (PointeeTy->isVoidType()) {
6282 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00006283 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006284 }
6285 if (PointeeTy->isFunctionType()) {
6286 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00006287 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006288 }
6289
Richard Trieuaba22802011-09-02 02:15:37 +00006290 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00006291
6292 return true;
6293}
6294
6295/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6296/// operands.
6297///
6298/// This routine will diagnose any invalid arithmetic on pointer operands much
6299/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6300/// for emitting a single diagnostic even for operations where both LHS and RHS
6301/// are (potentially problematic) pointers.
6302///
6303/// \returns True when the operand is valid to use (even if as an extension).
6304static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006305 Expr *LHSExpr, Expr *RHSExpr) {
6306 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6307 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006308 if (!isLHSPointer && !isRHSPointer) return true;
6309
6310 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00006311 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6312 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006313
6314 // Check for arithmetic on pointers to incomplete types.
6315 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6316 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6317 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006318 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6319 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6320 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006321
David Blaikiebbafb8a2012-03-11 07:00:24 +00006322 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006323 }
6324
6325 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6326 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6327 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006328 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6329 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6330 RHSExpr);
6331 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006332
David Blaikiebbafb8a2012-03-11 07:00:24 +00006333 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006334 }
6335
John McCallf2538342012-07-31 05:14:30 +00006336 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6337 return false;
6338 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6339 return false;
Richard Trieuaba22802011-09-02 02:15:37 +00006340
Chandler Carruthc9332212011-06-27 08:02:19 +00006341 return true;
6342}
6343
Nico Weberccec40d2012-03-02 22:01:22 +00006344/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6345/// literal.
6346static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6347 Expr *LHSExpr, Expr *RHSExpr) {
6348 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6349 Expr* IndexExpr = RHSExpr;
6350 if (!StrExpr) {
6351 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6352 IndexExpr = LHSExpr;
6353 }
6354
6355 bool IsStringPlusInt = StrExpr &&
6356 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6357 if (!IsStringPlusInt)
6358 return;
6359
6360 llvm::APSInt index;
6361 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6362 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6363 if (index.isNonNegative() &&
6364 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6365 index.isUnsigned()))
6366 return;
6367 }
6368
6369 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6370 Self.Diag(OpLoc, diag::warn_string_plus_int)
6371 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6372
6373 // Only print a fixit for "str" + int, not for int + "str".
6374 if (IndexExpr == RHSExpr) {
6375 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6376 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6377 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6378 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6379 << FixItHint::CreateInsertion(EndLoc, "]");
6380 } else
6381 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6382}
6383
Richard Trieu993f3ab2011-09-12 18:08:02 +00006384/// \brief Emit error when two pointers are incompatible.
Richard Trieub10c6312011-09-01 22:53:23 +00006385static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006386 Expr *LHSExpr, Expr *RHSExpr) {
6387 assert(LHSExpr->getType()->isAnyPointerType());
6388 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00006389 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006390 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6391 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00006392}
6393
Chris Lattnerfaa54172010-01-12 21:23:57 +00006394QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weberccec40d2012-03-02 22:01:22 +00006395 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6396 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006397 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6398
Richard Trieu4ae7e972011-09-06 21:13:51 +00006399 if (LHS.get()->getType()->isVectorType() ||
6400 RHS.get()->getType()->isVectorType()) {
6401 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006402 if (CompLHSTy) *CompLHSTy = compType;
6403 return compType;
6404 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006405
Richard Trieu4ae7e972011-09-06 21:13:51 +00006406 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6407 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006408 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006409
Nico Weberccec40d2012-03-02 22:01:22 +00006410 // Diagnose "string literal" '+' int.
6411 if (Opc == BO_Add)
6412 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6413
Steve Naroffe4718892007-04-27 18:30:00 +00006414 // handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006415 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006416 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006417 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006418 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006419
John McCallf2538342012-07-31 05:14:30 +00006420 // Type-checking. Ultimately the pointer's going to be in PExp;
6421 // note that we bias towards the LHS being the pointer.
6422 Expr *PExp = LHS.get(), *IExp = RHS.get();
Eli Friedman8e122982008-05-18 18:08:51 +00006423
John McCallf2538342012-07-31 05:14:30 +00006424 bool isObjCPointer;
6425 if (PExp->getType()->isPointerType()) {
6426 isObjCPointer = false;
6427 } else if (PExp->getType()->isObjCObjectPointerType()) {
6428 isObjCPointer = true;
6429 } else {
6430 std::swap(PExp, IExp);
6431 if (PExp->getType()->isPointerType()) {
6432 isObjCPointer = false;
6433 } else if (PExp->getType()->isObjCObjectPointerType()) {
6434 isObjCPointer = true;
6435 } else {
6436 return InvalidOperands(Loc, LHS, RHS);
6437 }
6438 }
6439 assert(PExp->getType()->isAnyPointerType());
Chandler Carruthc9332212011-06-27 08:02:19 +00006440
Richard Trieub420bca2011-09-12 18:37:54 +00006441 if (!IExp->getType()->isIntegerType())
6442 return InvalidOperands(Loc, LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006443
Richard Trieub420bca2011-09-12 18:37:54 +00006444 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6445 return QualType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006446
John McCallf2538342012-07-31 05:14:30 +00006447 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
Richard Trieub420bca2011-09-12 18:37:54 +00006448 return QualType();
6449
6450 // Check array bounds for pointer arithemtic
6451 CheckArrayAccess(PExp, IExp);
6452
6453 if (CompLHSTy) {
6454 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6455 if (LHSTy.isNull()) {
6456 LHSTy = LHS.get()->getType();
6457 if (LHSTy->isPromotableIntegerType())
6458 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006459 }
Richard Trieub420bca2011-09-12 18:37:54 +00006460 *CompLHSTy = LHSTy;
Eli Friedman8e122982008-05-18 18:08:51 +00006461 }
6462
Richard Trieub420bca2011-09-12 18:37:54 +00006463 return PExp->getType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00006464}
6465
Chris Lattner2a3569b2008-04-07 05:30:13 +00006466// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006467QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006468 SourceLocation Loc,
6469 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006470 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6471
Richard Trieu4ae7e972011-09-06 21:13:51 +00006472 if (LHS.get()->getType()->isVectorType() ||
6473 RHS.get()->getType()->isVectorType()) {
6474 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006475 if (CompLHSTy) *CompLHSTy = compType;
6476 return compType;
6477 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006478
Richard Trieu4ae7e972011-09-06 21:13:51 +00006479 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6480 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006481 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006482
Chris Lattner4d62f422007-12-09 21:53:25 +00006483 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006484
Chris Lattner4d62f422007-12-09 21:53:25 +00006485 // Handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006486 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006487 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006488 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006489 }
Mike Stump11289f42009-09-09 15:08:12 +00006490
Chris Lattner4d62f422007-12-09 21:53:25 +00006491 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006492 if (LHS.get()->getType()->isAnyPointerType()) {
6493 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006494
Chris Lattner12bdebb2009-04-24 23:50:08 +00006495 // Diagnose bad cases where we step over interface counts.
John McCallf2538342012-07-31 05:14:30 +00006496 if (LHS.get()->getType()->isObjCObjectPointerType() &&
6497 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00006498 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006499
Chris Lattner4d62f422007-12-09 21:53:25 +00006500 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006501 if (RHS.get()->getType()->isIntegerType()) {
6502 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006503 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006504
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006505 // Check array bounds for pointer arithemtic
Richard Smith13f67182011-12-16 19:31:14 +00006506 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6507 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006508
Richard Trieu4ae7e972011-09-06 21:13:51 +00006509 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6510 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006511 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006512
Chris Lattner4d62f422007-12-09 21:53:25 +00006513 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006514 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00006515 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006516 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006517
David Blaikiebbafb8a2012-03-11 07:00:24 +00006518 if (getLangOpts().CPlusPlus) {
Eli Friedman168fe152009-05-16 13:54:38 +00006519 // Pointee types must be the same: C++ [expr.add]
6520 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006521 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006522 }
6523 } else {
6524 // Pointee types must be compatible C99 6.5.6p3
6525 if (!Context.typesAreCompatible(
6526 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6527 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006528 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006529 return QualType();
6530 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006531 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006532
Chandler Carruthc9332212011-06-27 08:02:19 +00006533 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006534 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006535 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006536
Richard Trieu4ae7e972011-09-06 21:13:51 +00006537 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006538 return Context.getPointerDiffType();
6539 }
6540 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006541
Richard Trieu4ae7e972011-09-06 21:13:51 +00006542 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006543}
6544
Douglas Gregor0bf31402010-10-08 23:50:27 +00006545static bool isScopedEnumerationType(QualType T) {
6546 if (const EnumType *ET = dyn_cast<EnumType>(T))
6547 return ET->getDecl()->isScoped();
6548 return false;
6549}
6550
Richard Trieue4a19fb2011-09-06 21:21:28 +00006551static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006552 SourceLocation Loc, unsigned Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00006553 QualType LHSType) {
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006554 llvm::APSInt Right;
6555 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00006556 if (RHS.get()->isValueDependent() ||
6557 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006558 return;
6559
6560 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006561 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006562 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006563 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006564 return;
6565 }
6566 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00006567 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006568 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006569 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006570 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006571 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006572 return;
6573 }
6574 if (Opc != BO_Shl)
6575 return;
6576
6577 // When left shifting an ICE which is signed, we can check for overflow which
6578 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6579 // integers have defined behavior modulo one more than the maximum value
6580 // representable in the result type, so never warn for those.
6581 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00006582 if (LHS.get()->isValueDependent() ||
6583 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6584 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006585 return;
6586 llvm::APInt ResultBits =
6587 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6588 if (LeftBits.uge(ResultBits))
6589 return;
6590 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6591 Result = Result.shl(Right);
6592
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006593 // Print the bit representation of the signed integer as an unsigned
6594 // hexadecimal number.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006595 SmallString<40> HexResult;
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006596 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6597
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006598 // If we are only missing a sign bit, this is less likely to result in actual
6599 // bugs -- if the result is cast back to an unsigned type, it will have the
6600 // expected value. Thus we place this behind a different warning that can be
6601 // turned off separately if needed.
6602 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006603 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006604 << HexResult.str() << LHSType
6605 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006606 return;
6607 }
6608
6609 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006610 << HexResult.str() << Result.getMinSignedBits() << LHSType
6611 << Left.getBitWidth() << LHS.get()->getSourceRange()
6612 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006613}
6614
Chris Lattner2a3569b2008-04-07 05:30:13 +00006615// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00006616QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006617 SourceLocation Loc, unsigned Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006618 bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006619 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6620
Chris Lattner5c11c412007-12-12 05:47:28 +00006621 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006622 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6623 !RHS.get()->getType()->hasIntegerRepresentation())
6624 return InvalidOperands(Loc, LHS, RHS);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006625
Douglas Gregor0bf31402010-10-08 23:50:27 +00006626 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6627 // hasIntegerRepresentation() above instead of this.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006628 if (isScopedEnumerationType(LHS.get()->getType()) ||
6629 isScopedEnumerationType(RHS.get()->getType())) {
6630 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006631 }
6632
Nate Begemane46ee9a2009-10-25 02:26:48 +00006633 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006634 if (LHS.get()->getType()->isVectorType() ||
6635 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006636 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006637
Chris Lattner5c11c412007-12-12 05:47:28 +00006638 // Shifts don't perform usual arithmetic conversions, they just do integer
6639 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006640
John McCall57cdd882010-12-16 19:28:59 +00006641 // For the LHS, do usual unary conversions, but then reset them away
6642 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006643 ExprResult OldLHS = LHS;
6644 LHS = UsualUnaryConversions(LHS.take());
6645 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006646 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00006647 QualType LHSType = LHS.get()->getType();
Richard Trieuba63ce62011-09-09 01:45:06 +00006648 if (IsCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00006649
6650 // The RHS is simpler.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006651 RHS = UsualUnaryConversions(RHS.take());
6652 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006653 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006654
Ryan Flynnf53fab82009-08-07 16:20:20 +00006655 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00006656 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006657
Chris Lattner5c11c412007-12-12 05:47:28 +00006658 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00006659 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006660}
6661
Chandler Carruth17773fc2010-07-10 12:30:03 +00006662static bool IsWithinTemplateSpecialization(Decl *D) {
6663 if (DeclContext *DC = D->getDeclContext()) {
6664 if (isa<ClassTemplateSpecializationDecl>(DC))
6665 return true;
6666 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6667 return FD->isFunctionTemplateSpecialization();
6668 }
6669 return false;
6670}
6671
Richard Trieueea56f72011-09-02 03:48:46 +00006672/// If two different enums are compared, raise a warning.
Richard Trieu1762d7c2011-09-06 21:27:33 +00006673static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6674 ExprResult &RHS) {
6675 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6676 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00006677
6678 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6679 if (!LHSEnumType)
6680 return;
6681 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6682 if (!RHSEnumType)
6683 return;
6684
6685 // Ignore anonymous enums.
6686 if (!LHSEnumType->getDecl()->getIdentifier())
6687 return;
6688 if (!RHSEnumType->getDecl()->getIdentifier())
6689 return;
6690
6691 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6692 return;
6693
6694 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6695 << LHSStrippedType << RHSStrippedType
Richard Trieu1762d7c2011-09-06 21:27:33 +00006696 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00006697}
6698
Richard Trieudd82a5c2011-09-02 02:55:45 +00006699/// \brief Diagnose bad pointer comparisons.
6700static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006701 ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006702 bool IsError) {
6703 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieudd82a5c2011-09-02 02:55:45 +00006704 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006705 << LHS.get()->getType() << RHS.get()->getType()
6706 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006707}
6708
6709/// \brief Returns false if the pointers are converted to a composite type,
6710/// true otherwise.
6711static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006712 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006713 // C++ [expr.rel]p2:
6714 // [...] Pointer conversions (4.10) and qualification
6715 // conversions (4.4) are performed on pointer operands (or on
6716 // a pointer operand and a null pointer constant) to bring
6717 // them to their composite pointer type. [...]
6718 //
6719 // C++ [expr.eq]p1 uses the same notion for (in)equality
6720 // comparisons of pointers.
6721
6722 // C++ [expr.eq]p2:
6723 // In addition, pointers to members can be compared, or a pointer to
6724 // member and a null pointer constant. Pointer to member conversions
6725 // (4.11) and qualification conversions (4.4) are performed to bring
6726 // them to a common type. If one operand is a null pointer constant,
6727 // the common type is the type of the other operand. Otherwise, the
6728 // common type is a pointer to member type similar (4.4) to the type
6729 // of one of the operands, with a cv-qualification signature (4.4)
6730 // that is the union of the cv-qualification signatures of the operand
6731 // types.
6732
Richard Trieu1762d7c2011-09-06 21:27:33 +00006733 QualType LHSType = LHS.get()->getType();
6734 QualType RHSType = RHS.get()->getType();
6735 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6736 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieudd82a5c2011-09-02 02:55:45 +00006737
6738 bool NonStandardCompositeType = false;
Richard Trieu48277e52011-09-02 21:44:27 +00006739 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieu1762d7c2011-09-06 21:27:33 +00006740 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006741 if (T.isNull()) {
Richard Trieu1762d7c2011-09-06 21:27:33 +00006742 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006743 return true;
6744 }
6745
6746 if (NonStandardCompositeType)
6747 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006748 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6749 << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006750
Richard Trieu1762d7c2011-09-06 21:27:33 +00006751 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6752 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006753 return false;
6754}
6755
6756static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006757 ExprResult &LHS,
6758 ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006759 bool IsError) {
6760 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6761 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006762 << LHS.get()->getType() << RHS.get()->getType()
6763 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006764}
6765
Jordan Rosed49a33e2012-06-08 21:14:25 +00006766static bool isObjCObjectLiteral(ExprResult &E) {
6767 switch (E.get()->getStmtClass()) {
6768 case Stmt::ObjCArrayLiteralClass:
6769 case Stmt::ObjCDictionaryLiteralClass:
6770 case Stmt::ObjCStringLiteralClass:
6771 case Stmt::ObjCBoxedExprClass:
6772 return true;
6773 default:
6774 // Note that ObjCBoolLiteral is NOT an object literal!
6775 return false;
6776 }
6777}
6778
Jordan Rose7660f782012-07-17 17:46:40 +00006779static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6780 // Get the LHS object's interface type.
6781 QualType Type = LHS->getType();
6782 QualType InterfaceType;
6783 if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6784 InterfaceType = PTy->getPointeeType();
6785 if (const ObjCObjectType *iQFaceTy =
6786 InterfaceType->getAsObjCQualifiedInterfaceType())
6787 InterfaceType = iQFaceTy->getBaseType();
6788 } else {
6789 // If this is not actually an Objective-C object, bail out.
6790 return false;
6791 }
6792
6793 // If the RHS isn't an Objective-C object, bail out.
6794 if (!RHS->getType()->isObjCObjectPointerType())
6795 return false;
6796
6797 // Try to find the -isEqual: method.
6798 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6799 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6800 InterfaceType,
6801 /*instance=*/true);
6802 if (!Method) {
6803 if (Type->isObjCIdType()) {
6804 // For 'id', just check the global pool.
6805 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6806 /*receiverId=*/true,
6807 /*warn=*/false);
6808 } else {
6809 // Check protocols.
6810 Method = S.LookupMethodInQualifiedType(IsEqualSel,
6811 cast<ObjCObjectPointerType>(Type),
6812 /*instance=*/true);
6813 }
6814 }
6815
6816 if (!Method)
6817 return false;
6818
6819 QualType T = Method->param_begin()[0]->getType();
6820 if (!T->isObjCObjectPointerType())
6821 return false;
6822
6823 QualType R = Method->getResultType();
6824 if (!R->isScalarType())
6825 return false;
6826
6827 return true;
6828}
6829
6830static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
6831 ExprResult &LHS, ExprResult &RHS,
6832 BinaryOperator::Opcode Opc){
Jordan Rose63ffaa82012-07-17 17:46:48 +00006833 Expr *Literal;
6834 Expr *Other;
6835 if (isObjCObjectLiteral(LHS)) {
6836 Literal = LHS.get();
6837 Other = RHS.get();
6838 } else {
6839 Literal = RHS.get();
6840 Other = LHS.get();
6841 }
6842
6843 // Don't warn on comparisons against nil.
6844 Other = Other->IgnoreParenCasts();
6845 if (Other->isNullPointerConstant(S.getASTContext(),
6846 Expr::NPC_ValueDependentIsNotNull))
6847 return;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006848
Jordan Roseea70bf72012-07-17 17:46:44 +00006849 // This should be kept in sync with warn_objc_literal_comparison.
Jordan Rose63ffaa82012-07-17 17:46:48 +00006850 // LK_String should always be last, since it has its own warning flag.
Jordan Roseea70bf72012-07-17 17:46:44 +00006851 enum {
6852 LK_Array,
6853 LK_Dictionary,
6854 LK_Numeric,
6855 LK_Boxed,
6856 LK_String
6857 } LiteralKind;
6858
Jordan Rosed49a33e2012-06-08 21:14:25 +00006859 switch (Literal->getStmtClass()) {
6860 case Stmt::ObjCStringLiteralClass:
6861 // "string literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006862 LiteralKind = LK_String;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006863 break;
6864 case Stmt::ObjCArrayLiteralClass:
6865 // "array literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006866 LiteralKind = LK_Array;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006867 break;
6868 case Stmt::ObjCDictionaryLiteralClass:
6869 // "dictionary literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006870 LiteralKind = LK_Dictionary;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006871 break;
6872 case Stmt::ObjCBoxedExprClass: {
6873 Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6874 switch (Inner->getStmtClass()) {
6875 case Stmt::IntegerLiteralClass:
6876 case Stmt::FloatingLiteralClass:
6877 case Stmt::CharacterLiteralClass:
6878 case Stmt::ObjCBoolLiteralExprClass:
6879 case Stmt::CXXBoolLiteralExprClass:
6880 // "numeric literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006881 LiteralKind = LK_Numeric;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006882 break;
6883 case Stmt::ImplicitCastExprClass: {
6884 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6885 // Boolean literals can be represented by implicit casts.
6886 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
Jordan Roseea70bf72012-07-17 17:46:44 +00006887 LiteralKind = LK_Numeric;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006888 break;
6889 }
6890 // FALLTHROUGH
6891 }
6892 default:
6893 // "boxed expression"
Jordan Roseea70bf72012-07-17 17:46:44 +00006894 LiteralKind = LK_Boxed;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006895 break;
6896 }
6897 break;
6898 }
6899 default:
6900 llvm_unreachable("Unknown Objective-C object literal kind");
6901 }
6902
Jordan Roseea70bf72012-07-17 17:46:44 +00006903 if (LiteralKind == LK_String)
6904 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
6905 << Literal->getSourceRange();
6906 else
6907 S.Diag(Loc, diag::warn_objc_literal_comparison)
6908 << LiteralKind << Literal->getSourceRange();
Jordan Rosed49a33e2012-06-08 21:14:25 +00006909
Jordan Rose7660f782012-07-17 17:46:40 +00006910 if (BinaryOperator::isEqualityOp(Opc) &&
6911 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
6912 SourceLocation Start = LHS.get()->getLocStart();
6913 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
6914 SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc));
Jordan Rosef9198032012-07-09 16:54:44 +00006915
Jordan Rose7660f782012-07-17 17:46:40 +00006916 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
6917 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
6918 << FixItHint::CreateReplacement(OpRange, "isEqual:")
6919 << FixItHint::CreateInsertion(End, "]");
Jordan Rosed49a33e2012-06-08 21:14:25 +00006920 }
Jordan Rosed49a33e2012-06-08 21:14:25 +00006921}
6922
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006923// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00006924QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006925 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006926 bool IsRelational) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006927 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6928
John McCalle3027922010-08-25 11:45:40 +00006929 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006930
Chris Lattner9a152e22009-12-05 05:40:13 +00006931 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00006932 if (LHS.get()->getType()->isVectorType() ||
6933 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006934 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006935
Richard Trieub80728f2011-09-06 21:43:51 +00006936 QualType LHSType = LHS.get()->getType();
6937 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00006938
Richard Trieub80728f2011-09-06 21:43:51 +00006939 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6940 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006941
Richard Trieub80728f2011-09-06 21:43:51 +00006942 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth712563b2011-02-17 08:37:06 +00006943
Richard Trieub80728f2011-09-06 21:43:51 +00006944 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuba63ce62011-09-09 01:45:06 +00006945 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieub80728f2011-09-06 21:43:51 +00006946 !LHS.get()->getLocStart().isMacroID() &&
6947 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006948 // For non-floating point types, check for self-comparisons of the form
6949 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6950 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006951 //
6952 // NOTE: Don't warn about comparison expressions resulting from macro
6953 // expansion. Also don't warn about comparisons which are only self
6954 // comparisons within a template specialization. The warnings should catch
6955 // obvious cases in the definition of the template anyways. The idea is to
6956 // warn when the typed comparison operator will always evaluate to the same
6957 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006958 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006959 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006960 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006961 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006962 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006963 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006964 << (Opc == BO_EQ
6965 || Opc == BO_LE
6966 || Opc == BO_GE));
Richard Trieub80728f2011-09-06 21:43:51 +00006967 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregorec170db2010-06-08 19:50:34 +00006968 !DRL->getDecl()->getType()->isReferenceType() &&
6969 !DRR->getDecl()->getType()->isReferenceType()) {
6970 // what is it always going to eval to?
6971 char always_evals_to;
6972 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006973 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006974 always_evals_to = 0; // false
6975 break;
John McCalle3027922010-08-25 11:45:40 +00006976 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006977 always_evals_to = 1; // true
6978 break;
6979 default:
6980 // best we can say is 'a constant'
6981 always_evals_to = 2; // e.g. array1 <= array2
6982 break;
6983 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006984 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006985 << 1 // array
6986 << always_evals_to);
6987 }
6988 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006989 }
Mike Stump11289f42009-09-09 15:08:12 +00006990
Chris Lattner222b8bd2009-03-08 19:39:53 +00006991 if (isa<CastExpr>(LHSStripped))
6992 LHSStripped = LHSStripped->IgnoreParenCasts();
6993 if (isa<CastExpr>(RHSStripped))
6994 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006995
Chris Lattner222b8bd2009-03-08 19:39:53 +00006996 // Warn about comparisons against a string constant (unless the other
6997 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006998 Expr *literalString = 0;
6999 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00007000 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007001 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007002 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00007003 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007004 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00007005 } else if ((isa<StringLiteral>(RHSStripped) ||
7006 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007007 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007008 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00007009 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007010 literalStringStripped = RHSStripped;
7011 }
7012
7013 if (literalString) {
7014 std::string resultComparison;
7015 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007016 case BO_LT: resultComparison = ") < 0"; break;
7017 case BO_GT: resultComparison = ") > 0"; break;
7018 case BO_LE: resultComparison = ") <= 0"; break;
7019 case BO_GE: resultComparison = ") >= 0"; break;
7020 case BO_EQ: resultComparison = ") == 0"; break;
7021 case BO_NE: resultComparison = ") != 0"; break;
David Blaikie83d382b2011-09-23 05:06:16 +00007022 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007023 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007024
Ted Kremenek3427fac2011-02-23 01:52:04 +00007025 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00007026 PDiag(diag::warn_stringcompare)
7027 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00007028 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007029 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00007030 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007031
Douglas Gregorec170db2010-06-08 19:50:34 +00007032 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieub80728f2011-09-06 21:43:51 +00007033 if (LHS.get()->getType()->isArithmeticType() &&
7034 RHS.get()->getType()->isArithmeticType()) {
7035 UsualArithmeticConversions(LHS, RHS);
7036 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007037 return QualType();
7038 }
Douglas Gregorec170db2010-06-08 19:50:34 +00007039 else {
Richard Trieub80728f2011-09-06 21:43:51 +00007040 LHS = UsualUnaryConversions(LHS.take());
7041 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007042 return QualType();
7043
Richard Trieub80728f2011-09-06 21:43:51 +00007044 RHS = UsualUnaryConversions(RHS.take());
7045 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007046 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007047 }
7048
Richard Trieub80728f2011-09-06 21:43:51 +00007049 LHSType = LHS.get()->getType();
7050 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007051
Douglas Gregorca63811b2008-11-19 03:25:36 +00007052 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007053 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00007054
Richard Trieuba63ce62011-09-09 01:45:06 +00007055 if (IsRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00007056 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007057 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007058 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00007059 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00007060 if (LHSType->hasFloatingRepresentation())
7061 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007062
Richard Trieub80728f2011-09-06 21:43:51 +00007063 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007064 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007065 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007066
Richard Trieub80728f2011-09-06 21:43:51 +00007067 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007068 Expr::NPC_ValueDependentIsNull);
Richard Trieub80728f2011-09-06 21:43:51 +00007069 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007070 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007071
Douglas Gregorf267edd2010-06-15 21:38:40 +00007072 // All of the following pointer-related warnings are GCC extensions, except
7073 // when handling null pointer constants.
Richard Trieub80728f2011-09-06 21:43:51 +00007074 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00007075 QualType LCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00007076 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattner3a0702e2008-04-03 05:07:25 +00007077 QualType RCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00007078 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007079
David Blaikiebbafb8a2012-03-11 07:00:24 +00007080 if (getLangOpts().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00007081 if (LCanPointeeTy == RCanPointeeTy)
7082 return ResultTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00007083 if (!IsRelational &&
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007084 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7085 // Valid unless comparison between non-null pointer and function pointer
7086 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00007087 // In a SFINAE context, we treat this as a hard error to maintain
7088 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007089 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7090 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00007091 diagnoseFunctionPointerToVoidComparison(
Richard Trieub80728f2011-09-06 21:43:51 +00007092 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00007093
7094 if (isSFINAEContext())
7095 return QualType();
7096
Richard Trieub80728f2011-09-06 21:43:51 +00007097 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007098 return ResultTy;
7099 }
7100 }
Anders Carlssona95069c2010-11-04 03:17:43 +00007101
Richard Trieub80728f2011-09-06 21:43:51 +00007102 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007103 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00007104 else
7105 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007106 }
Eli Friedman16c209612009-08-23 00:27:47 +00007107 // C99 6.5.9p2 and C99 6.5.8p2
7108 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7109 RCanPointeeTy.getUnqualifiedType())) {
7110 // Valid unless a relational comparison of function pointers
Richard Trieuba63ce62011-09-09 01:45:06 +00007111 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman16c209612009-08-23 00:27:47 +00007112 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00007113 << LHSType << RHSType << LHS.get()->getSourceRange()
7114 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00007115 }
Richard Trieuba63ce62011-09-09 01:45:06 +00007116 } else if (!IsRelational &&
Eli Friedman16c209612009-08-23 00:27:47 +00007117 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7118 // Valid unless comparison between non-null pointer and function pointer
7119 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00007120 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007121 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007122 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00007123 } else {
7124 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00007125 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00007126 }
John McCall7684dde2011-03-11 04:25:25 +00007127 if (LCanPointeeTy != RCanPointeeTy) {
7128 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007129 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007130 else
Richard Trieub80728f2011-09-06 21:43:51 +00007131 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007132 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00007133 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00007134 }
Mike Stump11289f42009-09-09 15:08:12 +00007135
David Blaikiebbafb8a2012-03-11 07:00:24 +00007136 if (getLangOpts().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00007137 // Comparison of nullptr_t with itself.
Richard Trieub80728f2011-09-06 21:43:51 +00007138 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlssona95069c2010-11-04 03:17:43 +00007139 return ResultTy;
7140
Mike Stump11289f42009-09-09 15:08:12 +00007141 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007142 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00007143 if (RHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00007144 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00007145 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00007146 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7147 RHS = ImpCastExprToType(RHS.take(), LHSType,
7148 LHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007149 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007150 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007151 return ResultTy;
7152 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007153 if (LHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00007154 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00007155 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00007156 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7157 LHS = ImpCastExprToType(LHS.take(), RHSType,
7158 RHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007159 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007160 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007161 return ResultTy;
7162 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007163
7164 // Comparison of member pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00007165 if (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00007166 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7167 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007168 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00007169 else
7170 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007171 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007172
7173 // Handle scoped enumeration types specifically, since they don't promote
7174 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00007175 if (LHS.get()->getType()->isEnumeralType() &&
7176 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7177 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007178 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00007179 }
Mike Stump11289f42009-09-09 15:08:12 +00007180
Steve Naroff081c7422008-09-04 15:10:53 +00007181 // Handle block pointer types.
Richard Trieuba63ce62011-09-09 01:45:06 +00007182 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieub80728f2011-09-06 21:43:51 +00007183 RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00007184 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7185 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007186
Steve Naroff081c7422008-09-04 15:10:53 +00007187 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00007188 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007189 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00007190 << LHSType << RHSType << LHS.get()->getSourceRange()
7191 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00007192 }
Richard Trieub80728f2011-09-06 21:43:51 +00007193 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007194 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00007195 }
John Wiegley01296292011-04-08 18:41:53 +00007196
Steve Naroffe18f94c2008-09-28 01:11:11 +00007197 // Allow block pointers to be compared with null pointer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00007198 if (!IsRelational
Richard Trieub80728f2011-09-06 21:43:51 +00007199 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7200 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00007201 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00007202 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007203 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00007204 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007205 ->getPointeeType()->isVoidType())))
7206 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00007207 << LHSType << RHSType << LHS.get()->getSourceRange()
7208 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00007209 }
John McCall7684dde2011-03-11 04:25:25 +00007210 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00007211 LHS = ImpCastExprToType(LHS.take(), RHSType,
7212 RHSType->isPointerType() ? CK_BitCast
7213 : CK_AnyPointerToBlockPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00007214 else
John McCall9320b872011-09-09 05:25:32 +00007215 RHS = ImpCastExprToType(RHS.take(), LHSType,
7216 LHSType->isPointerType() ? CK_BitCast
7217 : CK_AnyPointerToBlockPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007218 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00007219 }
Steve Naroff081c7422008-09-04 15:10:53 +00007220
Richard Trieub80728f2011-09-06 21:43:51 +00007221 if (LHSType->isObjCObjectPointerType() ||
7222 RHSType->isObjCObjectPointerType()) {
7223 const PointerType *LPT = LHSType->getAs<PointerType>();
7224 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00007225 if (LPT || RPT) {
7226 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7227 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007228
Steve Naroff753567f2008-11-17 19:49:16 +00007229 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00007230 !Context.typesAreCompatible(LHSType, RHSType)) {
7231 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007232 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007233 }
John McCall7684dde2011-03-11 04:25:25 +00007234 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00007235 LHS = ImpCastExprToType(LHS.take(), RHSType,
7236 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00007237 else
John McCall9320b872011-09-09 05:25:32 +00007238 RHS = ImpCastExprToType(RHS.take(), LHSType,
7239 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007240 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00007241 }
Richard Trieub80728f2011-09-06 21:43:51 +00007242 if (LHSType->isObjCObjectPointerType() &&
7243 RHSType->isObjCObjectPointerType()) {
7244 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7245 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007246 /*isError*/false);
Jordan Rosed49a33e2012-06-08 21:14:25 +00007247 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
Jordan Rose7660f782012-07-17 17:46:40 +00007248 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
Jordan Rosed49a33e2012-06-08 21:14:25 +00007249
John McCall7684dde2011-03-11 04:25:25 +00007250 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007251 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007252 else
Richard Trieub80728f2011-09-06 21:43:51 +00007253 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007254 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00007255 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00007256 }
Richard Trieub80728f2011-09-06 21:43:51 +00007257 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7258 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00007259 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007260 bool isError = false;
Douglas Gregor0064c592012-09-14 04:35:37 +00007261 if (LangOpts.DebuggerSupport) {
7262 // Under a debugger, allow the comparison of pointers to integers,
7263 // since users tend to want to compare addresses.
7264 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
Richard Trieub80728f2011-09-06 21:43:51 +00007265 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007266 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007267 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007268 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007269 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007270 else if (getLangOpts().CPlusPlus) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00007271 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7272 isError = true;
7273 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00007274 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00007275
Chris Lattnerd99bd522009-08-23 00:03:44 +00007276 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007277 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00007278 << LHSType << RHSType << LHS.get()->getSourceRange()
7279 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007280 if (isError)
7281 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00007282 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007283
Richard Trieub80728f2011-09-06 21:43:51 +00007284 if (LHSType->isIntegerType())
7285 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00007286 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00007287 else
Richard Trieub80728f2011-09-06 21:43:51 +00007288 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00007289 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007290 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00007291 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007292
Steve Naroff4b191572008-09-04 16:56:14 +00007293 // Handle block pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00007294 if (!IsRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00007295 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7296 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007297 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007298 }
Richard Trieuba63ce62011-09-09 01:45:06 +00007299 if (!IsRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00007300 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7301 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007302 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007303 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007304
Richard Trieub80728f2011-09-06 21:43:51 +00007305 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007306}
7307
Tanya Lattner20248222012-01-16 21:02:28 +00007308
7309// Return a signed type that is of identical size and number of elements.
7310// For floating point vectors, return an integer type of identical size
7311// and number of elements.
7312QualType Sema::GetSignedVectorType(QualType V) {
7313 const VectorType *VTy = V->getAs<VectorType>();
7314 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7315 if (TypeSize == Context.getTypeSize(Context.CharTy))
7316 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7317 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7318 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7319 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7320 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7321 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7322 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7323 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7324 "Unhandled vector element size in vector compare");
7325 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7326}
7327
Nate Begeman191a6b12008-07-14 18:02:46 +00007328/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00007329/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00007330/// like a scalar comparison, a vector comparison produces a vector of integer
7331/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00007332QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007333 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007334 bool IsRelational) {
Nate Begeman191a6b12008-07-14 18:02:46 +00007335 // Check to make sure we're operating on vectors of the same type and width,
7336 // Allowing one side to be a scalar of element type.
Richard Trieubcce2f72011-09-07 01:19:57 +00007337 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00007338 if (vType.isNull())
7339 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007340
Richard Trieubcce2f72011-09-07 01:19:57 +00007341 QualType LHSType = LHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007342
Anton Yartsev530deb92011-03-27 15:36:07 +00007343 // If AltiVec, the comparison results in a numeric type, i.e.
7344 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00007345 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00007346 return Context.getLogicalOperationType();
7347
Nate Begeman191a6b12008-07-14 18:02:46 +00007348 // For non-floating point types, check for self-comparisons of the form
7349 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7350 // often indicate logic errors in the program.
Richard Trieubcce2f72011-09-07 01:19:57 +00007351 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith508ebf32011-10-28 03:31:48 +00007352 if (DeclRefExpr* DRL
7353 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7354 if (DeclRefExpr* DRR
7355 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begeman191a6b12008-07-14 18:02:46 +00007356 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007357 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007358 PDiag(diag::warn_comparison_always)
7359 << 0 // self-
7360 << 2 // "a constant"
7361 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007362 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007363
Nate Begeman191a6b12008-07-14 18:02:46 +00007364 // Check for comparisons of floating point operands using != and ==.
Richard Trieuba63ce62011-09-09 01:45:06 +00007365 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikieca043222012-01-16 05:16:03 +00007366 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieubcce2f72011-09-07 01:19:57 +00007367 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00007368 }
Tanya Lattner20248222012-01-16 21:02:28 +00007369
7370 // Return a signed type for the vector.
7371 return GetSignedVectorType(LHSType);
7372}
Mike Stump4e1f26a2009-02-19 03:04:26 +00007373
Tanya Lattner3dd33b22012-01-19 01:16:16 +00007374QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7375 SourceLocation Loc) {
Tanya Lattner20248222012-01-16 21:02:28 +00007376 // Ensure that either both operands are of the same vector type, or
7377 // one operand is of a vector type and the other is of its element type.
7378 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7379 if (vType.isNull() || vType->isFloatingType())
7380 return InvalidOperands(Loc, LHS, RHS);
7381
7382 return GetSignedVectorType(LHS.get()->getType());
Nate Begeman191a6b12008-07-14 18:02:46 +00007383}
7384
Steve Naroff218bc2b2007-05-04 21:54:46 +00007385inline QualType Sema::CheckBitwiseOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00007386 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00007387 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7388
Richard Trieubcce2f72011-09-07 01:19:57 +00007389 if (LHS.get()->getType()->isVectorType() ||
7390 RHS.get()->getType()->isVectorType()) {
7391 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7392 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00007393 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007394
Richard Trieubcce2f72011-09-07 01:19:57 +00007395 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007396 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007397
Richard Trieubcce2f72011-09-07 01:19:57 +00007398 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7399 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuba63ce62011-09-09 01:45:06 +00007400 IsCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00007401 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007402 return QualType();
Richard Trieubcce2f72011-09-07 01:19:57 +00007403 LHS = LHSResult.take();
7404 RHS = RHSResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007405
Eli Friedman93ee5ca2012-06-16 02:19:17 +00007406 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007407 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00007408 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007409}
7410
Steve Naroff218bc2b2007-05-04 21:54:46 +00007411inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieubcce2f72011-09-07 01:19:57 +00007412 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00007413
Tanya Lattner20248222012-01-16 21:02:28 +00007414 // Check vector operands differently.
7415 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7416 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7417
Chris Lattner8406c512010-07-13 19:41:32 +00007418 // Diagnose cases where the user write a logical and/or but probably meant a
7419 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7420 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00007421 if (LHS.get()->getType()->isIntegerType() &&
7422 !LHS.get()->getType()->isBooleanType() &&
7423 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00007424 // Don't warn in macros or template instantiations.
7425 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00007426 // If the RHS can be constant folded, and if it constant folds to something
7427 // that isn't 0 or 1 (which indicate a potential logical operation that
7428 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007429 // Parens on the RHS are ignored.
Richard Smith00ab3ae2011-10-16 23:01:09 +00007430 llvm::APSInt Result;
7431 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikiebbafb8a2012-03-11 07:00:24 +00007432 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith00ab3ae2011-10-16 23:01:09 +00007433 (Result != 0 && Result != 1)) {
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007434 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00007435 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007436 << (Opc == BO_LAnd ? "&&" : "||");
7437 // Suggest replacing the logical operator with the bitwise version
7438 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7439 << (Opc == BO_LAnd ? "&" : "|")
7440 << FixItHint::CreateReplacement(SourceRange(
7441 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00007442 getLangOpts())),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007443 Opc == BO_LAnd ? "&" : "|");
7444 if (Opc == BO_LAnd)
7445 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7446 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7447 << FixItHint::CreateRemoval(
7448 SourceRange(
Richard Trieubcce2f72011-09-07 01:19:57 +00007449 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007450 0, getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00007451 getLangOpts()),
Richard Trieubcce2f72011-09-07 01:19:57 +00007452 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007453 }
Chris Lattner938533d2010-07-24 01:10:11 +00007454 }
Chris Lattner8406c512010-07-13 19:41:32 +00007455
David Blaikiebbafb8a2012-03-11 07:00:24 +00007456 if (!Context.getLangOpts().CPlusPlus) {
Richard Trieubcce2f72011-09-07 01:19:57 +00007457 LHS = UsualUnaryConversions(LHS.take());
7458 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007459 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007460
Richard Trieubcce2f72011-09-07 01:19:57 +00007461 RHS = UsualUnaryConversions(RHS.take());
7462 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007463 return QualType();
7464
Richard Trieubcce2f72011-09-07 01:19:57 +00007465 if (!LHS.get()->getType()->isScalarType() ||
7466 !RHS.get()->getType()->isScalarType())
7467 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007468
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007469 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007470 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007471
John McCall4a2429a2010-06-04 00:29:51 +00007472 // The following is safe because we only use this method for
7473 // non-overloadable operands.
7474
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007475 // C++ [expr.log.and]p1
7476 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007477 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00007478 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7479 if (LHSRes.isInvalid())
7480 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007481 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00007482
Richard Trieubcce2f72011-09-07 01:19:57 +00007483 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7484 if (RHSRes.isInvalid())
7485 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007486 RHS = RHSRes;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007487
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007488 // C++ [expr.log.and]p2
7489 // C++ [expr.log.or]p2
7490 // The result is a bool.
7491 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007492}
7493
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007494/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7495/// is a read-only property; return true if so. A readonly property expression
7496/// depends on various declarations and thus must be treated specially.
7497///
Mike Stump11289f42009-09-09 15:08:12 +00007498static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007499 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7500 if (!PropExpr) return false;
7501 if (PropExpr->isImplicitProperty()) return false;
John McCallb7bd14f2010-12-02 01:19:52 +00007502
John McCall526ab472011-10-25 17:37:35 +00007503 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7504 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCallb7bd14f2010-12-02 01:19:52 +00007505 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007506 PropExpr->getBase()->getType();
7507
John McCall526ab472011-10-25 17:37:35 +00007508 if (const ObjCObjectPointerType *OPT =
7509 BaseType->getAsObjCInterfacePointerType())
7510 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7511 if (S.isPropertyReadonly(PDecl, IFace))
7512 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007513 return false;
7514}
7515
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007516static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007517 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7518 if (!ME) return false;
7519 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7520 ObjCMessageExpr *Base =
7521 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7522 if (!Base) return false;
7523 return Base->getMethodDecl() != 0;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007524}
7525
John McCall5fa2ef42012-03-13 00:37:01 +00007526/// Is the given expression (which must be 'const') a reference to a
7527/// variable which was originally non-const, but which has become
7528/// 'const' due to being captured within a block?
7529enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7530static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7531 assert(E->isLValue() && E->getType().isConstQualified());
7532 E = E->IgnoreParens();
7533
7534 // Must be a reference to a declaration from an enclosing scope.
7535 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7536 if (!DRE) return NCCK_None;
7537 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7538
7539 // The declaration must be a variable which is not declared 'const'.
7540 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7541 if (!var) return NCCK_None;
7542 if (var->getType().isConstQualified()) return NCCK_None;
7543 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7544
7545 // Decide whether the first capture was for a block or a lambda.
7546 DeclContext *DC = S.CurContext;
7547 while (DC->getParent() != var->getDeclContext())
7548 DC = DC->getParent();
7549 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7550}
7551
Chris Lattner30bd3272008-11-18 01:22:49 +00007552/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7553/// emit an error and return true. If so, return false.
7554static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianca5c5972012-04-10 17:30:10 +00007555 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007556 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007557 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007558 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007559 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7560 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007561 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7562 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007563 if (IsLV == Expr::MLV_Valid)
7564 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007565
Chris Lattner30bd3272008-11-18 01:22:49 +00007566 unsigned Diag = 0;
7567 bool NeedType = false;
7568 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00007569 case Expr::MLV_ConstQualified:
7570 Diag = diag::err_typecheck_assign_const;
7571
John McCall5fa2ef42012-03-13 00:37:01 +00007572 // Use a specialized diagnostic when we're assigning to an object
7573 // from an enclosing function or block.
7574 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7575 if (NCCK == NCCK_Block)
7576 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7577 else
7578 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7579 break;
7580 }
7581
John McCalld4631322011-06-17 06:42:21 +00007582 // In ARC, use some specialized diagnostics for occasions where we
7583 // infer 'const'. These are always pseudo-strong variables.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007584 if (S.getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00007585 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7586 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7587 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7588
John McCalld4631322011-06-17 06:42:21 +00007589 // Use the normal diagnostic if it's pseudo-__strong but the
7590 // user actually wrote 'const'.
7591 if (var->isARCPseudoStrong() &&
7592 (!var->getTypeSourceInfo() ||
7593 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7594 // There are two pseudo-strong cases:
7595 // - self
John McCall31168b02011-06-15 23:02:42 +00007596 ObjCMethodDecl *method = S.getCurMethodDecl();
7597 if (method && var == method->getSelfDecl())
Ted Kremenek1fcdaa92011-11-14 21:59:25 +00007598 Diag = method->isClassMethod()
7599 ? diag::err_typecheck_arc_assign_self_class_method
7600 : diag::err_typecheck_arc_assign_self;
John McCalld4631322011-06-17 06:42:21 +00007601
7602 // - fast enumeration variables
7603 else
John McCall31168b02011-06-15 23:02:42 +00007604 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00007605
John McCall31168b02011-06-15 23:02:42 +00007606 SourceRange Assign;
7607 if (Loc != OrigLoc)
7608 Assign = SourceRange(OrigLoc, OrigLoc);
7609 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7610 // We need to preserve the AST regardless, so migration tool
7611 // can do its job.
7612 return false;
7613 }
7614 }
7615 }
7616
7617 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007618 case Expr::MLV_ArrayType:
Richard Smitheb3cad52012-06-04 22:27:30 +00007619 case Expr::MLV_ArrayTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007620 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7621 NeedType = true;
7622 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007623 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007624 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7625 NeedType = true;
7626 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007627 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007628 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7629 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007630 case Expr::MLV_Valid:
7631 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007632 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007633 case Expr::MLV_MemberFunction:
7634 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007635 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7636 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007637 case Expr::MLV_IncompleteType:
7638 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007639 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007640 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner9bad62c2008-01-04 18:04:52 +00007641 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007642 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7643 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007644 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007645 case Expr::MLV_NoSetterProperty:
John McCall526ab472011-10-25 17:37:35 +00007646 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007647 case Expr::MLV_InvalidMessageExpression:
7648 Diag = diag::error_readonly_message_assignment;
7649 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007650 case Expr::MLV_SubObjCPropertySetting:
7651 Diag = diag::error_no_subobject_property_setting;
7652 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007653 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007654
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007655 SourceRange Assign;
7656 if (Loc != OrigLoc)
7657 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007658 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007659 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007660 else
Mike Stump11289f42009-09-09 15:08:12 +00007661 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007662 return true;
7663}
7664
Nico Weberb8124d12012-07-03 02:03:06 +00007665static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7666 SourceLocation Loc,
7667 Sema &Sema) {
7668 // C / C++ fields
Nico Weber33fd5232012-06-28 23:53:12 +00007669 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7670 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7671 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7672 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
Nico Weberb8124d12012-07-03 02:03:06 +00007673 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
Nico Weber33fd5232012-06-28 23:53:12 +00007674 }
Chris Lattner30bd3272008-11-18 01:22:49 +00007675
Nico Weberb8124d12012-07-03 02:03:06 +00007676 // Objective-C instance variables
Nico Weber33fd5232012-06-28 23:53:12 +00007677 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7678 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7679 if (OL && OR && OL->getDecl() == OR->getDecl()) {
7680 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7681 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7682 if (RL && RR && RL->getDecl() == RR->getDecl())
Nico Weberb8124d12012-07-03 02:03:06 +00007683 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
Nico Weber33fd5232012-06-28 23:53:12 +00007684 }
7685}
Chris Lattner30bd3272008-11-18 01:22:49 +00007686
7687// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +00007688QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007689 SourceLocation Loc,
7690 QualType CompoundType) {
John McCall526ab472011-10-25 17:37:35 +00007691 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7692
Chris Lattner326f7572008-11-18 01:30:42 +00007693 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007694 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007695 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007696
Richard Trieuda4f43a62011-09-07 01:33:52 +00007697 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00007698 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7699 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007700 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007701 if (CompoundType.isNull()) {
Nico Weber33fd5232012-06-28 23:53:12 +00007702 Expr *RHSCheck = RHS.get();
7703
Nico Weberb8124d12012-07-03 02:03:06 +00007704 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
Nico Weber33fd5232012-06-28 23:53:12 +00007705
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007706 QualType LHSTy(LHSType);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007707 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007708 if (RHS.isInvalid())
7709 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007710 // Special case of NSObject attributes on c-style pointer types.
7711 if (ConvTy == IncompatiblePointer &&
7712 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007713 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007714 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007715 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007716 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007717
John McCall7decc9e2010-11-18 06:31:45 +00007718 if (ConvTy == Compatible &&
Fariborz Jahaniane2a77762012-01-24 19:40:13 +00007719 LHSType->isObjCObjectType())
Fariborz Jahanian3c4225a2012-01-24 18:05:45 +00007720 Diag(Loc, diag::err_objc_object_assignment)
7721 << LHSType;
John McCall7decc9e2010-11-18 06:31:45 +00007722
Chris Lattnerea714382008-08-21 18:04:13 +00007723 // If the RHS is a unary plus or minus, check to see if they = and + are
7724 // right next to each other. If so, the user may have typo'd "x =+ 4"
7725 // instead of "x += 4".
Chris Lattnerea714382008-08-21 18:04:13 +00007726 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7727 RHSCheck = ICE->getSubExpr();
7728 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007729 if ((UO->getOpcode() == UO_Plus ||
7730 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007731 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007732 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007733 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner36c39c92009-03-08 06:51:10 +00007734 // And there is a space or other character before the subexpr of the
7735 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007736 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattnered9f14c2009-03-09 07:11:10 +00007737 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007738 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007739 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007740 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007741 }
Chris Lattnerea714382008-08-21 18:04:13 +00007742 }
John McCall31168b02011-06-15 23:02:42 +00007743
7744 if (ConvTy == Compatible) {
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007745 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
7746 // Warn about retain cycles where a block captures the LHS, but
7747 // not if the LHS is a simple variable into which the block is
7748 // being stored...unless that variable can be captured by reference!
7749 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
7750 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
7751 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
7752 checkRetainCycles(LHSExpr, RHS.get());
7753
Jordan Rosed3934582012-09-28 22:21:30 +00007754 // It is safe to assign a weak reference into a strong variable.
7755 // Although this code can still have problems:
7756 // id x = self.weakProp;
7757 // id y = self.weakProp;
7758 // we do not warn to warn spuriously when 'x' and 'y' are on separate
7759 // paths through the function. This should be revisited if
7760 // -Wrepeated-use-of-weak is made flow-sensitive.
7761 DiagnosticsEngine::Level Level =
7762 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
7763 RHS.get()->getLocStart());
7764 if (Level != DiagnosticsEngine::Ignored)
7765 getCurFunction()->markSafeWeakUse(RHS.get());
7766
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007767 } else if (getLangOpts().ObjCAutoRefCount) {
Richard Trieuda4f43a62011-09-07 01:33:52 +00007768 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007769 }
John McCall31168b02011-06-15 23:02:42 +00007770 }
Chris Lattnerea714382008-08-21 18:04:13 +00007771 } else {
7772 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007773 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007774 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007775
Chris Lattner326f7572008-11-18 01:30:42 +00007776 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007777 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007778 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007779
Richard Trieuda4f43a62011-09-07 01:33:52 +00007780 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007781
Steve Naroff98cf3e92007-06-06 18:38:38 +00007782 // C99 6.5.16p3: The type of an assignment expression is the type of the
7783 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007784 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007785 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7786 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007787 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007788 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007789 return (getLangOpts().CPlusPlus
John McCall01cbf2d2010-10-12 02:19:57 +00007790 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007791}
7792
Chris Lattner326f7572008-11-18 01:30:42 +00007793// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007794static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007795 SourceLocation Loc) {
John McCall3aef3d82011-04-10 19:13:55 +00007796 LHS = S.CheckPlaceholderExpr(LHS.take());
7797 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007798 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007799 return QualType();
7800
John McCall73d36182010-10-12 07:14:40 +00007801 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7802 // operands, but not unary promotions.
7803 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007804
John McCall34376a62010-12-04 03:47:34 +00007805 // So we treat the LHS as a ignored value, and in C++ we allow the
7806 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007807 LHS = S.IgnoredValueConversions(LHS.take());
7808 if (LHS.isInvalid())
7809 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007810
Eli Friedmanc11535c2012-05-24 00:47:05 +00007811 S.DiagnoseUnusedExprResult(LHS.get());
7812
David Blaikiebbafb8a2012-03-11 07:00:24 +00007813 if (!S.getLangOpts().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007814 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7815 if (RHS.isInvalid())
7816 return QualType();
7817 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007818 S.RequireCompleteType(Loc, RHS.get()->getType(),
7819 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007820 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007821
John Wiegley01296292011-04-08 18:41:53 +00007822 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007823}
7824
Steve Naroff7a5af782007-07-13 16:58:59 +00007825/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7826/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007827static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7828 ExprValueKind &VK,
7829 SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007830 bool IsInc, bool IsPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007831 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007832 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007833
Chris Lattner6b0cf142008-11-21 07:05:48 +00007834 QualType ResType = Op->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00007835 // Atomic types can be used for increment / decrement where the non-atomic
7836 // versions can, so ignore the _Atomic() specifier for the purpose of
7837 // checking.
7838 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7839 ResType = ResAtomicType->getValueType();
7840
Chris Lattner6b0cf142008-11-21 07:05:48 +00007841 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007842
David Blaikiebbafb8a2012-03-11 07:00:24 +00007843 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007844 // Decrement of bool is not allowed.
Richard Trieuba63ce62011-09-09 01:45:06 +00007845 if (!IsInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007846 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007847 return QualType();
7848 }
7849 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007850 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007851 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007852 // OK!
John McCallf2538342012-07-31 05:14:30 +00007853 } else if (ResType->isPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007854 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007855 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007856 return QualType();
John McCallf2538342012-07-31 05:14:30 +00007857 } else if (ResType->isObjCObjectPointerType()) {
7858 // On modern runtimes, ObjC pointer arithmetic is forbidden.
7859 // Otherwise, we just need a complete type.
7860 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7861 checkArithmeticOnObjCPointer(S, OpLoc, Op))
7862 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +00007863 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007864 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007865 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007866 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007867 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007868 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007869 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007870 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007871 IsInc, IsPrefix);
David Blaikiebbafb8a2012-03-11 07:00:24 +00007872 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev85129b82011-02-07 02:17:30 +00007873 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007874 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007875 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuba63ce62011-09-09 01:45:06 +00007876 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007877 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007878 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007879 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007880 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007881 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007882 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007883 // In C++, a prefix increment is the same type as the operand. Otherwise
7884 // (in C or with postfix), the increment is the unqualified type of the
7885 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007886 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007887 VK = VK_LValue;
7888 return ResType;
7889 } else {
7890 VK = VK_RValue;
7891 return ResType.getUnqualifiedType();
7892 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007893}
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007894
7895
Anders Carlsson806700f2008-02-01 07:15:58 +00007896/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007897/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007898/// where the declaration is needed for type checking. We only need to
7899/// handle cases when the expression references a function designator
7900/// or is an lvalue. Here are some examples:
7901/// - &(x) => x
7902/// - &*****f => f for f a function designator.
7903/// - &s.xx => s
7904/// - &s.zz[1].yy -> s, if zz is an array
7905/// - *(x + 1) -> x, if x is an array
7906/// - &"123"[2] -> 0
7907/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007908static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007909 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007910 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007911 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007912 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007913 // If this is an arrow operator, the address is an offset from
7914 // the base's value, so the object the base refers to is
7915 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007916 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007917 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007918 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007919 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007920 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007921 // FIXME: This code shouldn't be necessary! We should catch the implicit
7922 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007923 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7924 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7925 if (ICE->getSubExpr()->getType()->isArrayType())
7926 return getPrimaryDecl(ICE->getSubExpr());
7927 }
7928 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007929 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007930 case Stmt::UnaryOperatorClass: {
7931 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007932
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007933 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007934 case UO_Real:
7935 case UO_Imag:
7936 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007937 return getPrimaryDecl(UO->getSubExpr());
7938 default:
7939 return 0;
7940 }
7941 }
Steve Naroff47500512007-04-19 23:00:49 +00007942 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007943 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007944 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007945 // If the result of an implicit cast is an l-value, we care about
7946 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007947 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007948 default:
7949 return 0;
7950 }
7951}
7952
Richard Trieu5f376f62011-09-07 21:46:33 +00007953namespace {
7954 enum {
7955 AO_Bit_Field = 0,
7956 AO_Vector_Element = 1,
7957 AO_Property_Expansion = 2,
7958 AO_Register_Variable = 3,
7959 AO_No_Error = 4
7960 };
7961}
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007962/// \brief Diagnose invalid operand for address of operations.
7963///
7964/// \param Type The type of operand which cannot have its address taken.
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007965static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7966 Expr *E, unsigned Type) {
7967 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7968}
7969
Steve Naroff47500512007-04-19 23:00:49 +00007970/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007971/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007972/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007973/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007974/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007975/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007976/// we allow the '&' but retain the overloaded-function type.
John McCall526ab472011-10-25 17:37:35 +00007977static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall4bc41ae2010-11-18 19:01:18 +00007978 SourceLocation OpLoc) {
John McCall526ab472011-10-25 17:37:35 +00007979 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7980 if (PTy->getKind() == BuiltinType::Overload) {
7981 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7982 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7983 << OrigOp.get()->getSourceRange();
7984 return QualType();
7985 }
7986
7987 return S.Context.OverloadTy;
7988 }
7989
7990 if (PTy->getKind() == BuiltinType::UnknownAny)
7991 return S.Context.UnknownAnyTy;
7992
7993 if (PTy->getKind() == BuiltinType::BoundMember) {
7994 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7995 << OrigOp.get()->getSourceRange();
Douglas Gregor668d3622011-10-09 19:10:41 +00007996 return QualType();
7997 }
John McCall526ab472011-10-25 17:37:35 +00007998
7999 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
8000 if (OrigOp.isInvalid()) return QualType();
John McCall0009fcc2011-04-26 20:42:42 +00008001 }
John McCall8d08b9b2010-08-27 09:08:28 +00008002
John McCall526ab472011-10-25 17:37:35 +00008003 if (OrigOp.get()->isTypeDependent())
8004 return S.Context.DependentTy;
8005
8006 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00008007
John McCall8d08b9b2010-08-27 09:08:28 +00008008 // Make sure to ignore parentheses in subsequent checks
John McCall526ab472011-10-25 17:37:35 +00008009 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00008010
David Blaikiebbafb8a2012-03-11 07:00:24 +00008011 if (S.getLangOpts().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00008012 // Implement C99-only parts of addressof rules.
8013 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00008014 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00008015 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8016 // (assuming the deref expression is valid).
8017 return uOp->getSubExpr()->getType();
8018 }
8019 // Technically, there should be a check for array subscript
8020 // expressions here, but the result of one is always an lvalue anyway.
8021 }
John McCallf3a88602011-02-03 08:15:49 +00008022 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00008023 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5f376f62011-09-07 21:46:33 +00008024 unsigned AddressOfError = AO_No_Error;
Nuno Lopes17f345f2008-12-16 22:59:47 +00008025
Fariborz Jahanian071caef2011-03-26 19:48:30 +00008026 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00008027 bool sfinae = S.isSFINAEContext();
8028 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8029 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008030 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00008031 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008032 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00008033 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008034 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00008035 } else if (lval == Expr::LV_MemberFunction) {
8036 // If it's an instance method, make a member pointer.
8037 // The expression must have exactly the form &A::foo.
8038
8039 // If the underlying expression isn't a decl ref, give up.
8040 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008041 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00008042 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00008043 return QualType();
8044 }
8045 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8046 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8047
8048 // The id-expression was parenthesized.
John McCall526ab472011-10-25 17:37:35 +00008049 if (OrigOp.get() != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00008050 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00008051 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00008052
8053 // The method was named without a qualifier.
8054 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008055 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008056 << op->getSourceRange();
8057 }
8058
John McCall4bc41ae2010-11-18 19:01:18 +00008059 return S.Context.getMemberPointerType(op->getType(),
8060 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00008061 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00008062 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008063 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00008064 if (!op->getType()->isFunctionType()) {
John McCall526ab472011-10-25 17:37:35 +00008065 // Use a special diagnostic for loads from property references.
John McCallfe96e0b2011-11-06 09:01:30 +00008066 if (isa<PseudoObjectExpr>(op)) {
John McCall526ab472011-10-25 17:37:35 +00008067 AddressOfError = AO_Property_Expansion;
8068 } else {
8069 // FIXME: emit more specific diag...
8070 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8071 << op->getSourceRange();
8072 return QualType();
8073 }
Steve Naroff35d85152007-05-07 00:24:15 +00008074 }
John McCall086a4642010-11-24 05:12:34 +00008075 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008076 // The operand cannot be a bit-field
Richard Trieu5f376f62011-09-07 21:46:33 +00008077 AddressOfError = AO_Bit_Field;
John McCall086a4642010-11-24 05:12:34 +00008078 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00008079 // The operand cannot be an element of a vector
Richard Trieu5f376f62011-09-07 21:46:33 +00008080 AddressOfError = AO_Vector_Element;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00008081 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00008082 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00008083 // with the register storage-class specifier.
8084 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00008085 // in C++ it is not error to take address of a register
8086 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00008087 if (vd->getStorageClass() == SC_Register &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008088 !S.getLangOpts().CPlusPlus) {
Richard Trieu5f376f62011-09-07 21:46:33 +00008089 AddressOfError = AO_Register_Variable;
Steve Naroff35d85152007-05-07 00:24:15 +00008090 }
John McCalld14a8642009-11-21 08:51:07 +00008091 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008092 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00008093 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00008094 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008095 // Could be a pointer to member, though, if there is an explicit
8096 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00008097 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008098 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008099 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00008100 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008101 S.Diag(OpLoc,
8102 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00008103 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008104 return QualType();
8105 }
Mike Stump11289f42009-09-09 15:08:12 +00008106
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00008107 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8108 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00008109 return S.Context.getMemberPointerType(op->getType(),
8110 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00008111 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008112 }
Eli Friedman755c0c92011-08-26 20:28:17 +00008113 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikie83d382b2011-09-23 05:06:16 +00008114 llvm_unreachable("Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00008115 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008116
Richard Trieu5f376f62011-09-07 21:46:33 +00008117 if (AddressOfError != AO_No_Error) {
8118 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8119 return QualType();
8120 }
8121
Eli Friedmance7f9002009-05-16 23:27:50 +00008122 if (lval == Expr::LV_IncompleteVoidType) {
8123 // Taking the address of a void variable is technically illegal, but we
8124 // allow it in cases which are otherwise valid.
8125 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00008126 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00008127 }
8128
Steve Naroff47500512007-04-19 23:00:49 +00008129 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00008130 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00008131 return S.Context.getObjCObjectPointerType(op->getType());
8132 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00008133}
8134
Chris Lattner9156f1b2010-07-05 19:17:26 +00008135/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00008136static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8137 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008138 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008139 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008140
John Wiegley01296292011-04-08 18:41:53 +00008141 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8142 if (ConvResult.isInvalid())
8143 return QualType();
8144 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00008145 QualType OpTy = Op->getType();
8146 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00008147
8148 if (isa<CXXReinterpretCastExpr>(Op)) {
8149 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8150 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8151 Op->getSourceRange());
8152 }
8153
Chris Lattner9156f1b2010-07-05 19:17:26 +00008154 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8155 // is an incomplete type or void. It would be possible to warn about
8156 // dereferencing a void pointer, but it's completely well-defined, and such a
8157 // warning is unlikely to catch any mistakes.
8158 if (const PointerType *PT = OpTy->getAs<PointerType>())
8159 Result = PT->getPointeeType();
8160 else if (const ObjCObjectPointerType *OPT =
8161 OpTy->getAs<ObjCObjectPointerType>())
8162 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00008163 else {
John McCall3aef3d82011-04-10 19:13:55 +00008164 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00008165 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008166 if (PR.take() != Op)
8167 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00008168 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008169
Chris Lattner9156f1b2010-07-05 19:17:26 +00008170 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008171 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00008172 << OpTy << Op->getSourceRange();
8173 return QualType();
8174 }
John McCall4bc41ae2010-11-18 19:01:18 +00008175
8176 // Dereferences are usually l-values...
8177 VK = VK_LValue;
8178
8179 // ...except that certain expressions are never l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008180 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00008181 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00008182
8183 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00008184}
Steve Naroff218bc2b2007-05-04 21:54:46 +00008185
John McCalle3027922010-08-25 11:45:40 +00008186static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00008187 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008188 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008189 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00008190 default: llvm_unreachable("Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00008191 case tok::periodstar: Opc = BO_PtrMemD; break;
8192 case tok::arrowstar: Opc = BO_PtrMemI; break;
8193 case tok::star: Opc = BO_Mul; break;
8194 case tok::slash: Opc = BO_Div; break;
8195 case tok::percent: Opc = BO_Rem; break;
8196 case tok::plus: Opc = BO_Add; break;
8197 case tok::minus: Opc = BO_Sub; break;
8198 case tok::lessless: Opc = BO_Shl; break;
8199 case tok::greatergreater: Opc = BO_Shr; break;
8200 case tok::lessequal: Opc = BO_LE; break;
8201 case tok::less: Opc = BO_LT; break;
8202 case tok::greaterequal: Opc = BO_GE; break;
8203 case tok::greater: Opc = BO_GT; break;
8204 case tok::exclaimequal: Opc = BO_NE; break;
8205 case tok::equalequal: Opc = BO_EQ; break;
8206 case tok::amp: Opc = BO_And; break;
8207 case tok::caret: Opc = BO_Xor; break;
8208 case tok::pipe: Opc = BO_Or; break;
8209 case tok::ampamp: Opc = BO_LAnd; break;
8210 case tok::pipepipe: Opc = BO_LOr; break;
8211 case tok::equal: Opc = BO_Assign; break;
8212 case tok::starequal: Opc = BO_MulAssign; break;
8213 case tok::slashequal: Opc = BO_DivAssign; break;
8214 case tok::percentequal: Opc = BO_RemAssign; break;
8215 case tok::plusequal: Opc = BO_AddAssign; break;
8216 case tok::minusequal: Opc = BO_SubAssign; break;
8217 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8218 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8219 case tok::ampequal: Opc = BO_AndAssign; break;
8220 case tok::caretequal: Opc = BO_XorAssign; break;
8221 case tok::pipeequal: Opc = BO_OrAssign; break;
8222 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008223 }
8224 return Opc;
8225}
8226
John McCalle3027922010-08-25 11:45:40 +00008227static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00008228 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008229 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00008230 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00008231 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00008232 case tok::plusplus: Opc = UO_PreInc; break;
8233 case tok::minusminus: Opc = UO_PreDec; break;
8234 case tok::amp: Opc = UO_AddrOf; break;
8235 case tok::star: Opc = UO_Deref; break;
8236 case tok::plus: Opc = UO_Plus; break;
8237 case tok::minus: Opc = UO_Minus; break;
8238 case tok::tilde: Opc = UO_Not; break;
8239 case tok::exclaim: Opc = UO_LNot; break;
8240 case tok::kw___real: Opc = UO_Real; break;
8241 case tok::kw___imag: Opc = UO_Imag; break;
8242 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00008243 }
8244 return Opc;
8245}
8246
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008247/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8248/// This warning is only emitted for builtin assignment operations. It is also
8249/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +00008250static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008251 SourceLocation OpLoc) {
8252 if (!S.ActiveTemplateInstantiations.empty())
8253 return;
8254 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8255 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008256 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8257 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8258 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8259 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8260 if (!LHSDeclRef || !RHSDeclRef ||
8261 LHSDeclRef->getLocation().isMacroID() ||
8262 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008263 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008264 const ValueDecl *LHSDecl =
8265 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8266 const ValueDecl *RHSDecl =
8267 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8268 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008269 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008270 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008271 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008272 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008273 if (RefTy->getPointeeType().isVolatileQualified())
8274 return;
8275
8276 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +00008277 << LHSDeclRef->getType()
8278 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008279}
8280
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008281/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8282/// operator @p Opc at location @c TokLoc. This routine only supports
8283/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00008284ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008285 BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008286 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008287 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl67766732012-02-27 20:34:02 +00008288 // The syntax only allows initializer lists on the RHS of assignment,
8289 // so we don't need to worry about accepting invalid code for
8290 // non-assignment operators.
8291 // C++11 5.17p9:
8292 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8293 // of x = {} is x = T().
8294 InitializationKind Kind =
8295 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8296 InitializedEntity Entity =
8297 InitializedEntity::InitializeTemporary(LHSExpr->getType());
8298 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00008299 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
Sebastian Redl67766732012-02-27 20:34:02 +00008300 if (Init.isInvalid())
8301 return Init;
8302 RHSExpr = Init.take();
8303 }
8304
Richard Trieu4a287fb2011-09-07 01:49:20 +00008305 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008306 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008307 // The following two variables are used for compound assignment operators
8308 QualType CompLHSTy; // Type of LHS after promotions for computation
8309 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00008310 ExprValueKind VK = VK_RValue;
8311 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008312
8313 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008314 case BO_Assign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008315 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008316 if (getLangOpts().CPlusPlus &&
Richard Trieu4a287fb2011-09-07 01:49:20 +00008317 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8318 VK = LHS.get()->getValueKind();
8319 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008320 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008321 if (!ResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00008322 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008323 break;
John McCalle3027922010-08-25 11:45:40 +00008324 case BO_PtrMemD:
8325 case BO_PtrMemI:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008326 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008327 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00008328 break;
John McCalle3027922010-08-25 11:45:40 +00008329 case BO_Mul:
8330 case BO_Div:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008331 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00008332 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008333 break;
John McCalle3027922010-08-25 11:45:40 +00008334 case BO_Rem:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008335 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008336 break;
John McCalle3027922010-08-25 11:45:40 +00008337 case BO_Add:
Nico Weberccec40d2012-03-02 22:01:22 +00008338 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008339 break;
John McCalle3027922010-08-25 11:45:40 +00008340 case BO_Sub:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008341 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008342 break;
John McCalle3027922010-08-25 11:45:40 +00008343 case BO_Shl:
8344 case BO_Shr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008345 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008346 break;
John McCalle3027922010-08-25 11:45:40 +00008347 case BO_LE:
8348 case BO_LT:
8349 case BO_GE:
8350 case BO_GT:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008351 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008352 break;
John McCalle3027922010-08-25 11:45:40 +00008353 case BO_EQ:
8354 case BO_NE:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008355 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008356 break;
John McCalle3027922010-08-25 11:45:40 +00008357 case BO_And:
8358 case BO_Xor:
8359 case BO_Or:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008360 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008361 break;
John McCalle3027922010-08-25 11:45:40 +00008362 case BO_LAnd:
8363 case BO_LOr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008364 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008365 break;
John McCalle3027922010-08-25 11:45:40 +00008366 case BO_MulAssign:
8367 case BO_DivAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008368 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00008369 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008370 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008371 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8372 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008373 break;
John McCalle3027922010-08-25 11:45:40 +00008374 case BO_RemAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008375 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008376 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008377 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8378 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008379 break;
John McCalle3027922010-08-25 11:45:40 +00008380 case BO_AddAssign:
Nico Weberccec40d2012-03-02 22:01:22 +00008381 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu4a287fb2011-09-07 01:49:20 +00008382 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8383 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008384 break;
John McCalle3027922010-08-25 11:45:40 +00008385 case BO_SubAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008386 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8387 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8388 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008389 break;
John McCalle3027922010-08-25 11:45:40 +00008390 case BO_ShlAssign:
8391 case BO_ShrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008392 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008393 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008394 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8395 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008396 break;
John McCalle3027922010-08-25 11:45:40 +00008397 case BO_AndAssign:
8398 case BO_XorAssign:
8399 case BO_OrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008400 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008401 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008402 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8403 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008404 break;
John McCalle3027922010-08-25 11:45:40 +00008405 case BO_Comma:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008406 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikiebbafb8a2012-03-11 07:00:24 +00008407 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu4a287fb2011-09-07 01:49:20 +00008408 VK = RHS.get()->getValueKind();
8409 OK = RHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008410 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008411 break;
8412 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008413 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00008414 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008415
8416 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu4a287fb2011-09-07 01:49:20 +00008417 CheckArrayAccess(LHS.get());
8418 CheckArrayAccess(RHS.get());
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008419
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008420 if (CompResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00008421 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
Lang Hames5de91cc2012-10-02 04:45:10 +00008422 ResultTy, VK, OK, OpLoc,
8423 FPFeatures.fp_contract));
David Blaikiebbafb8a2012-03-11 07:00:24 +00008424 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieucfc491d2011-08-02 04:35:43 +00008425 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00008426 VK = VK_LValue;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008427 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008428 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008429 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00008430 ResultTy, VK, OK, CompLHSTy,
Lang Hames5de91cc2012-10-02 04:45:10 +00008431 CompResultTy, OpLoc,
8432 FPFeatures.fp_contract));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008433}
8434
Sebastian Redl44615072009-10-27 12:10:02 +00008435/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8436/// operators are mixed in a way that suggests that the programmer forgot that
8437/// comparison operators have higher precedence. The most typical example of
8438/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00008439static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008440 SourceLocation OpLoc, Expr *LHSExpr,
8441 Expr *RHSExpr) {
Sebastian Redl44615072009-10-27 12:10:02 +00008442 typedef BinaryOperator BinOp;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008443 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8444 RHSopc = static_cast<BinOp::Opcode>(-1);
8445 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8446 LHSopc = BO->getOpcode();
8447 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8448 RHSopc = BO->getOpcode();
Sebastian Redl43028242009-10-26 15:24:15 +00008449
8450 // Subs are not binary operators.
Richard Trieu4a287fb2011-09-07 01:49:20 +00008451 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl43028242009-10-26 15:24:15 +00008452 return;
8453
8454 // Bitwise operations are sometimes used as eager logical ops.
8455 // Don't diagnose this.
Richard Trieu4a287fb2011-09-07 01:49:20 +00008456 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8457 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00008458 return;
8459
Richard Trieu4a287fb2011-09-07 01:49:20 +00008460 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8461 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00008462 if (!isLeftComp && !isRightComp) return;
8463
Richard Trieu4a287fb2011-09-07 01:49:20 +00008464 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8465 OpLoc)
8466 : SourceRange(OpLoc, RHSExpr->getLocEnd());
David Blaikie1d202a62012-10-08 01:11:04 +00008467 StringRef OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8468 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00008469 SourceRange ParensRange = isLeftComp ?
Richard Trieu4a287fb2011-09-07 01:49:20 +00008470 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8471 RHSExpr->getLocEnd())
8472 : SourceRange(LHSExpr->getLocStart(),
8473 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu73088052011-08-10 22:41:34 +00008474
8475 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8476 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8477 SuggestParentheses(Self, OpLoc,
David Blaikiedac86fd2012-10-08 01:19:49 +00008478 Self.PDiag(diag::note_precedence_silence) << OpStr,
Nico Webercdfb1ae2012-06-03 07:07:00 +00008479 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu73088052011-08-10 22:41:34 +00008480 SuggestParentheses(Self, OpLoc,
8481 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8482 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00008483}
8484
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008485/// \brief It accepts a '&' expr that is inside a '|' one.
8486/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8487/// in parentheses.
8488static void
8489EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8490 BinaryOperator *Bop) {
8491 assert(Bop->getOpcode() == BO_And);
8492 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8493 << Bop->getSourceRange() << OpLoc;
8494 SuggestParentheses(Self, Bop->getOperatorLoc(),
David Blaikiedac86fd2012-10-08 01:19:49 +00008495 Self.PDiag(diag::note_precedence_silence)
8496 << Bop->getOpcodeStr(),
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008497 Bop->getSourceRange());
8498}
8499
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008500/// \brief It accepts a '&&' expr that is inside a '||' one.
8501/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8502/// in parentheses.
8503static void
8504EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008505 BinaryOperator *Bop) {
8506 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008507 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8508 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008509 SuggestParentheses(Self, Bop->getOperatorLoc(),
David Blaikiedac86fd2012-10-08 01:19:49 +00008510 Self.PDiag(diag::note_precedence_silence)
8511 << Bop->getOpcodeStr(),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008512 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008513}
8514
8515/// \brief Returns true if the given expression can be evaluated as a constant
8516/// 'true'.
8517static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8518 bool Res;
8519 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8520}
8521
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008522/// \brief Returns true if the given expression can be evaluated as a constant
8523/// 'false'.
8524static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8525 bool Res;
8526 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8527}
8528
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008529/// \brief Look for '&&' in the left hand of a '||' expr.
8530static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008531 Expr *LHSExpr, Expr *RHSExpr) {
8532 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008533 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008534 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008535 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008536 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008537 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8538 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8539 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8540 } else if (Bop->getOpcode() == BO_LOr) {
8541 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8542 // If it's "a || b && 1 || c" we didn't warn earlier for
8543 // "a || b && 1", but warn now.
8544 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8545 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8546 }
8547 }
8548 }
8549}
8550
8551/// \brief Look for '&&' in the right hand of a '||' expr.
8552static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008553 Expr *LHSExpr, Expr *RHSExpr) {
8554 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008555 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008556 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008557 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008558 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008559 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8560 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8561 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008562 }
8563 }
8564}
8565
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008566/// \brief Look for '&' in the left or right hand of a '|' expr.
8567static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8568 Expr *OrArg) {
8569 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8570 if (Bop->getOpcode() == BO_And)
8571 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8572 }
8573}
8574
David Blaikie15f17cb2012-10-05 00:41:03 +00008575static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
8576 Expr *SubExpr, StringRef shift) {
8577 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
8578 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
David Blaikiedac86fd2012-10-08 01:19:49 +00008579 StringRef Op = Bop->getOpcodeStr();
David Blaikie15f17cb2012-10-05 00:41:03 +00008580 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
David Blaikiedac86fd2012-10-08 01:19:49 +00008581 << Bop->getSourceRange() << OpLoc << Op << shift;
David Blaikie15f17cb2012-10-05 00:41:03 +00008582 SuggestParentheses(S, Bop->getOperatorLoc(),
David Blaikiedac86fd2012-10-08 01:19:49 +00008583 S.PDiag(diag::note_precedence_silence) << Op,
David Blaikie15f17cb2012-10-05 00:41:03 +00008584 Bop->getSourceRange());
8585 }
8586 }
8587}
8588
Sebastian Redl43028242009-10-26 15:24:15 +00008589/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008590/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008591static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008592 SourceLocation OpLoc, Expr *LHSExpr,
8593 Expr *RHSExpr){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008594 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008595 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008596 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008597
8598 // Diagnose "arg1 & arg2 | arg3"
8599 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008600 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8601 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008602 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008603
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008604 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8605 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008606 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008607 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8608 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008609 }
David Blaikie15f17cb2012-10-05 00:41:03 +00008610
8611 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
8612 || Opc == BO_Shr) {
David Blaikiedac86fd2012-10-08 01:19:49 +00008613 StringRef shift = BinaryOperator::getOpcodeStr(Opc);
David Blaikie15f17cb2012-10-05 00:41:03 +00008614 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, shift);
8615 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, shift);
8616 }
Sebastian Redl43028242009-10-26 15:24:15 +00008617}
8618
Steve Naroff218bc2b2007-05-04 21:54:46 +00008619// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008620ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008621 tok::TokenKind Kind,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008622 Expr *LHSExpr, Expr *RHSExpr) {
John McCalle3027922010-08-25 11:45:40 +00008623 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008624 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8625 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008626
Sebastian Redl43028242009-10-26 15:24:15 +00008627 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008628 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +00008629
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008630 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor5287f092009-11-05 00:51:44 +00008631}
8632
John McCall526ab472011-10-25 17:37:35 +00008633/// Build an overloaded binary operator expression in the given scope.
8634static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8635 BinaryOperatorKind Opc,
8636 Expr *LHS, Expr *RHS) {
8637 // Find all of the overloaded operators visible from this
8638 // point. We perform both an operator-name lookup from the local
8639 // scope and an argument-dependent lookup based on the types of
8640 // the arguments.
8641 UnresolvedSet<16> Functions;
8642 OverloadedOperatorKind OverOp
8643 = BinaryOperator::getOverloadedOperator(Opc);
8644 if (Sc && OverOp != OO_None)
8645 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8646 RHS->getType(), Functions);
8647
8648 // Build the (potentially-overloaded, potentially-dependent)
8649 // binary operation.
8650 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8651}
8652
John McCalldadc5752010-08-24 06:29:42 +00008653ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008654 BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008655 Expr *LHSExpr, Expr *RHSExpr) {
John McCall9a43e122011-10-28 01:04:34 +00008656 // We want to end up calling one of checkPseudoObjectAssignment
8657 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8658 // both expressions are overloadable or either is type-dependent),
8659 // or CreateBuiltinBinOp (in any other case). We also want to get
8660 // any placeholder types out of the way.
8661
John McCall526ab472011-10-25 17:37:35 +00008662 // Handle pseudo-objects in the LHS.
8663 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8664 // Assignments with a pseudo-object l-value need special analysis.
8665 if (pty->getKind() == BuiltinType::PseudoObject &&
8666 BinaryOperator::isAssignmentOp(Opc))
8667 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8668
8669 // Don't resolve overloads if the other type is overloadable.
8670 if (pty->getKind() == BuiltinType::Overload) {
8671 // We can't actually test that if we still have a placeholder,
8672 // though. Fortunately, none of the exceptions we see in that
John McCall9a43e122011-10-28 01:04:34 +00008673 // code below are valid when the LHS is an overload set. Note
8674 // that an overload set can be dependently-typed, but it never
8675 // instantiates to having an overloadable type.
John McCall526ab472011-10-25 17:37:35 +00008676 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8677 if (resolvedRHS.isInvalid()) return ExprError();
8678 RHSExpr = resolvedRHS.take();
8679
John McCall9a43e122011-10-28 01:04:34 +00008680 if (RHSExpr->isTypeDependent() ||
8681 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008682 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8683 }
8684
8685 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8686 if (LHS.isInvalid()) return ExprError();
8687 LHSExpr = LHS.take();
8688 }
8689
8690 // Handle pseudo-objects in the RHS.
8691 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8692 // An overload in the RHS can potentially be resolved by the type
8693 // being assigned to.
John McCall9a43e122011-10-28 01:04:34 +00008694 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8695 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8696 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8697
Eli Friedman419b1ff2012-01-17 21:27:43 +00008698 if (LHSExpr->getType()->isOverloadableType())
8699 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8700
John McCall526ab472011-10-25 17:37:35 +00008701 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCall9a43e122011-10-28 01:04:34 +00008702 }
John McCall526ab472011-10-25 17:37:35 +00008703
8704 // Don't resolve overloads if the other type is overloadable.
8705 if (pty->getKind() == BuiltinType::Overload &&
8706 LHSExpr->getType()->isOverloadableType())
8707 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8708
8709 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8710 if (!resolvedRHS.isUsable()) return ExprError();
8711 RHSExpr = resolvedRHS.take();
8712 }
8713
David Blaikiebbafb8a2012-03-11 07:00:24 +00008714 if (getLangOpts().CPlusPlus) {
John McCall9a43e122011-10-28 01:04:34 +00008715 // If either expression is type-dependent, always build an
8716 // overloaded op.
8717 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8718 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008719
John McCall9a43e122011-10-28 01:04:34 +00008720 // Otherwise, build an overloaded op if either expression has an
8721 // overloadable type.
8722 if (LHSExpr->getType()->isOverloadableType() ||
8723 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008724 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb5d49352009-01-19 22:31:54 +00008725 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008726
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008727 // Build a built-in binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008728 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008729}
8730
John McCalldadc5752010-08-24 06:29:42 +00008731ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008732 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008733 Expr *InputExpr) {
8734 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008735 ExprValueKind VK = VK_RValue;
8736 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008737 QualType resultType;
8738 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008739 case UO_PreInc:
8740 case UO_PreDec:
8741 case UO_PostInc:
8742 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008743 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008744 Opc == UO_PreInc ||
8745 Opc == UO_PostInc,
8746 Opc == UO_PreInc ||
8747 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008748 break;
John McCalle3027922010-08-25 11:45:40 +00008749 case UO_AddrOf:
John McCall526ab472011-10-25 17:37:35 +00008750 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008751 break;
John McCall31996342011-04-07 08:22:57 +00008752 case UO_Deref: {
John Wiegley01296292011-04-08 18:41:53 +00008753 Input = DefaultFunctionArrayLvalueConversion(Input.take());
Eli Friedman34866c72012-08-31 00:14:07 +00008754 if (Input.isInvalid()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008755 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008756 break;
John McCall31996342011-04-07 08:22:57 +00008757 }
John McCalle3027922010-08-25 11:45:40 +00008758 case UO_Plus:
8759 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008760 Input = UsualUnaryConversions(Input.take());
8761 if (Input.isInvalid()) return ExprError();
8762 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008763 if (resultType->isDependentType())
8764 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008765 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8766 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008767 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008768 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregord08452f2008-11-19 15:42:04 +00008769 resultType->isEnumeralType())
8770 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008771 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008772 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008773 resultType->isPointerType())
8774 break;
8775
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008776 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008777 << resultType << Input.get()->getSourceRange());
8778
John McCalle3027922010-08-25 11:45:40 +00008779 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008780 Input = UsualUnaryConversions(Input.take());
8781 if (Input.isInvalid()) return ExprError();
8782 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008783 if (resultType->isDependentType())
8784 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008785 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8786 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8787 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008788 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008789 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008790 else if (resultType->hasIntegerRepresentation())
8791 break;
John McCall526ab472011-10-25 17:37:35 +00008792 else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008793 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008794 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008795 }
Steve Naroff35d85152007-05-07 00:24:15 +00008796 break;
John Wiegley01296292011-04-08 18:41:53 +00008797
John McCalle3027922010-08-25 11:45:40 +00008798 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008799 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008800 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8801 if (Input.isInvalid()) return ExprError();
8802 resultType = Input.get()->getType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00008803
8804 // Though we still have to promote half FP to float...
8805 if (resultType->isHalfType()) {
8806 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8807 resultType = Context.FloatTy;
8808 }
8809
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008810 if (resultType->isDependentType())
8811 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008812 if (resultType->isScalarType()) {
8813 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008814 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008815 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8816 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008817 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8818 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008819 }
Tanya Lattner3dd33b22012-01-19 01:16:16 +00008820 } else if (resultType->isExtVectorType()) {
Tanya Lattner20248222012-01-16 21:02:28 +00008821 // Vector logical not returns the signed variant of the operand type.
8822 resultType = GetSignedVectorType(resultType);
8823 break;
John McCall36226622010-10-12 02:09:17 +00008824 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008825 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008826 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008827 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008828
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008829 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008830 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008831 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008832 break;
John McCalle3027922010-08-25 11:45:40 +00008833 case UO_Real:
8834 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008835 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smith0b6b8e42012-02-18 20:53:32 +00008836 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8837 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley01296292011-04-08 18:41:53 +00008838 if (Input.isInvalid()) return ExprError();
Richard Smith0b6b8e42012-02-18 20:53:32 +00008839 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8840 if (Input.get()->getValueKind() != VK_RValue &&
8841 Input.get()->getObjectKind() == OK_Ordinary)
8842 VK = Input.get()->getValueKind();
David Blaikiebbafb8a2012-03-11 07:00:24 +00008843 } else if (!getLangOpts().CPlusPlus) {
Richard Smith0b6b8e42012-02-18 20:53:32 +00008844 // In C, a volatile scalar is read by __imag. In C++, it is not.
8845 Input = DefaultLvalueConversion(Input.take());
8846 }
Chris Lattner30b5dd02007-08-24 21:16:53 +00008847 break;
John McCalle3027922010-08-25 11:45:40 +00008848 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008849 resultType = Input.get()->getType();
8850 VK = Input.get()->getValueKind();
8851 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008852 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008853 }
John Wiegley01296292011-04-08 18:41:53 +00008854 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008855 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008856
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008857 // Check for array bounds violations in the operand of the UnaryOperator,
8858 // except for the '*' and '&' operators that have to be handled specially
8859 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8860 // that are explicitly defined as valid by the standard).
8861 if (Opc != UO_AddrOf && Opc != UO_Deref)
8862 CheckArrayAccess(Input.get());
8863
John Wiegley01296292011-04-08 18:41:53 +00008864 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008865 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008866}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008867
Douglas Gregor72341032011-12-14 21:23:13 +00008868/// \brief Determine whether the given expression is a qualified member
8869/// access expression, of a form that could be turned into a pointer to member
8870/// with the address-of operator.
8871static bool isQualifiedMemberAccess(Expr *E) {
8872 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8873 if (!DRE->getQualifier())
8874 return false;
8875
8876 ValueDecl *VD = DRE->getDecl();
8877 if (!VD->isCXXClassMember())
8878 return false;
8879
8880 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8881 return true;
8882 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8883 return Method->isInstance();
8884
8885 return false;
8886 }
8887
8888 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8889 if (!ULE->getQualifier())
8890 return false;
8891
8892 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8893 DEnd = ULE->decls_end();
8894 D != DEnd; ++D) {
8895 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8896 if (Method->isInstance())
8897 return true;
8898 } else {
8899 // Overload set does not contain methods.
8900 break;
8901 }
8902 }
8903
8904 return false;
8905 }
8906
8907 return false;
8908}
8909
John McCalldadc5752010-08-24 06:29:42 +00008910ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008911 UnaryOperatorKind Opc, Expr *Input) {
John McCall526ab472011-10-25 17:37:35 +00008912 // First things first: handle placeholders so that the
8913 // overloaded-operator check considers the right type.
8914 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8915 // Increment and decrement of pseudo-object references.
8916 if (pty->getKind() == BuiltinType::PseudoObject &&
8917 UnaryOperator::isIncrementDecrementOp(Opc))
8918 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8919
8920 // extension is always a builtin operator.
8921 if (Opc == UO_Extension)
8922 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8923
8924 // & gets special logic for several kinds of placeholder.
8925 // The builtin code knows what to do.
8926 if (Opc == UO_AddrOf &&
8927 (pty->getKind() == BuiltinType::Overload ||
8928 pty->getKind() == BuiltinType::UnknownAny ||
8929 pty->getKind() == BuiltinType::BoundMember))
8930 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8931
8932 // Anything else needs to be handled now.
8933 ExprResult Result = CheckPlaceholderExpr(Input);
8934 if (Result.isInvalid()) return ExprError();
8935 Input = Result.take();
8936 }
8937
David Blaikiebbafb8a2012-03-11 07:00:24 +00008938 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregor72341032011-12-14 21:23:13 +00008939 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8940 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008941 // Find all of the overloaded operators visible from this
8942 // point. We perform both an operator-name lookup from the local
8943 // scope and an argument-dependent lookup based on the types of
8944 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008945 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008946 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008947 if (S && OverOp != OO_None)
8948 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8949 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008950
John McCallb268a282010-08-23 23:25:46 +00008951 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008952 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008953
John McCallb268a282010-08-23 23:25:46 +00008954 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008955}
8956
Douglas Gregor5287f092009-11-05 00:51:44 +00008957// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008958ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008959 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008960 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008961}
8962
Steve Naroff66356bd2007-09-16 14:56:35 +00008963/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008964ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008965 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008966 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008967 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008968 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008969 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008970}
8971
John McCall31168b02011-06-15 23:02:42 +00008972/// Given the last statement in a statement-expression, check whether
8973/// the result is a producing expression (like a call to an
8974/// ns_returns_retained function) and, if so, rebuild it to hoist the
8975/// release out of the full-expression. Otherwise, return null.
8976/// Cannot fail.
Richard Trieuba63ce62011-09-09 01:45:06 +00008977static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCall31168b02011-06-15 23:02:42 +00008978 // Should always be wrapped with one of these.
Richard Trieuba63ce62011-09-09 01:45:06 +00008979 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCall31168b02011-06-15 23:02:42 +00008980 if (!cleanups) return 0;
8981
8982 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall2d637d22011-09-10 06:18:15 +00008983 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCall31168b02011-06-15 23:02:42 +00008984 return 0;
8985
8986 // Splice out the cast. This shouldn't modify any interesting
8987 // features of the statement.
8988 Expr *producer = cast->getSubExpr();
8989 assert(producer->getType() == cast->getType());
8990 assert(producer->getValueKind() == cast->getValueKind());
8991 cleanups->setSubExpr(producer);
8992 return cleanups;
8993}
8994
John McCall3abee492012-04-04 01:27:53 +00008995void Sema::ActOnStartStmtExpr() {
8996 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
8997}
8998
8999void Sema::ActOnStmtExprError() {
John McCalled7b2782012-04-06 18:20:53 +00009000 // Note that function is also called by TreeTransform when leaving a
9001 // StmtExpr scope without rebuilding anything.
9002
John McCall3abee492012-04-04 01:27:53 +00009003 DiscardCleanupsInEvaluationContext();
9004 PopExpressionEvaluationContext();
9005}
9006
John McCalldadc5752010-08-24 06:29:42 +00009007ExprResult
John McCallb268a282010-08-23 23:25:46 +00009008Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009009 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00009010 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9011 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9012
John McCall3abee492012-04-04 01:27:53 +00009013 if (hasAnyUnrecoverableErrorsInThisFunction())
9014 DiscardCleanupsInEvaluationContext();
9015 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
9016 PopExpressionEvaluationContext();
9017
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00009018 bool isFileScope
9019 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00009020 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009021 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00009022
Chris Lattner366727f2007-07-24 16:58:17 +00009023 // FIXME: there are a variety of strange constraints to enforce here, for
9024 // example, it is not possible to goto into a stmt expression apparently.
9025 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00009026
Chris Lattner366727f2007-07-24 16:58:17 +00009027 // If there are sub stmts in the compound stmt, take the type of the last one
9028 // as the type of the stmtexpr.
9029 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009030 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00009031 if (!Compound->body_empty()) {
9032 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009033 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00009034 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009035 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9036 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00009037 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009038 }
John McCall31168b02011-06-15 23:02:42 +00009039
John Wiegley01296292011-04-08 18:41:53 +00009040 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00009041 // Do function/array conversion on the last expression, but not
9042 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00009043 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9044 if (LastExpr.isInvalid())
9045 return ExprError();
9046 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00009047
John Wiegley01296292011-04-08 18:41:53 +00009048 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00009049 // In ARC, if the final expression ends in a consume, splice
9050 // the consume out and bind it later. In the alternate case
9051 // (when dealing with a retainable type), the result
9052 // initialization will create a produce. In both cases the
9053 // result will be +1, and we'll need to balance that out with
9054 // a bind.
9055 if (Expr *rebuiltLastStmt
9056 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9057 LastExpr = rebuiltLastStmt;
9058 } else {
9059 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009060 InitializedEntity::InitializeResult(LPLoc,
9061 Ty,
9062 false),
9063 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00009064 LastExpr);
9065 }
9066
John Wiegley01296292011-04-08 18:41:53 +00009067 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009068 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009069 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009070 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00009071 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009072 else
John Wiegley01296292011-04-08 18:41:53 +00009073 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009074 StmtExprMayBindToTemp = true;
9075 }
9076 }
9077 }
Chris Lattner944d3062008-07-26 19:51:01 +00009078 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009079
Eli Friedmanba961a92009-03-23 00:24:07 +00009080 // FIXME: Check that expression type is complete/non-abstract; statement
9081 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009082 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9083 if (StmtExprMayBindToTemp)
9084 return MaybeBindToTemporary(ResStmtExpr);
9085 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00009086}
Steve Naroff78864672007-08-01 22:05:33 +00009087
John McCalldadc5752010-08-24 06:29:42 +00009088ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009089 TypeSourceInfo *TInfo,
9090 OffsetOfComponent *CompPtr,
9091 unsigned NumComponents,
9092 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00009093 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009094 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00009095 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00009096
Chris Lattnerf17bd422007-08-30 17:45:32 +00009097 // We must have at least one component that refers to the type, and the first
9098 // one is known to be a field designator. Verify that the ArgTy represents
9099 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009100 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00009101 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9102 << ArgTy << TypeRange);
9103
9104 // Type must be complete per C99 7.17p3 because a declaring a variable
9105 // with an incomplete type would be ill-formed.
9106 if (!Dependent
9107 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009108 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor882211c2010-04-28 22:16:22 +00009109 return ExprError();
9110
Chris Lattner78502cf2007-08-31 21:49:13 +00009111 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9112 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00009113 // FIXME: This diagnostic isn't actually visible because the location is in
9114 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00009115 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00009116 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9117 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00009118
9119 bool DidWarnAboutNonPOD = false;
9120 QualType CurrentType = ArgTy;
9121 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009122 SmallVector<OffsetOfNode, 4> Comps;
9123 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00009124 for (unsigned i = 0; i != NumComponents; ++i) {
9125 const OffsetOfComponent &OC = CompPtr[i];
9126 if (OC.isBrackets) {
9127 // Offset of an array sub-field. TODO: Should we allow vector elements?
9128 if (!CurrentType->isDependentType()) {
9129 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9130 if(!AT)
9131 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9132 << CurrentType);
9133 CurrentType = AT->getElementType();
9134 } else
9135 CurrentType = Context.DependentTy;
9136
Richard Smith9fcc5c32011-10-17 23:29:39 +00009137 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9138 if (IdxRval.isInvalid())
9139 return ExprError();
9140 Expr *Idx = IdxRval.take();
9141
Douglas Gregor882211c2010-04-28 22:16:22 +00009142 // The expression must be an integral expression.
9143 // FIXME: An integral constant expression?
Douglas Gregor882211c2010-04-28 22:16:22 +00009144 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9145 !Idx->getType()->isIntegerType())
9146 return ExprError(Diag(Idx->getLocStart(),
9147 diag::err_typecheck_subscript_not_integer)
9148 << Idx->getSourceRange());
Richard Smitheda612882011-10-17 05:48:07 +00009149
Douglas Gregor882211c2010-04-28 22:16:22 +00009150 // Record this array index.
9151 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smith9fcc5c32011-10-17 23:29:39 +00009152 Exprs.push_back(Idx);
Douglas Gregor882211c2010-04-28 22:16:22 +00009153 continue;
9154 }
9155
9156 // Offset of a field.
9157 if (CurrentType->isDependentType()) {
9158 // We have the offset of a field, but we can't look into the dependent
9159 // type. Just record the identifier of the field.
9160 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9161 CurrentType = Context.DependentTy;
9162 continue;
9163 }
9164
9165 // We need to have a complete type to look into.
9166 if (RequireCompleteType(OC.LocStart, CurrentType,
9167 diag::err_offsetof_incomplete_type))
9168 return ExprError();
9169
9170 // Look for the designated field.
9171 const RecordType *RC = CurrentType->getAs<RecordType>();
9172 if (!RC)
9173 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9174 << CurrentType);
9175 RecordDecl *RD = RC->getDecl();
9176
9177 // C++ [lib.support.types]p5:
9178 // The macro offsetof accepts a restricted set of type arguments in this
9179 // International Standard. type shall be a POD structure or a POD union
9180 // (clause 9).
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009181 // C++11 [support.types]p4:
9182 // If type is not a standard-layout class (Clause 9), the results are
9183 // undefined.
Douglas Gregor882211c2010-04-28 22:16:22 +00009184 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009185 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9186 unsigned DiagID =
9187 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9188 : diag::warn_offsetof_non_pod_type;
9189
9190 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00009191 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009192 PDiag(DiagID)
Douglas Gregor882211c2010-04-28 22:16:22 +00009193 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9194 << CurrentType))
9195 DidWarnAboutNonPOD = true;
9196 }
9197
9198 // Look for the field.
9199 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9200 LookupQualifiedName(R, RD);
9201 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009202 IndirectFieldDecl *IndirectMemberDecl = 0;
9203 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00009204 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00009205 MemberDecl = IndirectMemberDecl->getAnonField();
9206 }
9207
Douglas Gregor882211c2010-04-28 22:16:22 +00009208 if (!MemberDecl)
9209 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9210 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9211 OC.LocEnd));
9212
Douglas Gregor10982ea2010-04-28 22:36:06 +00009213 // C99 7.17p3:
9214 // (If the specified member is a bit-field, the behavior is undefined.)
9215 //
9216 // We diagnose this as an error.
Richard Smithcaf33902011-10-10 18:28:20 +00009217 if (MemberDecl->isBitField()) {
Douglas Gregor10982ea2010-04-28 22:36:06 +00009218 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9219 << MemberDecl->getDeclName()
9220 << SourceRange(BuiltinLoc, RParenLoc);
9221 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9222 return ExprError();
9223 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009224
9225 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009226 if (IndirectMemberDecl)
9227 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009228
Douglas Gregord1702062010-04-29 00:18:15 +00009229 // If the member was found in a base class, introduce OffsetOfNodes for
9230 // the base class indirections.
9231 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9232 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009233 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00009234 CXXBasePath &Path = Paths.front();
9235 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9236 B != BEnd; ++B)
9237 Comps.push_back(OffsetOfNode(B->Base));
9238 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009239
Francois Pichet783dd6e2010-11-21 06:08:52 +00009240 if (IndirectMemberDecl) {
9241 for (IndirectFieldDecl::chain_iterator FI =
9242 IndirectMemberDecl->chain_begin(),
9243 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9244 assert(isa<FieldDecl>(*FI));
9245 Comps.push_back(OffsetOfNode(OC.LocStart,
9246 cast<FieldDecl>(*FI), OC.LocEnd));
9247 }
9248 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00009249 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00009250
Douglas Gregor882211c2010-04-28 22:16:22 +00009251 CurrentType = MemberDecl->getType().getNonReferenceType();
9252 }
9253
9254 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00009255 TInfo, Comps, Exprs, RParenLoc));
Douglas Gregor882211c2010-04-28 22:16:22 +00009256}
Mike Stump4e1f26a2009-02-19 03:04:26 +00009257
John McCalldadc5752010-08-24 06:29:42 +00009258ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00009259 SourceLocation BuiltinLoc,
9260 SourceLocation TypeLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009261 ParsedType ParsedArgTy,
John McCall36226622010-10-12 02:09:17 +00009262 OffsetOfComponent *CompPtr,
9263 unsigned NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00009264 SourceLocation RParenLoc) {
John McCall36226622010-10-12 02:09:17 +00009265
Douglas Gregor882211c2010-04-28 22:16:22 +00009266 TypeSourceInfo *ArgTInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00009267 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor882211c2010-04-28 22:16:22 +00009268 if (ArgTy.isNull())
9269 return ExprError();
9270
Eli Friedman06dcfd92010-08-05 10:15:45 +00009271 if (!ArgTInfo)
9272 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9273
9274 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00009275 RParenLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00009276}
9277
9278
John McCalldadc5752010-08-24 06:29:42 +00009279ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009280 Expr *CondExpr,
9281 Expr *LHSExpr, Expr *RHSExpr,
9282 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00009283 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9284
John McCall7decc9e2010-11-18 06:31:45 +00009285 ExprValueKind VK = VK_RValue;
9286 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009287 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00009288 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00009289 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009290 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00009291 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009292 } else {
9293 // The conditional expression is required to be a constant expression.
9294 llvm::APSInt condEval(32);
Douglas Gregore2b37442012-05-04 22:38:52 +00009295 ExprResult CondICE
9296 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9297 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009298 if (CondICE.isInvalid())
9299 return ExprError();
9300 CondExpr = CondICE.take();
Steve Naroff9efdabc2007-08-03 21:21:27 +00009301
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009302 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00009303 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9304
9305 resType = ActiveExpr->getType();
9306 ValueDependent = ActiveExpr->isValueDependent();
9307 VK = ActiveExpr->getValueKind();
9308 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009309 }
9310
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009311 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00009312 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00009313 resType->isDependentType(),
9314 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00009315}
9316
Steve Naroffc540d662008-09-03 18:15:37 +00009317//===----------------------------------------------------------------------===//
9318// Clang Extensions.
9319//===----------------------------------------------------------------------===//
9320
9321/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuba63ce62011-09-09 01:45:06 +00009322void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009323 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuba63ce62011-09-09 01:45:06 +00009324 PushBlockScope(CurScope, Block);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009325 CurContext->addDecl(Block);
Richard Trieuba63ce62011-09-09 01:45:06 +00009326 if (CurScope)
9327 PushDeclContext(CurScope, Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009328 else
9329 CurContext = Block;
John McCallf1a3c2a2011-11-11 03:19:12 +00009330
Eli Friedman34b49062012-01-26 03:00:14 +00009331 getCurBlock()->HasImplicitReturnType = true;
9332
John McCallf1a3c2a2011-11-11 03:19:12 +00009333 // Enter a new evaluation context to insulate the block from any
9334 // cleanups from the enclosing full-expression.
9335 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009336}
9337
Douglas Gregor7efd007c2012-06-15 16:59:29 +00009338void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9339 Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00009340 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00009341 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009342 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009343
John McCall8cb7bdf2010-06-04 23:28:52 +00009344 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00009345 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00009346
Douglas Gregor7efd007c2012-06-15 16:59:29 +00009347 // FIXME: We should allow unexpanded parameter packs here, but that would,
9348 // in turn, make the block expression contain unexpanded parameter packs.
9349 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9350 // Drop the parameters.
9351 FunctionProtoType::ExtProtoInfo EPI;
9352 EPI.HasTrailingReturn = false;
9353 EPI.TypeQuals |= DeclSpec::TQ_const;
9354 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9355 EPI);
9356 Sig = Context.getTrivialTypeSourceInfo(T);
9357 }
9358
John McCall3882ace2011-01-05 12:14:39 +00009359 // GetTypeForDeclarator always produces a function type for a block
9360 // literal signature. Furthermore, it is always a FunctionProtoType
9361 // unless the function was written with a typedef.
9362 assert(T->isFunctionType() &&
9363 "GetTypeForDeclarator made a non-function block signature");
9364
9365 // Look for an explicit signature in that function type.
9366 FunctionProtoTypeLoc ExplicitSignature;
9367
9368 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9369 if (isa<FunctionProtoTypeLoc>(tmp)) {
9370 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9371
9372 // Check whether that explicit signature was synthesized by
9373 // GetTypeForDeclarator. If so, don't save that as part of the
9374 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00009375 if (ExplicitSignature.getLocalRangeBegin() ==
9376 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00009377 // This would be much cheaper if we stored TypeLocs instead of
9378 // TypeSourceInfos.
9379 TypeLoc Result = ExplicitSignature.getResultLoc();
9380 unsigned Size = Result.getFullDataSize();
9381 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9382 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9383
9384 ExplicitSignature = FunctionProtoTypeLoc();
9385 }
John McCalla3ccba02010-06-04 11:21:44 +00009386 }
Mike Stump11289f42009-09-09 15:08:12 +00009387
John McCall3882ace2011-01-05 12:14:39 +00009388 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9389 CurBlock->FunctionType = T;
9390
9391 const FunctionType *Fn = T->getAs<FunctionType>();
9392 QualType RetTy = Fn->getResultType();
9393 bool isVariadic =
9394 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9395
John McCall8e346702010-06-04 19:02:56 +00009396 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00009397
John McCalla3ccba02010-06-04 11:21:44 +00009398 // Don't allow returning a objc interface by value.
9399 if (RetTy->isObjCObjectType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009400 Diag(ParamInfo.getLocStart(),
John McCalla3ccba02010-06-04 11:21:44 +00009401 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9402 return;
9403 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009404
John McCalla3ccba02010-06-04 11:21:44 +00009405 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00009406 // return type. TODO: what should we do with declarators like:
9407 // ^ * { ... }
9408 // If the answer is "apply template argument deduction"....
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009409 if (RetTy != Context.DependentTy) {
John McCalla3ccba02010-06-04 11:21:44 +00009410 CurBlock->ReturnType = RetTy;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009411 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman34b49062012-01-26 03:00:14 +00009412 CurBlock->HasImplicitReturnType = false;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009413 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009414
John McCalla3ccba02010-06-04 11:21:44 +00009415 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009416 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00009417 if (ExplicitSignature) {
9418 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9419 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009420 if (Param->getIdentifier() == 0 &&
9421 !Param->isImplicit() &&
9422 !Param->isInvalidDecl() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00009423 !getLangOpts().CPlusPlus)
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009424 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00009425 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009426 }
John McCalla3ccba02010-06-04 11:21:44 +00009427
9428 // Fake up parameter variables if we have a typedef, like
9429 // ^ fntype { ... }
9430 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9431 for (FunctionProtoType::arg_type_iterator
9432 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9433 ParmVarDecl *Param =
9434 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009435 ParamInfo.getLocStart(),
John McCalla3ccba02010-06-04 11:21:44 +00009436 *I);
John McCall8e346702010-06-04 19:02:56 +00009437 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00009438 }
Steve Naroffc540d662008-09-03 18:15:37 +00009439 }
John McCalla3ccba02010-06-04 11:21:44 +00009440
John McCall8e346702010-06-04 19:02:56 +00009441 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00009442 if (!Params.empty()) {
David Blaikie9c70e042011-09-21 18:16:56 +00009443 CurBlock->TheDecl->setParams(Params);
Douglas Gregorb524d902010-11-01 18:37:59 +00009444 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9445 CurBlock->TheDecl->param_end(),
9446 /*CheckParameterNames=*/false);
9447 }
9448
John McCalla3ccba02010-06-04 11:21:44 +00009449 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00009450 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00009451
John McCalla3ccba02010-06-04 11:21:44 +00009452 // Put the parameter variables in scope. We can bail out immediately
9453 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00009454 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00009455 return;
9456
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009457 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00009458 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9459 (*AI)->setOwningFunction(CurBlock->TheDecl);
9460
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009461 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009462 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009463 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00009464
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009465 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009466 }
John McCallf7b2fb52010-01-22 00:28:27 +00009467 }
Steve Naroffc540d662008-09-03 18:15:37 +00009468}
9469
9470/// ActOnBlockError - If there is an error parsing a block, this callback
9471/// is invoked to pop the information about the block from the action impl.
9472void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCallf1a3c2a2011-11-11 03:19:12 +00009473 // Leave the expression-evaluation context.
9474 DiscardCleanupsInEvaluationContext();
9475 PopExpressionEvaluationContext();
9476
Steve Naroffc540d662008-09-03 18:15:37 +00009477 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00009478 PopDeclContext();
Eli Friedman71c80552012-01-05 03:35:19 +00009479 PopFunctionScopeInfo();
Steve Naroffc540d662008-09-03 18:15:37 +00009480}
9481
9482/// ActOnBlockStmtExpr - This is called when the body of a block statement
9483/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00009484ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00009485 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00009486 // If blocks are disabled, emit an error.
9487 if (!LangOpts.Blocks)
9488 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00009489
John McCallf1a3c2a2011-11-11 03:19:12 +00009490 // Leave the expression-evaluation context.
John McCall85110b42012-03-08 22:00:17 +00009491 if (hasAnyUnrecoverableErrorsInThisFunction())
9492 DiscardCleanupsInEvaluationContext();
John McCallf1a3c2a2011-11-11 03:19:12 +00009493 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9494 PopExpressionEvaluationContext();
9495
Douglas Gregor9a28e842010-03-01 23:15:13 +00009496 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Jordan Rosed39e5f12012-07-02 21:19:23 +00009497
9498 if (BSI->HasImplicitReturnType)
9499 deduceClosureReturnType(*BSI);
9500
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009501 PopDeclContext();
9502
Steve Naroffc540d662008-09-03 18:15:37 +00009503 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00009504 if (!BSI->ReturnType.isNull())
9505 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009506
Mike Stump3bf1ab42009-07-28 22:04:01 +00009507 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00009508 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00009509
John McCallc63de662011-02-02 13:00:07 +00009510 // Set the captured variables on the block.
Eli Friedman20139d32012-01-11 02:36:31 +00009511 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9512 SmallVector<BlockDecl::Capture, 4> Captures;
9513 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9514 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9515 if (Cap.isThisCapture())
9516 continue;
Eli Friedman24af8502012-02-03 22:47:37 +00009517 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedman20139d32012-01-11 02:36:31 +00009518 Cap.isNested(), Cap.getCopyExpr());
9519 Captures.push_back(NewCap);
9520 }
9521 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9522 BSI->CXXThisCaptureIndex != 0);
John McCallc63de662011-02-02 13:00:07 +00009523
John McCall8e346702010-06-04 19:02:56 +00009524 // If the user wrote a function type in some form, try to use that.
9525 if (!BSI->FunctionType.isNull()) {
9526 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9527
9528 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9529 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9530
9531 // Turn protoless block types into nullary block types.
9532 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009533 FunctionProtoType::ExtProtoInfo EPI;
9534 EPI.ExtInfo = Ext;
9535 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009536
9537 // Otherwise, if we don't need to change anything about the function type,
9538 // preserve its sugar structure.
9539 } else if (FTy->getResultType() == RetTy &&
9540 (!NoReturn || FTy->getNoReturnAttr())) {
9541 BlockTy = BSI->FunctionType;
9542
9543 // Otherwise, make the minimal modifications to the function type.
9544 } else {
9545 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00009546 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9547 EPI.TypeQuals = 0; // FIXME: silently?
9548 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00009549 BlockTy = Context.getFunctionType(RetTy,
9550 FPT->arg_type_begin(),
9551 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00009552 EPI);
John McCall8e346702010-06-04 19:02:56 +00009553 }
9554
9555 // If we don't have a function type, just build one from nothing.
9556 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00009557 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00009558 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00009559 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009560 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009561
John McCall8e346702010-06-04 19:02:56 +00009562 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9563 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00009564 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009565
Chris Lattner45542ea2009-04-19 05:28:12 +00009566 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00009567 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor5d944db2012-08-17 05:12:08 +00009568 !hasAnyUnrecoverableErrorsInThisFunction() &&
9569 !PP.isCodeCompletionEnabled())
John McCallb268a282010-08-23 23:25:46 +00009570 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00009571
Chris Lattner60f84492011-02-17 23:58:47 +00009572 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009573
Jordan Rosed39e5f12012-07-02 21:19:23 +00009574 // Try to apply the named return value optimization. We have to check again
9575 // if we can do this, though, because blocks keep return statements around
9576 // to deduce an implicit return type.
9577 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9578 !BSI->TheDecl->isDependentContext())
9579 computeNRVO(Body, getCurBlock());
Douglas Gregor49695f02011-09-06 20:46:03 +00009580
Benjamin Kramera4fb8362011-07-12 14:11:05 +00009581 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9582 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedman71c80552012-01-05 03:35:19 +00009583 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramera4fb8362011-07-12 14:11:05 +00009584
John McCall28fc7092011-11-10 05:35:25 +00009585 // If the block isn't obviously global, i.e. it captures anything at
John McCalld2393872012-04-13 01:08:17 +00009586 // all, then we need to do a few things in the surrounding context:
John McCall28fc7092011-11-10 05:35:25 +00009587 if (Result->getBlockDecl()->hasCaptures()) {
John McCalld2393872012-04-13 01:08:17 +00009588 // First, this expression has a new cleanup object.
John McCall28fc7092011-11-10 05:35:25 +00009589 ExprCleanupObjects.push_back(Result->getBlockDecl());
9590 ExprNeedsCleanups = true;
John McCalld2393872012-04-13 01:08:17 +00009591
9592 // It also gets a branch-protected scope if any of the captured
9593 // variables needs destruction.
9594 for (BlockDecl::capture_const_iterator
9595 ci = Result->getBlockDecl()->capture_begin(),
9596 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9597 const VarDecl *var = ci->getVariable();
9598 if (var->getType().isDestructedType() != QualType::DK_none) {
9599 getCurFunction()->setHasBranchProtectedScope();
9600 break;
9601 }
9602 }
John McCall28fc7092011-11-10 05:35:25 +00009603 }
Fariborz Jahanian197c68c2012-03-06 18:41:35 +00009604
Douglas Gregor9a28e842010-03-01 23:15:13 +00009605 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00009606}
9607
John McCalldadc5752010-08-24 06:29:42 +00009608ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009609 Expr *E, ParsedType Ty,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009610 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00009611 TypeSourceInfo *TInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00009612 GetTypeFromParser(Ty, &TInfo);
9613 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00009614}
9615
John McCalldadc5752010-08-24 06:29:42 +00009616ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00009617 Expr *E, TypeSourceInfo *TInfo,
9618 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00009619 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00009620
Eli Friedman121ba0c2008-08-09 23:32:40 +00009621 // Get the va_list type
9622 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00009623 if (VaListType->isArrayType()) {
9624 // Deal with implicit array decay; for example, on x86-64,
9625 // va_list is an array, but it's supposed to decay to
9626 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00009627 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00009628 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00009629 ExprResult Result = UsualUnaryConversions(E);
9630 if (Result.isInvalid())
9631 return ExprError();
9632 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00009633 } else {
9634 // Otherwise, the va_list argument must be an l-value because
9635 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00009636 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00009637 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00009638 return ExprError();
9639 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00009640
Douglas Gregorad3150c2009-05-19 23:10:31 +00009641 if (!E->isTypeDependent() &&
9642 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009643 return ExprError(Diag(E->getLocStart(),
9644 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00009645 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00009646 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009647
David Majnemerc75d1a12011-06-14 05:17:32 +00009648 if (!TInfo->getType()->isDependentType()) {
9649 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009650 diag::err_second_parameter_to_va_arg_incomplete,
9651 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +00009652 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00009653
David Majnemerc75d1a12011-06-14 05:17:32 +00009654 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregorae298422012-05-04 17:09:59 +00009655 TInfo->getType(),
9656 diag::err_second_parameter_to_va_arg_abstract,
9657 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +00009658 return ExprError();
9659
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009660 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00009661 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009662 TInfo->getType()->isObjCLifetimeType()
9663 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9664 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00009665 << TInfo->getType()
9666 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009667 }
Eli Friedman6290ae42011-07-11 21:45:59 +00009668
9669 // Check for va_arg where arguments of the given type will be promoted
9670 // (i.e. this va_arg is guaranteed to have undefined behavior).
9671 QualType PromoteType;
9672 if (TInfo->getType()->isPromotableIntegerType()) {
9673 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9674 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9675 PromoteType = QualType();
9676 }
9677 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9678 PromoteType = Context.DoubleTy;
9679 if (!PromoteType.isNull())
9680 Diag(TInfo->getTypeLoc().getBeginLoc(),
9681 diag::warn_second_parameter_to_va_arg_never_compatible)
9682 << TInfo->getType()
9683 << PromoteType
9684 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00009685 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009686
Abramo Bagnara27db2392010-08-10 10:06:15 +00009687 QualType T = TInfo->getType().getNonLValueExprType(Context);
9688 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009689}
9690
John McCalldadc5752010-08-24 06:29:42 +00009691ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009692 // The type of __null will be int or long, depending on the size of
9693 // pointers on the target.
9694 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009695 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9696 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009697 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009698 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009699 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009700 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009701 Ty = Context.LongLongTy;
9702 else {
David Blaikie83d382b2011-09-23 05:06:16 +00009703 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009704 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009705
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009706 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009707}
9708
Alexis Huntc46382e2010-04-28 23:02:27 +00009709static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009710 Expr *SrcExpr, FixItHint &Hint) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009711 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonace5d072009-11-10 04:46:30 +00009712 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009713
Anders Carlssonace5d072009-11-10 04:46:30 +00009714 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9715 if (!PT)
9716 return;
9717
9718 // Check if the destination is of type 'id'.
9719 if (!PT->isObjCIdType()) {
9720 // Check if the destination is the 'NSString' interface.
9721 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9722 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9723 return;
9724 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009725
John McCallfe96e0b2011-11-06 09:01:30 +00009726 // Ignore any parens, implicit casts (should only be
9727 // array-to-pointer decays), and not-so-opaque values. The last is
9728 // important for making this trigger for property assignments.
9729 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9730 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9731 if (OV->getSourceExpr())
9732 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9733
9734 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregorfb65e592011-07-27 05:40:30 +00009735 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00009736 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009737
Douglas Gregora771f462010-03-31 17:46:05 +00009738 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009739}
9740
Chris Lattner9bad62c2008-01-04 18:04:52 +00009741bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9742 SourceLocation Loc,
9743 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009744 Expr *SrcExpr, AssignmentAction Action,
9745 bool *Complained) {
9746 if (Complained)
9747 *Complained = false;
9748
Chris Lattner9bad62c2008-01-04 18:04:52 +00009749 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00009750 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009751 bool isInvalid = false;
Eli Friedman381f4312012-02-29 20:59:56 +00009752 unsigned DiagKind = 0;
Douglas Gregora771f462010-03-31 17:46:05 +00009753 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00009754 ConversionFixItGenerator ConvHints;
9755 bool MayHaveConvFixit = false;
Richard Trieucaff2472011-11-23 22:32:32 +00009756 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009757
Chris Lattner9bad62c2008-01-04 18:04:52 +00009758 switch (ConvTy) {
Fariborz Jahanian268fec12012-07-17 18:00:08 +00009759 case Compatible:
9760 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
9761 return false;
9762
Chris Lattner940cfeb2008-01-04 18:22:42 +00009763 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009764 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00009765 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9766 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009767 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009768 case IntToPointer:
9769 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00009770 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9771 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009772 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009773 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009774 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009775 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00009776 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9777 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00009778 if (Hint.isNull() && !CheckInferredResultType) {
9779 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9780 }
9781 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009782 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009783 case IncompatiblePointerSign:
9784 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9785 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009786 case FunctionVoidPointer:
9787 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9788 break;
John McCall4fff8f62011-02-01 00:10:29 +00009789 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009790 // Perform array-to-pointer decay if necessary.
9791 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9792
John McCall4fff8f62011-02-01 00:10:29 +00009793 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9794 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9795 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9796 DiagKind = diag::err_typecheck_incompatible_address_space;
9797 break;
John McCall31168b02011-06-15 23:02:42 +00009798
9799
9800 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009801 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00009802 break;
John McCall4fff8f62011-02-01 00:10:29 +00009803 }
9804
9805 llvm_unreachable("unknown error case for discarding qualifiers!");
9806 // fallthrough
9807 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009808 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009809 // If the qualifiers lost were because we were applying the
9810 // (deprecated) C++ conversion from a string literal to a char*
9811 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9812 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009813 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009814 // bit of refactoring (so that the second argument is an
9815 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009816 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009817 // C++ semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009818 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009819 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9820 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009821 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9822 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009823 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009824 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009825 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009826 case IntToBlockPointer:
9827 DiagKind = diag::err_int_to_block_pointer;
9828 break;
9829 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009830 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009831 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009832 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009833 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009834 // it can give a more specific diagnostic.
9835 DiagKind = diag::warn_incompatible_qualified_id;
9836 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009837 case IncompatibleVectors:
9838 DiagKind = diag::warn_incompatible_vectors;
9839 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00009840 case IncompatibleObjCWeakRef:
9841 DiagKind = diag::err_arc_weak_unavailable_assign;
9842 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009843 case Incompatible:
9844 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00009845 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9846 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009847 isInvalid = true;
Richard Trieucaff2472011-11-23 22:32:32 +00009848 MayHaveFunctionDiff = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009849 break;
9850 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009851
Douglas Gregorc68e1402010-04-09 00:35:39 +00009852 QualType FirstType, SecondType;
9853 switch (Action) {
9854 case AA_Assigning:
9855 case AA_Initializing:
9856 // The destination type comes first.
9857 FirstType = DstType;
9858 SecondType = SrcType;
9859 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009860
Douglas Gregorc68e1402010-04-09 00:35:39 +00009861 case AA_Returning:
9862 case AA_Passing:
9863 case AA_Converting:
9864 case AA_Sending:
9865 case AA_Casting:
9866 // The source type comes first.
9867 FirstType = SrcType;
9868 SecondType = DstType;
9869 break;
9870 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009871
Anna Zaks3b402712011-07-28 19:51:27 +00009872 PartialDiagnostic FDiag = PDiag(DiagKind);
9873 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9874
9875 // If we can fix the conversion, suggest the FixIts.
9876 assert(ConvHints.isNull() || Hint.isNull());
9877 if (!ConvHints.isNull()) {
Benjamin Kramer490afa62012-01-14 21:05:10 +00009878 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9879 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks3b402712011-07-28 19:51:27 +00009880 FDiag << *HI;
9881 } else {
9882 FDiag << Hint;
9883 }
9884 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9885
Richard Trieucaff2472011-11-23 22:32:32 +00009886 if (MayHaveFunctionDiff)
9887 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9888
Anna Zaks3b402712011-07-28 19:51:27 +00009889 Diag(Loc, FDiag);
9890
Richard Trieucaff2472011-11-23 22:32:32 +00009891 if (SecondType == Context.OverloadTy)
9892 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9893 FirstType);
9894
Douglas Gregor33823722011-06-11 01:09:30 +00009895 if (CheckInferredResultType)
9896 EmitRelatedResultTypeNote(SrcExpr);
9897
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009898 if (Complained)
9899 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009900 return isInvalid;
9901}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009902
Richard Smithf4c51d92012-02-04 09:53:13 +00009903ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9904 llvm::APSInt *Result) {
Douglas Gregore2b37442012-05-04 22:38:52 +00009905 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9906 public:
9907 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9908 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9909 }
9910 } Diagnoser;
9911
9912 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9913}
9914
9915ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9916 llvm::APSInt *Result,
9917 unsigned DiagID,
9918 bool AllowFold) {
9919 class IDDiagnoser : public VerifyICEDiagnoser {
9920 unsigned DiagID;
9921
9922 public:
9923 IDDiagnoser(unsigned DiagID)
9924 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9925
9926 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9927 S.Diag(Loc, DiagID) << SR;
9928 }
9929 } Diagnoser(DiagID);
9930
9931 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9932}
9933
9934void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9935 SourceRange SR) {
9936 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smithf4c51d92012-02-04 09:53:13 +00009937}
9938
Benjamin Kramer33adaae2012-04-18 14:22:41 +00009939ExprResult
9940Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregore2b37442012-05-04 22:38:52 +00009941 VerifyICEDiagnoser &Diagnoser,
9942 bool AllowFold) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009943 SourceLocation DiagLoc = E->getLocStart();
Richard Smithf4c51d92012-02-04 09:53:13 +00009944
David Blaikiebbafb8a2012-03-11 07:00:24 +00009945 if (getLangOpts().CPlusPlus0x) {
Richard Smithf4c51d92012-02-04 09:53:13 +00009946 // C++11 [expr.const]p5:
9947 // If an expression of literal class type is used in a context where an
9948 // integral constant expression is required, then that class type shall
9949 // have a single non-explicit conversion function to an integral or
9950 // unscoped enumeration type
9951 ExprResult Converted;
Douglas Gregore2b37442012-05-04 22:38:52 +00009952 if (!Diagnoser.Suppress) {
9953 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9954 public:
9955 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9956
9957 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9958 QualType T) {
9959 return S.Diag(Loc, diag::err_ice_not_integral) << T;
9960 }
9961
9962 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9963 SourceLocation Loc,
9964 QualType T) {
9965 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
9966 }
9967
9968 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9969 SourceLocation Loc,
9970 QualType T,
9971 QualType ConvTy) {
9972 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
9973 }
9974
9975 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9976 CXXConversionDecl *Conv,
9977 QualType ConvTy) {
9978 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9979 << ConvTy->isEnumeralType() << ConvTy;
9980 }
9981
9982 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9983 QualType T) {
9984 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
9985 }
9986
9987 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9988 CXXConversionDecl *Conv,
9989 QualType ConvTy) {
9990 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9991 << ConvTy->isEnumeralType() << ConvTy;
9992 }
9993
9994 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9995 SourceLocation Loc,
9996 QualType T,
9997 QualType ConvTy) {
9998 return DiagnosticBuilder::getEmpty();
9999 }
10000 } ConvertDiagnoser;
10001
10002 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10003 ConvertDiagnoser,
10004 /*AllowScopedEnumerations*/ false);
Richard Smithf4c51d92012-02-04 09:53:13 +000010005 } else {
10006 // The caller wants to silently enquire whether this is an ICE. Don't
10007 // produce any diagnostics if it isn't.
Douglas Gregore2b37442012-05-04 22:38:52 +000010008 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
10009 public:
10010 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
10011
10012 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10013 QualType T) {
10014 return DiagnosticBuilder::getEmpty();
10015 }
10016
10017 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
10018 SourceLocation Loc,
10019 QualType T) {
10020 return DiagnosticBuilder::getEmpty();
10021 }
10022
10023 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
10024 SourceLocation Loc,
10025 QualType T,
10026 QualType ConvTy) {
10027 return DiagnosticBuilder::getEmpty();
10028 }
10029
10030 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10031 CXXConversionDecl *Conv,
10032 QualType ConvTy) {
10033 return DiagnosticBuilder::getEmpty();
10034 }
10035
10036 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10037 QualType T) {
10038 return DiagnosticBuilder::getEmpty();
10039 }
10040
10041 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10042 CXXConversionDecl *Conv,
10043 QualType ConvTy) {
10044 return DiagnosticBuilder::getEmpty();
10045 }
10046
10047 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10048 SourceLocation Loc,
10049 QualType T,
10050 QualType ConvTy) {
10051 return DiagnosticBuilder::getEmpty();
10052 }
10053 } ConvertDiagnoser;
10054
10055 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10056 ConvertDiagnoser, false);
Richard Smithf4c51d92012-02-04 09:53:13 +000010057 }
10058 if (Converted.isInvalid())
10059 return Converted;
10060 E = Converted.take();
10061 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
10062 return ExprError();
10063 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10064 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregore2b37442012-05-04 22:38:52 +000010065 if (!Diagnoser.Suppress)
10066 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithf4c51d92012-02-04 09:53:13 +000010067 return ExprError();
10068 }
10069
Richard Smith902ca212011-12-14 23:32:26 +000010070 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10071 // in the non-ICE case.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010072 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
Richard Smithf4c51d92012-02-04 09:53:13 +000010073 if (Result)
10074 *Result = E->EvaluateKnownConstInt(Context);
10075 return Owned(E);
Eli Friedmanbb967cc2009-04-25 22:26:58 +000010076 }
10077
Anders Carlssone54e8a12008-11-30 19:50:32 +000010078 Expr::EvalResult EvalResult;
Richard Smith92b1ce02011-12-12 09:28:41 +000010079 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
10080 EvalResult.Diag = &Notes;
Anders Carlssone54e8a12008-11-30 19:50:32 +000010081
Richard Smith902ca212011-12-14 23:32:26 +000010082 // Try to evaluate the expression, and produce diagnostics explaining why it's
10083 // not a constant expression as a side-effect.
10084 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10085 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10086
10087 // In C++11, we can rely on diagnostics being produced for any expression
10088 // which is not a constant expression. If no diagnostics were produced, then
10089 // this is a constant expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010090 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
Richard Smith902ca212011-12-14 23:32:26 +000010091 if (Result)
10092 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +000010093 return Owned(E);
10094 }
10095
10096 // If our only note is the usual "invalid subexpression" note, just point
10097 // the caret at its location rather than producing an essentially
10098 // redundant note.
10099 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10100 diag::note_invalid_subexpr_in_const_expr) {
10101 DiagLoc = Notes[0].first;
10102 Notes.clear();
Richard Smith902ca212011-12-14 23:32:26 +000010103 }
10104
10105 if (!Folded || !AllowFold) {
Douglas Gregore2b37442012-05-04 22:38:52 +000010106 if (!Diagnoser.Suppress) {
10107 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith92b1ce02011-12-12 09:28:41 +000010108 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10109 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone54e8a12008-11-30 19:50:32 +000010110 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000010111
Richard Smithf4c51d92012-02-04 09:53:13 +000010112 return ExprError();
Anders Carlssone54e8a12008-11-30 19:50:32 +000010113 }
10114
Douglas Gregore2b37442012-05-04 22:38:52 +000010115 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith2ec40612012-01-15 03:51:30 +000010116 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10117 Diag(Notes[I].first, Notes[I].second);
Mike Stump4e1f26a2009-02-19 03:04:26 +000010118
Anders Carlssone54e8a12008-11-30 19:50:32 +000010119 if (Result)
10120 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +000010121 return Owned(E);
Anders Carlssone54e8a12008-11-30 19:50:32 +000010122}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010123
Eli Friedman456f0182012-01-20 01:26:23 +000010124namespace {
10125 // Handle the case where we conclude a expression which we speculatively
10126 // considered to be unevaluated is actually evaluated.
10127 class TransformToPE : public TreeTransform<TransformToPE> {
10128 typedef TreeTransform<TransformToPE> BaseTransform;
10129
10130 public:
10131 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10132
10133 // Make sure we redo semantic analysis
10134 bool AlwaysRebuild() { return true; }
10135
Eli Friedman5f0ca242012-02-06 23:29:57 +000010136 // Make sure we handle LabelStmts correctly.
10137 // FIXME: This does the right thing, but maybe we need a more general
10138 // fix to TreeTransform?
10139 StmtResult TransformLabelStmt(LabelStmt *S) {
10140 S->getDecl()->setStmt(0);
10141 return BaseTransform::TransformLabelStmt(S);
10142 }
10143
Eli Friedman456f0182012-01-20 01:26:23 +000010144 // We need to special-case DeclRefExprs referring to FieldDecls which
10145 // are not part of a member pointer formation; normal TreeTransforming
10146 // doesn't catch this case because of the way we represent them in the AST.
10147 // FIXME: This is a bit ugly; is it really the best way to handle this
10148 // case?
10149 //
10150 // Error on DeclRefExprs referring to FieldDecls.
10151 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10152 if (isa<FieldDecl>(E->getDecl()) &&
David Blaikie131fcb42012-08-06 22:47:24 +000010153 !SemaRef.isUnevaluatedContext())
Eli Friedman456f0182012-01-20 01:26:23 +000010154 return SemaRef.Diag(E->getLocation(),
10155 diag::err_invalid_non_static_member_use)
10156 << E->getDecl() << E->getSourceRange();
10157
10158 return BaseTransform::TransformDeclRefExpr(E);
10159 }
10160
10161 // Exception: filter out member pointer formation
10162 ExprResult TransformUnaryOperator(UnaryOperator *E) {
10163 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10164 return E;
10165
10166 return BaseTransform::TransformUnaryOperator(E);
10167 }
10168
Douglas Gregor89625492012-02-09 08:14:43 +000010169 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10170 // Lambdas never need to be transformed.
10171 return E;
10172 }
Eli Friedman456f0182012-01-20 01:26:23 +000010173 };
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000010174}
10175
Eli Friedman456f0182012-01-20 01:26:23 +000010176ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
Eli Friedmane4f22df2012-02-29 04:03:55 +000010177 assert(ExprEvalContexts.back().Context == Unevaluated &&
10178 "Should only transform unevaluated expressions");
Eli Friedman456f0182012-01-20 01:26:23 +000010179 ExprEvalContexts.back().Context =
10180 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10181 if (ExprEvalContexts.back().Context == Unevaluated)
10182 return E;
10183 return TransformToPE(*this).TransformExpr(E);
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000010184}
10185
Douglas Gregorff790f12009-11-26 00:44:06 +000010186void
Douglas Gregor7fcbd902012-02-21 00:37:24 +000010187Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smithfd555f62012-02-22 02:04:18 +000010188 Decl *LambdaContextDecl,
10189 bool IsDecltype) {
Douglas Gregorff790f12009-11-26 00:44:06 +000010190 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +000010191 ExpressionEvaluationContextRecord(NewContext,
John McCall28fc7092011-11-10 05:35:25 +000010192 ExprCleanupObjects.size(),
Douglas Gregor7fcbd902012-02-21 00:37:24 +000010193 ExprNeedsCleanups,
Richard Smithfd555f62012-02-22 02:04:18 +000010194 LambdaContextDecl,
10195 IsDecltype));
John McCall31168b02011-06-15 23:02:42 +000010196 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010197 if (!MaybeODRUseExprs.empty())
10198 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010199}
10200
Eli Friedman15681d62012-09-26 04:34:21 +000010201void
10202Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10203 ReuseLambdaContextDecl_t,
10204 bool IsDecltype) {
10205 Decl *LambdaContextDecl = ExprEvalContexts.back().LambdaContextDecl;
10206 PushExpressionEvaluationContext(NewContext, LambdaContextDecl, IsDecltype);
10207}
10208
Richard Trieucfc491d2011-08-02 04:35:43 +000010209void Sema::PopExpressionEvaluationContext() {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010210 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010211
Douglas Gregor89625492012-02-09 08:14:43 +000010212 if (!Rec.Lambdas.empty()) {
10213 if (Rec.Context == Unevaluated) {
10214 // C++11 [expr.prim.lambda]p2:
10215 // A lambda-expression shall not appear in an unevaluated operand
10216 // (Clause 5).
10217 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10218 Diag(Rec.Lambdas[I]->getLocStart(),
10219 diag::err_lambda_unevaluated_operand);
10220 } else {
10221 // Mark the capture expressions odr-used. This was deferred
10222 // during lambda expression creation.
10223 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10224 LambdaExpr *Lambda = Rec.Lambdas[I];
10225 for (LambdaExpr::capture_init_iterator
10226 C = Lambda->capture_init_begin(),
10227 CEnd = Lambda->capture_init_end();
10228 C != CEnd; ++C) {
10229 MarkDeclarationsReferencedInExpr(*C);
10230 }
10231 }
10232 }
10233 }
10234
Douglas Gregorff790f12009-11-26 00:44:06 +000010235 // When are coming out of an unevaluated context, clear out any
10236 // temporaries that we may have created as part of the evaluation of
10237 // the expression in that context: they aren't relevant because they
10238 // will never be constructed.
Richard Smith764d2fe2011-12-20 02:08:33 +000010239 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall28fc7092011-11-10 05:35:25 +000010240 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10241 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +000010242 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010243 CleanupVarDeclMarking();
10244 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCall31168b02011-06-15 23:02:42 +000010245 // Otherwise, merge the contexts together.
10246 } else {
10247 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010248 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10249 Rec.SavedMaybeODRUseExprs.end());
John McCall31168b02011-06-15 23:02:42 +000010250 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010251
10252 // Pop the current expression evaluation context off the stack.
10253 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010254}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010255
John McCall31168b02011-06-15 23:02:42 +000010256void Sema::DiscardCleanupsInEvaluationContext() {
John McCall28fc7092011-11-10 05:35:25 +000010257 ExprCleanupObjects.erase(
10258 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10259 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +000010260 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010261 MaybeODRUseExprs.clear();
John McCall31168b02011-06-15 23:02:42 +000010262}
10263
Eli Friedmane0afc982012-01-21 01:01:51 +000010264ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10265 if (!E->getType()->isVariablyModifiedType())
10266 return E;
10267 return TranformToPotentiallyEvaluated(E);
10268}
10269
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +000010270static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010271 // Do not mark anything as "used" within a dependent context; wait for
10272 // an instantiation.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010273 if (SemaRef.CurContext->isDependentContext())
10274 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010275
Eli Friedmanfa0df832012-02-02 03:46:19 +000010276 switch (SemaRef.ExprEvalContexts.back().Context) {
10277 case Sema::Unevaluated:
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010278 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman02b58512012-01-21 04:44:06 +000010279 // (Depending on how you read the standard, we actually do need to do
10280 // something here for null pointer constants, but the standard's
10281 // definition of a null pointer constant is completely crazy.)
Eli Friedmanfa0df832012-02-02 03:46:19 +000010282 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010283
Eli Friedmanfa0df832012-02-02 03:46:19 +000010284 case Sema::ConstantEvaluated:
10285 case Sema::PotentiallyEvaluated:
Eli Friedman02b58512012-01-21 04:44:06 +000010286 // We are in a potentially evaluated expression (or a constant-expression
10287 // in C++03); we need to do implicit template instantiation, implicitly
10288 // define class members, and mark most declarations as used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010289 return true;
Mike Stump11289f42009-09-09 15:08:12 +000010290
Eli Friedmanfa0df832012-02-02 03:46:19 +000010291 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010292 // Referenced declarations will only be used if the construct in the
10293 // containing expression is used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010294 return false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010295 }
Matt Beaumont-Gay248bc722012-02-02 18:35:35 +000010296 llvm_unreachable("Invalid context");
Eli Friedmanfa0df832012-02-02 03:46:19 +000010297}
10298
10299/// \brief Mark a function referenced, and check whether it is odr-used
10300/// (C++ [basic.def.odr]p2, C99 6.9p3)
10301void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10302 assert(Func && "No function?");
10303
10304 Func->setReferenced();
10305
Richard Smith4a941e22012-02-14 22:25:15 +000010306 // Don't mark this function as used multiple times, unless it's a constexpr
10307 // function which we need to instantiate.
10308 if (Func->isUsed(false) &&
10309 !(Func->isConstexpr() && !Func->getBody() &&
10310 Func->isImplicitlyInstantiable()))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010311 return;
10312
10313 if (!IsPotentiallyEvaluatedContext(*this))
10314 return;
Mike Stump11289f42009-09-09 15:08:12 +000010315
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010316 // Note that this declaration has been used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010317 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010318 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010319 if (Constructor->isDefaultConstructor()) {
10320 if (Constructor->isTrivial())
10321 return;
10322 if (!Constructor->isUsed(false))
10323 DefineImplicitDefaultConstructor(Loc, Constructor);
10324 } else if (Constructor->isCopyConstructor()) {
10325 if (!Constructor->isUsed(false))
10326 DefineImplicitCopyConstructor(Loc, Constructor);
10327 } else if (Constructor->isMoveConstructor()) {
10328 if (!Constructor->isUsed(false))
10329 DefineImplicitMoveConstructor(Loc, Constructor);
10330 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010331 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010332
Douglas Gregor88d292c2010-05-13 16:44:06 +000010333 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010334 } else if (CXXDestructorDecl *Destructor =
10335 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010336 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10337 !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010338 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010339 if (Destructor->isVirtual())
10340 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010341 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010342 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10343 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010344 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010345 if (!MethodDecl->isUsed(false)) {
10346 if (MethodDecl->isCopyAssignmentOperator())
10347 DefineImplicitCopyAssignment(Loc, MethodDecl);
10348 else
10349 DefineImplicitMoveAssignment(Loc, MethodDecl);
10350 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010351 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10352 MethodDecl->getParent()->isLambda()) {
10353 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10354 if (Conversion->isLambdaToBlockPointerConversion())
10355 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10356 else
10357 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010358 } else if (MethodDecl->isVirtual())
10359 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010360 }
John McCall83779672011-02-19 02:53:41 +000010361
Eli Friedmanfa0df832012-02-02 03:46:19 +000010362 // Recursive functions should be marked when used from another function.
10363 // FIXME: Is this really right?
10364 if (CurContext == Func) return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010365
Richard Smithd3b5c9082012-07-27 04:22:15 +000010366 // Resolve the exception specification for any function which is
Richard Smithf623c962012-04-17 00:58:00 +000010367 // used: CodeGen will need it.
Richard Smithd3729422012-04-19 00:08:28 +000010368 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010369 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10370 ResolveExceptionSpec(Loc, FPT);
Richard Smithf623c962012-04-17 00:58:00 +000010371
Eli Friedmanfa0df832012-02-02 03:46:19 +000010372 // Implicit instantiation of function templates and member functions of
10373 // class templates.
10374 if (Func->isImplicitlyInstantiable()) {
10375 bool AlreadyInstantiated = false;
Richard Smith4a941e22012-02-14 22:25:15 +000010376 SourceLocation PointOfInstantiation = Loc;
Eli Friedmanfa0df832012-02-02 03:46:19 +000010377 if (FunctionTemplateSpecializationInfo *SpecInfo
10378 = Func->getTemplateSpecializationInfo()) {
10379 if (SpecInfo->getPointOfInstantiation().isInvalid())
10380 SpecInfo->setPointOfInstantiation(Loc);
10381 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000010382 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010383 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000010384 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10385 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010386 } else if (MemberSpecializationInfo *MSInfo
10387 = Func->getMemberSpecializationInfo()) {
10388 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregor06db9f52009-10-12 20:18:28 +000010389 MSInfo->setPointOfInstantiation(Loc);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010390 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000010391 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010392 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000010393 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10394 }
Douglas Gregor06db9f52009-10-12 20:18:28 +000010395 }
Mike Stump11289f42009-09-09 15:08:12 +000010396
Richard Smith4a941e22012-02-14 22:25:15 +000010397 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010398 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10399 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith4a941e22012-02-14 22:25:15 +000010400 PendingLocalImplicitInstantiations.push_back(
10401 std::make_pair(Func, PointOfInstantiation));
10402 else if (Func->isConstexpr())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010403 // Do not defer instantiations of constexpr functions, to avoid the
10404 // expression evaluator needing to call back into Sema if it sees a
10405 // call to such a function.
Richard Smith4a941e22012-02-14 22:25:15 +000010406 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000010407 else {
Richard Smith4a941e22012-02-14 22:25:15 +000010408 PendingInstantiations.push_back(std::make_pair(Func,
10409 PointOfInstantiation));
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000010410 // Notify the consumer that a function was implicitly instantiated.
10411 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10412 }
John McCall83779672011-02-19 02:53:41 +000010413 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010414 } else {
10415 // Walk redefinitions, as some of them may be instantiable.
10416 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10417 e(Func->redecls_end()); i != e; ++i) {
10418 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10419 MarkFunctionReferenced(Loc, *i);
10420 }
Sam Weinigbae69142009-09-11 03:29:30 +000010421 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010422
10423 // Keep track of used but undefined functions.
10424 if (!Func->isPure() && !Func->hasBody() &&
10425 Func->getLinkage() != ExternalLinkage) {
10426 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10427 if (old.isInvalid()) old = Loc;
10428 }
10429
10430 Func->setUsed(true);
10431}
10432
Eli Friedman9bb33f52012-02-03 02:04:35 +000010433static void
10434diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10435 VarDecl *var, DeclContext *DC) {
Eli Friedmandd053f62012-02-07 00:15:00 +000010436 DeclContext *VarDC = var->getDeclContext();
10437
Eli Friedman9bb33f52012-02-03 02:04:35 +000010438 // If the parameter still belongs to the translation unit, then
10439 // we're actually just using one parameter in the declaration of
10440 // the next.
10441 if (isa<ParmVarDecl>(var) &&
Eli Friedmandd053f62012-02-07 00:15:00 +000010442 isa<TranslationUnitDecl>(VarDC))
Eli Friedman9bb33f52012-02-03 02:04:35 +000010443 return;
10444
Eli Friedmandd053f62012-02-07 00:15:00 +000010445 // For C code, don't diagnose about capture if we're not actually in code
10446 // right now; it's impossible to write a non-constant expression outside of
10447 // function context, so we'll get other (more useful) diagnostics later.
10448 //
10449 // For C++, things get a bit more nasty... it would be nice to suppress this
10450 // diagnostic for certain cases like using a local variable in an array bound
10451 // for a member of a local class, but the correct predicate is not obvious.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010452 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman9bb33f52012-02-03 02:04:35 +000010453 return;
10454
Eli Friedmandd053f62012-02-07 00:15:00 +000010455 if (isa<CXXMethodDecl>(VarDC) &&
10456 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10457 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10458 << var->getIdentifier();
10459 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10460 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10461 << var->getIdentifier() << fn->getDeclName();
10462 } else if (isa<BlockDecl>(VarDC)) {
10463 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10464 << var->getIdentifier();
10465 } else {
10466 // FIXME: Is there any other context where a local variable can be
10467 // declared?
10468 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10469 << var->getIdentifier();
10470 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010471
Eli Friedman9bb33f52012-02-03 02:04:35 +000010472 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10473 << var->getIdentifier();
Eli Friedmandd053f62012-02-07 00:15:00 +000010474
10475 // FIXME: Add additional diagnostic info about class etc. which prevents
10476 // capture.
Eli Friedman9bb33f52012-02-03 02:04:35 +000010477}
10478
Douglas Gregor81495f32012-02-12 18:42:33 +000010479/// \brief Capture the given variable in the given lambda expression.
10480static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010481 VarDecl *Var, QualType FieldType,
10482 QualType DeclRefType,
Douglas Gregora8182f92012-05-16 17:01:33 +000010483 SourceLocation Loc,
10484 bool RefersToEnclosingLocal) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010485 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregor81495f32012-02-12 18:42:33 +000010486
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010487 // Build the non-static data member.
10488 FieldDecl *Field
10489 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10490 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Richard Smith2b013182012-06-10 03:12:00 +000010491 0, false, ICIS_NoInit);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010492 Field->setImplicit(true);
10493 Field->setAccess(AS_private);
Douglas Gregor3d23f7882012-02-09 02:12:34 +000010494 Lambda->addDecl(Field);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010495
10496 // C++11 [expr.prim.lambda]p21:
10497 // When the lambda-expression is evaluated, the entities that
10498 // are captured by copy are used to direct-initialize each
10499 // corresponding non-static data member of the resulting closure
10500 // object. (For array members, the array elements are
10501 // direct-initialized in increasing subscript order.) These
10502 // initializations are performed in the (unspecified) order in
10503 // which the non-static data members are declared.
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010504
Douglas Gregor89625492012-02-09 08:14:43 +000010505 // Introduce a new evaluation context for the initialization, so
10506 // that temporaries introduced as part of the capture are retained
10507 // to be re-"exported" from the lambda expression itself.
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010508 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10509
Douglas Gregorf02455e2012-02-10 09:26:04 +000010510 // C++ [expr.prim.labda]p12:
10511 // An entity captured by a lambda-expression is odr-used (3.2) in
10512 // the scope containing the lambda-expression.
Douglas Gregora8182f92012-05-16 17:01:33 +000010513 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10514 DeclRefType, VK_LValue, Loc);
Eli Friedman23b1be92012-03-01 21:32:56 +000010515 Var->setReferenced(true);
Douglas Gregorf02455e2012-02-10 09:26:04 +000010516 Var->setUsed(true);
Douglas Gregor199cec72012-02-09 02:45:47 +000010517
10518 // When the field has array type, create index variables for each
10519 // dimension of the array. We use these index variables to subscript
10520 // the source array, and other clients (e.g., CodeGen) will perform
10521 // the necessary iteration with these index variables.
10522 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor199cec72012-02-09 02:45:47 +000010523 QualType BaseType = FieldType;
10524 QualType SizeType = S.Context.getSizeType();
Douglas Gregor54fcea62012-02-13 16:35:30 +000010525 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor199cec72012-02-09 02:45:47 +000010526 while (const ConstantArrayType *Array
10527 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor199cec72012-02-09 02:45:47 +000010528 // Create the iteration variable for this array index.
10529 IdentifierInfo *IterationVarName = 0;
10530 {
10531 SmallString<8> Str;
10532 llvm::raw_svector_ostream OS(Str);
10533 OS << "__i" << IndexVariables.size();
10534 IterationVarName = &S.Context.Idents.get(OS.str());
10535 }
10536 VarDecl *IterationVar
10537 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10538 IterationVarName, SizeType,
10539 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10540 SC_None, SC_None);
10541 IndexVariables.push_back(IterationVar);
Douglas Gregor54fcea62012-02-13 16:35:30 +000010542 LSI->ArrayIndexVars.push_back(IterationVar);
10543
Douglas Gregor199cec72012-02-09 02:45:47 +000010544 // Create a reference to the iteration variable.
10545 ExprResult IterationVarRef
10546 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10547 assert(!IterationVarRef.isInvalid() &&
10548 "Reference to invented variable cannot fail!");
10549 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10550 assert(!IterationVarRef.isInvalid() &&
10551 "Conversion of invented variable cannot fail!");
10552
10553 // Subscript the array with this iteration variable.
10554 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10555 Ref, Loc, IterationVarRef.take(), Loc);
10556 if (Subscript.isInvalid()) {
10557 S.CleanupVarDeclMarking();
10558 S.DiscardCleanupsInEvaluationContext();
10559 S.PopExpressionEvaluationContext();
10560 return ExprError();
10561 }
10562
10563 Ref = Subscript.take();
10564 BaseType = Array->getElementType();
10565 }
10566
10567 // Construct the entity that we will be initializing. For an array, this
10568 // will be first element in the array, which may require several levels
10569 // of array-subscript entities.
10570 SmallVector<InitializedEntity, 4> Entities;
10571 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor19666fb2012-02-15 16:57:26 +000010572 Entities.push_back(
10573 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor199cec72012-02-09 02:45:47 +000010574 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10575 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10576 0,
10577 Entities.back()));
10578
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010579 InitializationKind InitKind
10580 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor199cec72012-02-09 02:45:47 +000010581 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010582 ExprResult Result(true);
Douglas Gregor199cec72012-02-09 02:45:47 +000010583 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010584 Result = Init.Perform(S, Entities.back(), InitKind, Ref);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010585
10586 // If this initialization requires any cleanups (e.g., due to a
10587 // default argument to a copy constructor), note that for the
10588 // lambda.
10589 if (S.ExprNeedsCleanups)
10590 LSI->ExprNeedsCleanups = true;
10591
10592 // Exit the expression evaluation context used for the capture.
10593 S.CleanupVarDeclMarking();
10594 S.DiscardCleanupsInEvaluationContext();
10595 S.PopExpressionEvaluationContext();
10596 return Result;
Douglas Gregor199cec72012-02-09 02:45:47 +000010597}
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010598
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010599bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10600 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10601 bool BuildAndDiagnose,
10602 QualType &CaptureType,
10603 QualType &DeclRefType) {
10604 bool Nested = false;
Douglas Gregor81495f32012-02-12 18:42:33 +000010605
Eli Friedman24af8502012-02-03 22:47:37 +000010606 DeclContext *DC = CurContext;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010607 if (Var->getDeclContext() == DC) return true;
10608 if (!Var->hasLocalStorage()) return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010609
Douglas Gregor81495f32012-02-12 18:42:33 +000010610 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010611
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010612 // Walk up the stack to determine whether we can capture the variable,
10613 // performing the "simple" checks that don't depend on type. We stop when
10614 // we've either hit the declared scope of the variable or find an existing
10615 // capture of that variable.
10616 CaptureType = Var->getType();
10617 DeclRefType = CaptureType.getNonReferenceType();
10618 bool Explicit = (Kind != TryCapture_Implicit);
10619 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010620 do {
Eli Friedman24af8502012-02-03 22:47:37 +000010621 // Only block literals and lambda expressions can capture; other
Eli Friedman9bb33f52012-02-03 02:04:35 +000010622 // scopes don't work.
Eli Friedman24af8502012-02-03 22:47:37 +000010623 DeclContext *ParentDC;
10624 if (isa<BlockDecl>(DC))
10625 ParentDC = DC->getParent();
10626 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregor81495f32012-02-12 18:42:33 +000010627 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedman24af8502012-02-03 22:47:37 +000010628 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10629 ParentDC = DC->getParent()->getParent();
Douglas Gregor81495f32012-02-12 18:42:33 +000010630 else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010631 if (BuildAndDiagnose)
Douglas Gregor81495f32012-02-12 18:42:33 +000010632 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010633 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000010634 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010635
Eli Friedman24af8502012-02-03 22:47:37 +000010636 CapturingScopeInfo *CSI =
Douglas Gregor81495f32012-02-12 18:42:33 +000010637 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010638
Eli Friedman24af8502012-02-03 22:47:37 +000010639 // Check whether we've already captured it.
Douglas Gregor81495f32012-02-12 18:42:33 +000010640 if (CSI->CaptureMap.count(Var)) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010641 // If we found a capture, any subcaptures are nested.
Eli Friedman9bb33f52012-02-03 02:04:35 +000010642 Nested = true;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010643
10644 // Retrieve the capture type for this variable.
10645 CaptureType = CSI->getCapture(Var).getCaptureType();
10646
10647 // Compute the type of an expression that refers to this variable.
10648 DeclRefType = CaptureType.getNonReferenceType();
10649
10650 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10651 if (Cap.isCopyCapture() &&
10652 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10653 DeclRefType.addConst();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010654 break;
10655 }
10656
Douglas Gregor81495f32012-02-12 18:42:33 +000010657 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010658 bool IsLambda = !IsBlock;
Eli Friedman24af8502012-02-03 22:47:37 +000010659
10660 // Lambdas are not allowed to capture unnamed variables
10661 // (e.g. anonymous unions).
10662 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10663 // assuming that's the intent.
Douglas Gregor81495f32012-02-12 18:42:33 +000010664 if (IsLambda && !Var->getDeclName()) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010665 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010666 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10667 Diag(Var->getLocation(), diag::note_declared_at);
10668 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010669 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000010670 }
10671
10672 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010673 if (Var->getType()->isVariablyModifiedType()) {
10674 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010675 if (IsBlock)
10676 Diag(Loc, diag::err_ref_vm_type);
10677 else
10678 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10679 Diag(Var->getLocation(), diag::note_previous_decl)
10680 << Var->getDeclName();
10681 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010682 return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010683 }
10684
Eli Friedman24af8502012-02-03 22:47:37 +000010685 // Lambdas are not allowed to capture __block variables; they don't
10686 // support the expected semantics.
Douglas Gregor81495f32012-02-12 18:42:33 +000010687 if (IsLambda && HasBlocksAttr) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010688 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010689 Diag(Loc, diag::err_lambda_capture_block)
10690 << Var->getDeclName();
10691 Diag(Var->getLocation(), diag::note_previous_decl)
10692 << Var->getDeclName();
10693 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010694 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000010695 }
10696
Douglas Gregor81495f32012-02-12 18:42:33 +000010697 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10698 // No capture-default
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010699 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010700 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10701 Diag(Var->getLocation(), diag::note_previous_decl)
10702 << Var->getDeclName();
10703 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10704 diag::note_lambda_decl);
10705 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010706 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000010707 }
10708
10709 FunctionScopesIndex--;
10710 DC = ParentDC;
10711 Explicit = false;
10712 } while (!Var->getDeclContext()->Equals(DC));
10713
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010714 // Walk back down the scope stack, computing the type of the capture at
10715 // each step, checking type-specific requirements, and adding captures if
10716 // requested.
10717 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10718 ++I) {
10719 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor812d8f62012-02-18 05:51:20 +000010720
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010721 // Compute the type of the capture and of a reference to the capture within
10722 // this scope.
10723 if (isa<BlockScopeInfo>(CSI)) {
10724 Expr *CopyExpr = 0;
10725 bool ByRef = false;
10726
10727 // Blocks are not allowed to capture arrays.
10728 if (CaptureType->isArrayType()) {
10729 if (BuildAndDiagnose) {
10730 Diag(Loc, diag::err_ref_array_type);
10731 Diag(Var->getLocation(), diag::note_previous_decl)
10732 << Var->getDeclName();
10733 }
10734 return true;
10735 }
10736
John McCall67cd5e02012-03-30 05:23:48 +000010737 // Forbid the block-capture of autoreleasing variables.
10738 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10739 if (BuildAndDiagnose) {
10740 Diag(Loc, diag::err_arc_autoreleasing_capture)
10741 << /*block*/ 0;
10742 Diag(Var->getLocation(), diag::note_previous_decl)
10743 << Var->getDeclName();
10744 }
10745 return true;
10746 }
10747
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010748 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10749 // Block capture by reference does not change the capture or
10750 // declaration reference types.
10751 ByRef = true;
10752 } else {
10753 // Block capture by copy introduces 'const'.
10754 CaptureType = CaptureType.getNonReferenceType().withConst();
10755 DeclRefType = CaptureType;
10756
David Blaikiebbafb8a2012-03-11 07:00:24 +000010757 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010758 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10759 // The capture logic needs the destructor, so make sure we mark it.
10760 // Usually this is unnecessary because most local variables have
10761 // their destructors marked at declaration time, but parameters are
10762 // an exception because it's technically only the call site that
10763 // actually requires the destructor.
10764 if (isa<ParmVarDecl>(Var))
10765 FinalizeVarWithDestructor(Var, Record);
10766
10767 // According to the blocks spec, the capture of a variable from
10768 // the stack requires a const copy constructor. This is not true
10769 // of the copy/move done to move a __block variable to the heap.
John McCall113bee02012-03-10 09:33:50 +000010770 Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010771 DeclRefType.withConst(),
10772 VK_LValue, Loc);
10773 ExprResult Result
10774 = PerformCopyInitialization(
10775 InitializedEntity::InitializeBlock(Var->getLocation(),
10776 CaptureType, false),
10777 Loc, Owned(DeclRef));
10778
10779 // Build a full-expression copy expression if initialization
10780 // succeeded and used a non-trivial constructor. Recover from
10781 // errors by pretending that the copy isn't necessary.
10782 if (!Result.isInvalid() &&
10783 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10784 ->isTrivial()) {
10785 Result = MaybeCreateExprWithCleanups(Result);
10786 CopyExpr = Result.take();
10787 }
10788 }
10789 }
10790 }
10791
10792 // Actually capture the variable.
10793 if (BuildAndDiagnose)
10794 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10795 SourceLocation(), CaptureType, CopyExpr);
10796 Nested = true;
10797 continue;
10798 }
Douglas Gregor812d8f62012-02-18 05:51:20 +000010799
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010800 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10801
10802 // Determine whether we are capturing by reference or by value.
10803 bool ByRef = false;
10804 if (I == N - 1 && Kind != TryCapture_Implicit) {
10805 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedman24af8502012-02-03 22:47:37 +000010806 } else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010807 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedman24af8502012-02-03 22:47:37 +000010808 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010809
10810 // Compute the type of the field that will capture this variable.
10811 if (ByRef) {
10812 // C++11 [expr.prim.lambda]p15:
10813 // An entity is captured by reference if it is implicitly or
10814 // explicitly captured but not captured by copy. It is
10815 // unspecified whether additional unnamed non-static data
10816 // members are declared in the closure type for entities
10817 // captured by reference.
10818 //
10819 // FIXME: It is not clear whether we want to build an lvalue reference
10820 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10821 // to do the former, while EDG does the latter. Core issue 1249 will
10822 // clarify, but for now we follow GCC because it's a more permissive and
10823 // easily defensible position.
10824 CaptureType = Context.getLValueReferenceType(DeclRefType);
10825 } else {
10826 // C++11 [expr.prim.lambda]p14:
10827 // For each entity captured by copy, an unnamed non-static
10828 // data member is declared in the closure type. The
10829 // declaration order of these members is unspecified. The type
10830 // of such a data member is the type of the corresponding
10831 // captured entity if the entity is not a reference to an
10832 // object, or the referenced type otherwise. [Note: If the
10833 // captured entity is a reference to a function, the
10834 // corresponding data member is also a reference to a
10835 // function. - end note ]
10836 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10837 if (!RefType->getPointeeType()->isFunctionType())
10838 CaptureType = RefType->getPointeeType();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010839 }
John McCall67cd5e02012-03-30 05:23:48 +000010840
10841 // Forbid the lambda copy-capture of autoreleasing variables.
10842 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10843 if (BuildAndDiagnose) {
10844 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10845 Diag(Var->getLocation(), diag::note_previous_decl)
10846 << Var->getDeclName();
10847 }
10848 return true;
10849 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010850 }
10851
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010852 // Capture this variable in the lambda.
10853 Expr *CopyExpr = 0;
10854 if (BuildAndDiagnose) {
10855 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
Douglas Gregora8182f92012-05-16 17:01:33 +000010856 DeclRefType, Loc,
10857 I == N-1);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010858 if (!Result.isInvalid())
10859 CopyExpr = Result.take();
10860 }
10861
10862 // Compute the type of a reference to this captured variable.
10863 if (ByRef)
10864 DeclRefType = CaptureType.getNonReferenceType();
10865 else {
10866 // C++ [expr.prim.lambda]p5:
10867 // The closure type for a lambda-expression has a public inline
10868 // function call operator [...]. This function call operator is
10869 // declared const (9.3.1) if and only if the lambda-expression’s
10870 // parameter-declaration-clause is not followed by mutable.
10871 DeclRefType = CaptureType.getNonReferenceType();
10872 if (!LSI->Mutable && !CaptureType->isReferenceType())
10873 DeclRefType.addConst();
10874 }
10875
10876 // Add the capture.
10877 if (BuildAndDiagnose)
10878 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10879 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010880 Nested = true;
10881 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010882
10883 return false;
10884}
10885
10886bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10887 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10888 QualType CaptureType;
10889 QualType DeclRefType;
10890 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10891 /*BuildAndDiagnose=*/true, CaptureType,
10892 DeclRefType);
10893}
10894
10895QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10896 QualType CaptureType;
10897 QualType DeclRefType;
10898
10899 // Determine whether we can capture this variable.
10900 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10901 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10902 return QualType();
10903
10904 return DeclRefType;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010905}
10906
Eli Friedman3bda6b12012-02-02 23:15:15 +000010907static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10908 SourceLocation Loc) {
10909 // Keep track of used but undefined variables.
Eli Friedman130bbd02012-02-04 00:54:05 +000010910 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar9d355812012-03-09 01:51:51 +000010911 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman130bbd02012-02-04 00:54:05 +000010912 Var->getLinkage() != ExternalLinkage &&
10913 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010914 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10915 if (old.isInvalid()) old = Loc;
10916 }
10917
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010918 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010919
Eli Friedman3bda6b12012-02-02 23:15:15 +000010920 Var->setUsed(true);
10921}
10922
10923void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10924 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10925 // an object that satisfies the requirements for appearing in a
10926 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10927 // is immediately applied." This function handles the lvalue-to-rvalue
10928 // conversion part.
10929 MaybeODRUseExprs.erase(E->IgnoreParens());
10930}
10931
Eli Friedmanc6237c62012-02-29 03:16:56 +000010932ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10933 if (!Res.isUsable())
10934 return Res;
10935
10936 // If a constant-expression is a reference to a variable where we delay
10937 // deciding whether it is an odr-use, just assume we will apply the
10938 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
10939 // (a non-type template argument), we have special handling anyway.
10940 UpdateMarkingForLValueToRValue(Res.get());
10941 return Res;
10942}
10943
Eli Friedman3bda6b12012-02-02 23:15:15 +000010944void Sema::CleanupVarDeclMarking() {
10945 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10946 e = MaybeODRUseExprs.end();
10947 i != e; ++i) {
10948 VarDecl *Var;
10949 SourceLocation Loc;
John McCall113bee02012-03-10 09:33:50 +000010950 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010951 Var = cast<VarDecl>(DRE->getDecl());
10952 Loc = DRE->getLocation();
10953 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10954 Var = cast<VarDecl>(ME->getMemberDecl());
10955 Loc = ME->getMemberLoc();
10956 } else {
10957 llvm_unreachable("Unexpcted expression");
10958 }
10959
10960 MarkVarDeclODRUsed(*this, Var, Loc);
10961 }
10962
10963 MaybeODRUseExprs.clear();
10964}
10965
10966// Mark a VarDecl referenced, and perform the necessary handling to compute
10967// odr-uses.
10968static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10969 VarDecl *Var, Expr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010970 Var->setReferenced();
10971
Eli Friedman3bda6b12012-02-02 23:15:15 +000010972 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010973 return;
10974
10975 // Implicit instantiation of static data members of class templates.
Richard Smithd3cf2382012-02-15 02:42:50 +000010976 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010977 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10978 assert(MSInfo && "Missing member specialization information?");
Richard Smithd3cf2382012-02-15 02:42:50 +000010979 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10980 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000010981 (!AlreadyInstantiated ||
10982 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smithd3cf2382012-02-15 02:42:50 +000010983 if (!AlreadyInstantiated) {
10984 // This is a modification of an existing AST node. Notify listeners.
10985 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10986 L->StaticDataMemberInstantiated(Var);
10987 MSInfo->setPointOfInstantiation(Loc);
10988 }
10989 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar9d355812012-03-09 01:51:51 +000010990 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010991 // Do not defer instantiations of variables which could be used in a
10992 // constant expression.
Richard Smithd3cf2382012-02-15 02:42:50 +000010993 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010994 else
Richard Smithd3cf2382012-02-15 02:42:50 +000010995 SemaRef.PendingInstantiations.push_back(
10996 std::make_pair(Var, PointOfInstantiation));
Eli Friedmanfa0df832012-02-02 03:46:19 +000010997 }
10998 }
10999
Eli Friedman3bda6b12012-02-02 23:15:15 +000011000 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
11001 // an object that satisfies the requirements for appearing in a
11002 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
11003 // is immediately applied." We check the first part here, and
11004 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
11005 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith35ecb362012-03-02 04:14:40 +000011006 // C++03 depends on whether we get the C++03 version correct. This does not
11007 // apply to references, since they are not objects.
Eli Friedman3bda6b12012-02-02 23:15:15 +000011008 const VarDecl *DefVD;
Richard Smith35ecb362012-03-02 04:14:40 +000011009 if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000011010 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Eli Friedman3bda6b12012-02-02 23:15:15 +000011011 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
11012 SemaRef.MaybeODRUseExprs.insert(E);
11013 else
11014 MarkVarDeclODRUsed(SemaRef, Var, Loc);
11015}
Eli Friedmanfa0df832012-02-02 03:46:19 +000011016
Eli Friedman3bda6b12012-02-02 23:15:15 +000011017/// \brief Mark a variable referenced, and check whether it is odr-used
11018/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
11019/// used directly for normal expressions referring to VarDecl.
11020void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
11021 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedmanfa0df832012-02-02 03:46:19 +000011022}
11023
11024static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
11025 Decl *D, Expr *E) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000011026 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
11027 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
11028 return;
11029 }
11030
Eli Friedmanfa0df832012-02-02 03:46:19 +000011031 SemaRef.MarkAnyDeclReferenced(Loc, D);
Rafael Espindola49e860b2012-06-26 17:45:31 +000011032
11033 // If this is a call to a method via a cast, also mark the method in the
11034 // derived class used in case codegen can devirtualize the call.
11035 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11036 if (!ME)
11037 return;
11038 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
11039 if (!MD)
11040 return;
11041 const Expr *Base = ME->getBase();
Rafael Espindolab7f5a9c2012-06-27 18:18:05 +000011042 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Rafael Espindola49e860b2012-06-26 17:45:31 +000011043 if (!MostDerivedClassDecl)
11044 return;
11045 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
Rafael Espindolaa245edc2012-06-27 17:44:39 +000011046 if (!DM)
11047 return;
Rafael Espindola49e860b2012-06-26 17:45:31 +000011048 SemaRef.MarkAnyDeclReferenced(Loc, DM);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011049}
Eli Friedmanfa0df832012-02-02 03:46:19 +000011050
Eli Friedmanfa0df832012-02-02 03:46:19 +000011051/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
11052void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
11053 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
11054}
11055
11056/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
11057void Sema::MarkMemberReferenced(MemberExpr *E) {
11058 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
11059}
11060
Douglas Gregorf02455e2012-02-10 09:26:04 +000011061/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedmanfa0df832012-02-02 03:46:19 +000011062/// marks the declaration referenced, and performs odr-use checking for functions
11063/// and variables. This method should not be used when building an normal
11064/// expression which refers to a variable.
11065void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
11066 if (VarDecl *VD = dyn_cast<VarDecl>(D))
11067 MarkVariableReferenced(Loc, VD);
11068 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
11069 MarkFunctionReferenced(Loc, FD);
11070 else
11071 D->setReferenced();
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000011072}
Anders Carlsson7f84ed92009-10-09 23:51:55 +000011073
Douglas Gregor5597ab42010-05-07 23:12:07 +000011074namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +000011075 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +000011076 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +000011077 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +000011078 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
11079 Sema &S;
11080 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +000011081
Douglas Gregor5597ab42010-05-07 23:12:07 +000011082 public:
11083 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +000011084
Douglas Gregor5597ab42010-05-07 23:12:07 +000011085 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +000011086
11087 bool TraverseTemplateArgument(const TemplateArgument &Arg);
11088 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +000011089 };
11090}
11091
Chandler Carruthaf80f662010-06-09 08:17:30 +000011092bool MarkReferencedDecls::TraverseTemplateArgument(
11093 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000011094 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +000011095 if (Decl *D = Arg.getAsDecl())
11096 S.MarkAnyDeclReferenced(Loc, D);
Douglas Gregor5597ab42010-05-07 23:12:07 +000011097 }
Chandler Carruthaf80f662010-06-09 08:17:30 +000011098
11099 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +000011100}
11101
Chandler Carruthaf80f662010-06-09 08:17:30 +000011102bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000011103 if (ClassTemplateSpecializationDecl *Spec
11104 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11105 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +000011106 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +000011107 }
11108
Chandler Carruthc65667c2010-06-10 10:31:57 +000011109 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +000011110}
11111
11112void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11113 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +000011114 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +000011115}
11116
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011117namespace {
11118 /// \brief Helper class that marks all of the declarations referenced by
11119 /// potentially-evaluated subexpressions as "referenced".
11120 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11121 Sema &S;
Douglas Gregor680e9e02012-02-21 19:11:17 +000011122 bool SkipLocalVariables;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011123
11124 public:
11125 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11126
Douglas Gregor680e9e02012-02-21 19:11:17 +000011127 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11128 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011129
11130 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregor680e9e02012-02-21 19:11:17 +000011131 // If we were asked not to visit local variables, don't.
11132 if (SkipLocalVariables) {
11133 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11134 if (VD->hasLocalStorage())
11135 return;
11136 }
11137
Eli Friedmanfa0df832012-02-02 03:46:19 +000011138 S.MarkDeclRefReferenced(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011139 }
11140
11141 void VisitMemberExpr(MemberExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011142 S.MarkMemberReferenced(E);
Douglas Gregor32b3de52010-09-11 23:32:50 +000011143 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011144 }
11145
John McCall28fc7092011-11-10 05:35:25 +000011146 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011147 S.MarkFunctionReferenced(E->getLocStart(),
John McCall28fc7092011-11-10 05:35:25 +000011148 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11149 Visit(E->getSubExpr());
11150 }
11151
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011152 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011153 if (E->getOperatorNew())
Eli Friedmanfa0df832012-02-02 03:46:19 +000011154 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011155 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000011156 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +000011157 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011158 }
Sebastian Redl6047f072012-02-16 12:22:20 +000011159
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011160 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11161 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000011162 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000011163 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11164 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11165 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedmanfa0df832012-02-02 03:46:19 +000011166 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000011167 S.LookupDestructor(Record));
11168 }
11169
Douglas Gregor32b3de52010-09-11 23:32:50 +000011170 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011171 }
11172
11173 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011174 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +000011175 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011176 }
11177
Douglas Gregorf0873f42010-10-19 17:17:35 +000011178 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11179 Visit(E->getExpr());
11180 }
Eli Friedman3bda6b12012-02-02 23:15:15 +000011181
11182 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11183 Inherited::VisitImplicitCastExpr(E);
11184
11185 if (E->getCastKind() == CK_LValueToRValue)
11186 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11187 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011188 };
11189}
11190
11191/// \brief Mark any declarations that appear within this expression or any
11192/// potentially-evaluated subexpressions as "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +000011193///
11194/// \param SkipLocalVariables If true, don't mark local variables as
11195/// 'referenced'.
11196void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11197 bool SkipLocalVariables) {
11198 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011199}
11200
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011201/// \brief Emit a diagnostic that describes an effect on the run-time behavior
11202/// of the program being compiled.
11203///
11204/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011205/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011206/// possibility that the code will actually be executable. Code in sizeof()
11207/// expressions, code used only during overload resolution, etc., are not
11208/// potentially evaluated. This routine will suppress such diagnostics or,
11209/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011210/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011211/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011212///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011213/// This routine should be used for all diagnostics that describe the run-time
11214/// behavior of a program, such as passing a non-POD value through an ellipsis.
11215/// Failure to do so will likely result in spurious diagnostics or failures
11216/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuba63ce62011-09-09 01:45:06 +000011217bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011218 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +000011219 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011220 case Unevaluated:
11221 // The argument will never be evaluated, so don't complain.
11222 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011223
Richard Smith764d2fe2011-12-20 02:08:33 +000011224 case ConstantEvaluated:
11225 // Relevant diagnostics should be produced by constant evaluation.
11226 break;
11227
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011228 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011229 case PotentiallyEvaluatedIfUsed:
Richard Trieuba63ce62011-09-09 01:45:06 +000011230 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +000011231 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuba63ce62011-09-09 01:45:06 +000011232 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek3427fac2011-02-23 01:52:04 +000011233 }
11234 else
11235 Diag(Loc, PD);
11236
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011237 return true;
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011238 }
11239
11240 return false;
11241}
11242
Anders Carlsson7f84ed92009-10-09 23:51:55 +000011243bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11244 CallExpr *CE, FunctionDecl *FD) {
11245 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11246 return false;
11247
Richard Smithfd555f62012-02-22 02:04:18 +000011248 // If we're inside a decltype's expression, don't check for a valid return
11249 // type or construct temporaries until we know whether this is the last call.
11250 if (ExprEvalContexts.back().IsDecltype) {
11251 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11252 return false;
11253 }
11254
Douglas Gregora6c5abb2012-05-04 16:48:41 +000011255 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011256 FunctionDecl *FD;
11257 CallExpr *CE;
11258
11259 public:
11260 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11261 : FD(FD), CE(CE) { }
11262
11263 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11264 if (!FD) {
11265 S.Diag(Loc, diag::err_call_incomplete_return)
11266 << T << CE->getSourceRange();
11267 return;
11268 }
11269
11270 S.Diag(Loc, diag::err_call_function_incomplete_return)
11271 << CE->getSourceRange() << FD->getDeclName() << T;
11272 S.Diag(FD->getLocation(),
11273 diag::note_function_with_incomplete_return_type_declared_here)
11274 << FD->getDeclName();
11275 }
11276 } Diagnoser(FD, CE);
11277
11278 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson7f84ed92009-10-09 23:51:55 +000011279 return true;
11280
11281 return false;
11282}
11283
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011284// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000011285// will prevent this condition from triggering, which is what we want.
11286void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11287 SourceLocation Loc;
11288
John McCall0506e4a2009-11-11 02:41:58 +000011289 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011290 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000011291
Chandler Carruthf87d6c02011-08-16 22:30:10 +000011292 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011293 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000011294 return;
11295
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011296 IsOrAssign = Op->getOpcode() == BO_OrAssign;
11297
John McCallb0e419e2009-11-12 00:06:05 +000011298 // Greylist some idioms by putting them into a warning subcategory.
11299 if (ObjCMessageExpr *ME
11300 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11301 Selector Sel = ME->getSelector();
11302
John McCallb0e419e2009-11-12 00:06:05 +000011303 // self = [<foo> init...]
Douglas Gregor486b74e2011-09-27 16:10:05 +000011304 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +000011305 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11306
11307 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000011308 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000011309 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11310 }
John McCall0506e4a2009-11-11 02:41:58 +000011311
John McCalld5707ab2009-10-12 21:59:07 +000011312 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +000011313 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011314 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000011315 return;
11316
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011317 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000011318 Loc = Op->getOperatorLoc();
Fariborz Jahanianf07bcc52012-08-29 17:17:11 +000011319 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
11320 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
11321 else {
John McCalld5707ab2009-10-12 21:59:07 +000011322 // Not an assignment.
11323 return;
11324 }
11325
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000011326 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011327
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011328 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000011329 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11330 Diag(Loc, diag::note_condition_assign_silence)
11331 << FixItHint::CreateInsertion(Open, "(")
11332 << FixItHint::CreateInsertion(Close, ")");
11333
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011334 if (IsOrAssign)
11335 Diag(Loc, diag::note_condition_or_assign_to_comparison)
11336 << FixItHint::CreateReplacement(Loc, "!=");
11337 else
11338 Diag(Loc, diag::note_condition_assign_to_comparison)
11339 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +000011340}
11341
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011342/// \brief Redundant parentheses over an equality comparison can indicate
11343/// that the user intended an assignment used as condition.
Richard Trieuba63ce62011-09-09 01:45:06 +000011344void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011345 // Don't warn if the parens came from a macro.
Richard Trieuba63ce62011-09-09 01:45:06 +000011346 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011347 if (parenLoc.isInvalid() || parenLoc.isMacroID())
11348 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000011349 // Don't warn for dependent expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +000011350 if (ParenE->isTypeDependent())
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000011351 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011352
Richard Trieuba63ce62011-09-09 01:45:06 +000011353 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011354
11355 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000011356 if (opE->getOpcode() == BO_EQ &&
11357 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11358 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011359 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000011360
Ted Kremenekae022092011-02-02 02:20:30 +000011361 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011362 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +000011363 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011364 << FixItHint::CreateRemoval(ParenERange.getBegin())
11365 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000011366 Diag(Loc, diag::note_equality_comparison_to_assign)
11367 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011368 }
11369}
11370
John Wiegley01296292011-04-08 18:41:53 +000011371ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +000011372 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011373 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11374 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000011375
John McCall0009fcc2011-04-26 20:42:42 +000011376 ExprResult result = CheckPlaceholderExpr(E);
11377 if (result.isInvalid()) return ExprError();
11378 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000011379
John McCall0009fcc2011-04-26 20:42:42 +000011380 if (!E->isTypeDependent()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000011381 if (getLangOpts().CPlusPlus)
John McCall34376a62010-12-04 03:47:34 +000011382 return CheckCXXBooleanCondition(E); // C++ 6.4p4
11383
John Wiegley01296292011-04-08 18:41:53 +000011384 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11385 if (ERes.isInvalid())
11386 return ExprError();
11387 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +000011388
11389 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000011390 if (!T->isScalarType()) { // C99 6.8.4.1p1
11391 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11392 << T << E->getSourceRange();
11393 return ExprError();
11394 }
John McCalld5707ab2009-10-12 21:59:07 +000011395 }
11396
John Wiegley01296292011-04-08 18:41:53 +000011397 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +000011398}
Douglas Gregore60e41a2010-05-06 17:25:47 +000011399
John McCalldadc5752010-08-24 06:29:42 +000011400ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +000011401 Expr *SubExpr) {
11402 if (!SubExpr)
Douglas Gregore60e41a2010-05-06 17:25:47 +000011403 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011404
Richard Trieuba63ce62011-09-09 01:45:06 +000011405 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +000011406}
John McCall36e7fe32010-10-12 00:20:44 +000011407
John McCall31996342011-04-07 08:22:57 +000011408namespace {
John McCall2979fe02011-04-12 00:42:48 +000011409 /// A visitor for rebuilding a call to an __unknown_any expression
11410 /// to have an appropriate type.
11411 struct RebuildUnknownAnyFunction
11412 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11413
11414 Sema &S;
11415
11416 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11417
11418 ExprResult VisitStmt(Stmt *S) {
11419 llvm_unreachable("unexpected statement!");
John McCall2979fe02011-04-12 00:42:48 +000011420 }
11421
Richard Trieu10162ab2011-09-09 03:59:41 +000011422 ExprResult VisitExpr(Expr *E) {
11423 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11424 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011425 return ExprError();
11426 }
11427
11428 /// Rebuild an expression which simply semantically wraps another
11429 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000011430 template <class T> ExprResult rebuildSugarExpr(T *E) {
11431 ExprResult SubResult = Visit(E->getSubExpr());
11432 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000011433
Richard Trieu10162ab2011-09-09 03:59:41 +000011434 Expr *SubExpr = SubResult.take();
11435 E->setSubExpr(SubExpr);
11436 E->setType(SubExpr->getType());
11437 E->setValueKind(SubExpr->getValueKind());
11438 assert(E->getObjectKind() == OK_Ordinary);
11439 return E;
John McCall2979fe02011-04-12 00:42:48 +000011440 }
11441
Richard Trieu10162ab2011-09-09 03:59:41 +000011442 ExprResult VisitParenExpr(ParenExpr *E) {
11443 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011444 }
11445
Richard Trieu10162ab2011-09-09 03:59:41 +000011446 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11447 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011448 }
11449
Richard Trieu10162ab2011-09-09 03:59:41 +000011450 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11451 ExprResult SubResult = Visit(E->getSubExpr());
11452 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000011453
Richard Trieu10162ab2011-09-09 03:59:41 +000011454 Expr *SubExpr = SubResult.take();
11455 E->setSubExpr(SubExpr);
11456 E->setType(S.Context.getPointerType(SubExpr->getType()));
11457 assert(E->getValueKind() == VK_RValue);
11458 assert(E->getObjectKind() == OK_Ordinary);
11459 return E;
John McCall2979fe02011-04-12 00:42:48 +000011460 }
11461
Richard Trieu10162ab2011-09-09 03:59:41 +000011462 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11463 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011464
Richard Trieu10162ab2011-09-09 03:59:41 +000011465 E->setType(VD->getType());
John McCall2979fe02011-04-12 00:42:48 +000011466
Richard Trieu10162ab2011-09-09 03:59:41 +000011467 assert(E->getValueKind() == VK_RValue);
David Blaikiebbafb8a2012-03-11 07:00:24 +000011468 if (S.getLangOpts().CPlusPlus &&
Richard Trieu10162ab2011-09-09 03:59:41 +000011469 !(isa<CXXMethodDecl>(VD) &&
11470 cast<CXXMethodDecl>(VD)->isInstance()))
11471 E->setValueKind(VK_LValue);
John McCall2979fe02011-04-12 00:42:48 +000011472
Richard Trieu10162ab2011-09-09 03:59:41 +000011473 return E;
John McCall2979fe02011-04-12 00:42:48 +000011474 }
11475
Richard Trieu10162ab2011-09-09 03:59:41 +000011476 ExprResult VisitMemberExpr(MemberExpr *E) {
11477 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000011478 }
11479
Richard Trieu10162ab2011-09-09 03:59:41 +000011480 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11481 return resolveDecl(E, E->getDecl());
John McCall2979fe02011-04-12 00:42:48 +000011482 }
11483 };
11484}
11485
11486/// Given a function expression of unknown-any type, try to rebuild it
11487/// to have a function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011488static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11489 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11490 if (Result.isInvalid()) return ExprError();
11491 return S.DefaultFunctionArrayConversion(Result.take());
John McCall2979fe02011-04-12 00:42:48 +000011492}
11493
11494namespace {
John McCall2d2e8702011-04-11 07:02:50 +000011495 /// A visitor for rebuilding an expression of type __unknown_anytype
11496 /// into one which resolves the type directly on the referring
11497 /// expression. Strict preservation of the original source
11498 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +000011499 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +000011500 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +000011501
11502 Sema &S;
11503
11504 /// The current destination type.
11505 QualType DestType;
11506
Richard Trieu10162ab2011-09-09 03:59:41 +000011507 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11508 : S(S), DestType(CastType) {}
John McCall31996342011-04-07 08:22:57 +000011509
John McCall39439732011-04-09 22:50:59 +000011510 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +000011511 llvm_unreachable("unexpected statement!");
John McCall31996342011-04-07 08:22:57 +000011512 }
11513
Richard Trieu10162ab2011-09-09 03:59:41 +000011514 ExprResult VisitExpr(Expr *E) {
11515 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11516 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011517 return ExprError();
John McCall31996342011-04-07 08:22:57 +000011518 }
11519
Richard Trieu10162ab2011-09-09 03:59:41 +000011520 ExprResult VisitCallExpr(CallExpr *E);
11521 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall2d2e8702011-04-11 07:02:50 +000011522
John McCall39439732011-04-09 22:50:59 +000011523 /// Rebuild an expression which simply semantically wraps another
11524 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000011525 template <class T> ExprResult rebuildSugarExpr(T *E) {
11526 ExprResult SubResult = Visit(E->getSubExpr());
11527 if (SubResult.isInvalid()) return ExprError();
11528 Expr *SubExpr = SubResult.take();
11529 E->setSubExpr(SubExpr);
11530 E->setType(SubExpr->getType());
11531 E->setValueKind(SubExpr->getValueKind());
11532 assert(E->getObjectKind() == OK_Ordinary);
11533 return E;
John McCall39439732011-04-09 22:50:59 +000011534 }
John McCall31996342011-04-07 08:22:57 +000011535
Richard Trieu10162ab2011-09-09 03:59:41 +000011536 ExprResult VisitParenExpr(ParenExpr *E) {
11537 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000011538 }
11539
Richard Trieu10162ab2011-09-09 03:59:41 +000011540 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11541 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000011542 }
11543
Richard Trieu10162ab2011-09-09 03:59:41 +000011544 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11545 const PointerType *Ptr = DestType->getAs<PointerType>();
11546 if (!Ptr) {
11547 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11548 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011549 return ExprError();
11550 }
Richard Trieu10162ab2011-09-09 03:59:41 +000011551 assert(E->getValueKind() == VK_RValue);
11552 assert(E->getObjectKind() == OK_Ordinary);
11553 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +000011554
11555 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011556 DestType = Ptr->getPointeeType();
11557 ExprResult SubResult = Visit(E->getSubExpr());
11558 if (SubResult.isInvalid()) return ExprError();
11559 E->setSubExpr(SubResult.take());
11560 return E;
John McCall2979fe02011-04-12 00:42:48 +000011561 }
11562
Richard Trieu10162ab2011-09-09 03:59:41 +000011563 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCall39439732011-04-09 22:50:59 +000011564
Richard Trieu10162ab2011-09-09 03:59:41 +000011565 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCall39439732011-04-09 22:50:59 +000011566
Richard Trieu10162ab2011-09-09 03:59:41 +000011567 ExprResult VisitMemberExpr(MemberExpr *E) {
11568 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000011569 }
John McCall39439732011-04-09 22:50:59 +000011570
Richard Trieu10162ab2011-09-09 03:59:41 +000011571 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11572 return resolveDecl(E, E->getDecl());
John McCall31996342011-04-07 08:22:57 +000011573 }
11574 };
11575}
11576
John McCall2d2e8702011-04-11 07:02:50 +000011577/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu10162ab2011-09-09 03:59:41 +000011578ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11579 Expr *CalleeExpr = E->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000011580
11581 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +000011582 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +000011583 FK_FunctionPointer,
11584 FK_BlockPointer
11585 };
11586
Richard Trieu10162ab2011-09-09 03:59:41 +000011587 FnKind Kind;
11588 QualType CalleeType = CalleeExpr->getType();
11589 if (CalleeType == S.Context.BoundMemberTy) {
11590 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11591 Kind = FK_MemberFunction;
11592 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11593 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11594 CalleeType = Ptr->getPointeeType();
11595 Kind = FK_FunctionPointer;
John McCall2d2e8702011-04-11 07:02:50 +000011596 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000011597 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11598 Kind = FK_BlockPointer;
John McCall2d2e8702011-04-11 07:02:50 +000011599 }
Richard Trieu10162ab2011-09-09 03:59:41 +000011600 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall2d2e8702011-04-11 07:02:50 +000011601
11602 // Verify that this is a legal result type of a function.
11603 if (DestType->isArrayType() || DestType->isFunctionType()) {
11604 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu10162ab2011-09-09 03:59:41 +000011605 if (Kind == FK_BlockPointer)
John McCall2d2e8702011-04-11 07:02:50 +000011606 diagID = diag::err_block_returning_array_function;
11607
Richard Trieu10162ab2011-09-09 03:59:41 +000011608 S.Diag(E->getExprLoc(), diagID)
John McCall2d2e8702011-04-11 07:02:50 +000011609 << DestType->isFunctionType() << DestType;
11610 return ExprError();
11611 }
11612
11613 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu10162ab2011-09-09 03:59:41 +000011614 E->setType(DestType.getNonLValueExprType(S.Context));
11615 E->setValueKind(Expr::getValueKindForType(DestType));
11616 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000011617
11618 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu10162ab2011-09-09 03:59:41 +000011619 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall2d2e8702011-04-11 07:02:50 +000011620 DestType = S.Context.getFunctionType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000011621 Proto->arg_type_begin(),
11622 Proto->getNumArgs(),
11623 Proto->getExtProtoInfo());
John McCall2d2e8702011-04-11 07:02:50 +000011624 else
11625 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000011626 FnType->getExtInfo());
John McCall2d2e8702011-04-11 07:02:50 +000011627
11628 // Rebuild the appropriate pointer-to-function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011629 switch (Kind) {
John McCall4adb38c2011-04-27 00:36:17 +000011630 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +000011631 // Nothing to do.
11632 break;
11633
11634 case FK_FunctionPointer:
11635 DestType = S.Context.getPointerType(DestType);
11636 break;
11637
11638 case FK_BlockPointer:
11639 DestType = S.Context.getBlockPointerType(DestType);
11640 break;
11641 }
11642
11643 // Finally, we can recurse.
Richard Trieu10162ab2011-09-09 03:59:41 +000011644 ExprResult CalleeResult = Visit(CalleeExpr);
11645 if (!CalleeResult.isUsable()) return ExprError();
11646 E->setCallee(CalleeResult.take());
John McCall2d2e8702011-04-11 07:02:50 +000011647
11648 // Bind a temporary if necessary.
Richard Trieu10162ab2011-09-09 03:59:41 +000011649 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000011650}
11651
Richard Trieu10162ab2011-09-09 03:59:41 +000011652ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000011653 // Verify that this is a legal result type of a call.
11654 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu10162ab2011-09-09 03:59:41 +000011655 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall2979fe02011-04-12 00:42:48 +000011656 << DestType->isFunctionType() << DestType;
11657 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011658 }
11659
John McCall3f4138c2011-07-13 17:56:40 +000011660 // Rewrite the method result type if available.
Richard Trieu10162ab2011-09-09 03:59:41 +000011661 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11662 assert(Method->getResultType() == S.Context.UnknownAnyTy);
11663 Method->setResultType(DestType);
John McCall3f4138c2011-07-13 17:56:40 +000011664 }
John McCall2979fe02011-04-12 00:42:48 +000011665
John McCall2d2e8702011-04-11 07:02:50 +000011666 // Change the type of the message.
Richard Trieu10162ab2011-09-09 03:59:41 +000011667 E->setType(DestType.getNonReferenceType());
11668 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000011669
Richard Trieu10162ab2011-09-09 03:59:41 +000011670 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000011671}
11672
Richard Trieu10162ab2011-09-09 03:59:41 +000011673ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000011674 // The only case we should ever see here is a function-to-pointer decay.
Sean Callanan2db103c2012-03-06 23:12:57 +000011675 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanan12495112012-03-06 21:34:12 +000011676 assert(E->getValueKind() == VK_RValue);
11677 assert(E->getObjectKind() == OK_Ordinary);
11678
11679 E->setType(DestType);
11680
11681 // Rebuild the sub-expression as the pointee (function) type.
11682 DestType = DestType->castAs<PointerType>()->getPointeeType();
11683
11684 ExprResult Result = Visit(E->getSubExpr());
11685 if (!Result.isUsable()) return ExprError();
11686
11687 E->setSubExpr(Result.take());
11688 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000011689 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanan12495112012-03-06 21:34:12 +000011690 assert(E->getValueKind() == VK_RValue);
11691 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000011692
Sean Callanan12495112012-03-06 21:34:12 +000011693 assert(isa<BlockPointerType>(E->getType()));
John McCall2979fe02011-04-12 00:42:48 +000011694
Sean Callanan12495112012-03-06 21:34:12 +000011695 E->setType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000011696
Sean Callanan12495112012-03-06 21:34:12 +000011697 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11698 DestType = S.Context.getLValueReferenceType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000011699
Sean Callanan12495112012-03-06 21:34:12 +000011700 ExprResult Result = Visit(E->getSubExpr());
11701 if (!Result.isUsable()) return ExprError();
11702
11703 E->setSubExpr(Result.take());
11704 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000011705 } else {
Sean Callanan12495112012-03-06 21:34:12 +000011706 llvm_unreachable("Unhandled cast type!");
11707 }
John McCall2d2e8702011-04-11 07:02:50 +000011708}
11709
Richard Trieu10162ab2011-09-09 03:59:41 +000011710ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11711 ExprValueKind ValueKind = VK_LValue;
11712 QualType Type = DestType;
John McCall2d2e8702011-04-11 07:02:50 +000011713
11714 // We know how to make this work for certain kinds of decls:
11715
11716 // - functions
Richard Trieu10162ab2011-09-09 03:59:41 +000011717 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11718 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11719 DestType = Ptr->getPointeeType();
11720 ExprResult Result = resolveDecl(E, VD);
11721 if (Result.isInvalid()) return ExprError();
11722 return S.ImpCastExprToType(Result.take(), Type,
John McCall9a877fe2011-08-10 04:12:23 +000011723 CK_FunctionToPointerDecay, VK_RValue);
11724 }
11725
Richard Trieu10162ab2011-09-09 03:59:41 +000011726 if (!Type->isFunctionType()) {
11727 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11728 << VD << E->getSourceRange();
John McCall9a877fe2011-08-10 04:12:23 +000011729 return ExprError();
11730 }
John McCall2d2e8702011-04-11 07:02:50 +000011731
Richard Trieu10162ab2011-09-09 03:59:41 +000011732 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11733 if (MD->isInstance()) {
11734 ValueKind = VK_RValue;
11735 Type = S.Context.BoundMemberTy;
John McCall4adb38c2011-04-27 00:36:17 +000011736 }
11737
John McCall2d2e8702011-04-11 07:02:50 +000011738 // Function references aren't l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011739 if (!S.getLangOpts().CPlusPlus)
Richard Trieu10162ab2011-09-09 03:59:41 +000011740 ValueKind = VK_RValue;
John McCall2d2e8702011-04-11 07:02:50 +000011741
11742 // - variables
Richard Trieu10162ab2011-09-09 03:59:41 +000011743 } else if (isa<VarDecl>(VD)) {
11744 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11745 Type = RefTy->getPointeeType();
11746 } else if (Type->isFunctionType()) {
11747 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11748 << VD << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011749 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011750 }
11751
11752 // - nothing else
11753 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000011754 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11755 << VD << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011756 return ExprError();
11757 }
11758
Richard Trieu10162ab2011-09-09 03:59:41 +000011759 VD->setType(DestType);
11760 E->setType(Type);
11761 E->setValueKind(ValueKind);
11762 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +000011763}
11764
John McCall31996342011-04-07 08:22:57 +000011765/// Check a cast of an unknown-any type. We intentionally only
11766/// trigger this for C-style casts.
Richard Trieuba63ce62011-09-09 01:45:06 +000011767ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11768 Expr *CastExpr, CastKind &CastKind,
11769 ExprValueKind &VK, CXXCastPath &Path) {
John McCall31996342011-04-07 08:22:57 +000011770 // Rewrite the casted expression from scratch.
Richard Trieuba63ce62011-09-09 01:45:06 +000011771 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCall39439732011-04-09 22:50:59 +000011772 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000011773
Richard Trieuba63ce62011-09-09 01:45:06 +000011774 CastExpr = result.take();
11775 VK = CastExpr->getValueKind();
11776 CastKind = CK_NoOp;
John McCall39439732011-04-09 22:50:59 +000011777
Richard Trieuba63ce62011-09-09 01:45:06 +000011778 return CastExpr;
John McCall31996342011-04-07 08:22:57 +000011779}
11780
Douglas Gregord8fb1e32011-12-01 01:37:36 +000011781ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11782 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11783}
11784
Richard Trieuba63ce62011-09-09 01:45:06 +000011785static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11786 Expr *orig = E;
John McCall2d2e8702011-04-11 07:02:50 +000011787 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000011788 while (true) {
Richard Trieuba63ce62011-09-09 01:45:06 +000011789 E = E->IgnoreParenImpCasts();
11790 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11791 E = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000011792 diagID = diag::err_uncasted_call_of_unknown_any;
11793 } else {
John McCall31996342011-04-07 08:22:57 +000011794 break;
John McCall2d2e8702011-04-11 07:02:50 +000011795 }
John McCall31996342011-04-07 08:22:57 +000011796 }
11797
John McCall2d2e8702011-04-11 07:02:50 +000011798 SourceLocation loc;
11799 NamedDecl *d;
Richard Trieuba63ce62011-09-09 01:45:06 +000011800 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011801 loc = ref->getLocation();
11802 d = ref->getDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011803 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011804 loc = mem->getMemberLoc();
11805 d = mem->getMemberDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011806 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011807 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidisa6011e22011-10-03 06:36:51 +000011808 loc = msg->getSelectorStartLoc();
John McCall2d2e8702011-04-11 07:02:50 +000011809 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000011810 if (!d) {
11811 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11812 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11813 << orig->getSourceRange();
11814 return ExprError();
11815 }
John McCall2d2e8702011-04-11 07:02:50 +000011816 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +000011817 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11818 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011819 return ExprError();
11820 }
11821
11822 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000011823
11824 // Never recoverable.
11825 return ExprError();
11826}
11827
John McCall36e7fe32010-10-12 00:20:44 +000011828/// Check for operands with placeholder types and complain if found.
11829/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000011830ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall4124c492011-10-17 18:40:02 +000011831 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11832 if (!placeholderType) return Owned(E);
11833
11834 switch (placeholderType->getKind()) {
John McCall36e7fe32010-10-12 00:20:44 +000011835
John McCall31996342011-04-07 08:22:57 +000011836 // Overloaded expressions.
John McCall4124c492011-10-17 18:40:02 +000011837 case BuiltinType::Overload: {
John McCall50a2c2c2011-10-11 23:14:30 +000011838 // Try to resolve a single function template specialization.
11839 // This is obligatory.
11840 ExprResult result = Owned(E);
11841 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11842 return result;
11843
11844 // If that failed, try to recover with a call.
11845 } else {
11846 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11847 /*complain*/ true);
11848 return result;
11849 }
11850 }
John McCall31996342011-04-07 08:22:57 +000011851
John McCall0009fcc2011-04-26 20:42:42 +000011852 // Bound member functions.
John McCall4124c492011-10-17 18:40:02 +000011853 case BuiltinType::BoundMember: {
John McCall50a2c2c2011-10-11 23:14:30 +000011854 ExprResult result = Owned(E);
11855 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11856 /*complain*/ true);
11857 return result;
John McCall4124c492011-10-17 18:40:02 +000011858 }
11859
11860 // ARC unbridged casts.
11861 case BuiltinType::ARCUnbridgedCast: {
11862 Expr *realCast = stripARCUnbridgedCast(E);
11863 diagnoseARCUnbridgedCast(realCast);
11864 return Owned(realCast);
11865 }
John McCall0009fcc2011-04-26 20:42:42 +000011866
John McCall31996342011-04-07 08:22:57 +000011867 // Expressions of unknown type.
John McCall4124c492011-10-17 18:40:02 +000011868 case BuiltinType::UnknownAny:
John McCall31996342011-04-07 08:22:57 +000011869 return diagnoseUnknownAnyExpr(*this, E);
11870
John McCall526ab472011-10-25 17:37:35 +000011871 // Pseudo-objects.
11872 case BuiltinType::PseudoObject:
11873 return checkPseudoObjectRValue(E);
11874
Eli Friedman34866c72012-08-31 00:14:07 +000011875 case BuiltinType::BuiltinFn:
11876 Diag(E->getLocStart(), diag::err_builtin_fn_use);
11877 return ExprError();
11878
John McCalle314e272011-10-18 21:02:43 +000011879 // Everything else should be impossible.
11880#define BUILTIN_TYPE(Id, SingletonId) \
11881 case BuiltinType::Id:
11882#define PLACEHOLDER_TYPE(Id, SingletonId)
11883#include "clang/AST/BuiltinTypes.def"
John McCall4124c492011-10-17 18:40:02 +000011884 break;
11885 }
11886
11887 llvm_unreachable("invalid placeholder type!");
John McCall36e7fe32010-10-12 00:20:44 +000011888}
Richard Trieu2c850c02011-04-21 21:44:26 +000011889
Richard Trieuba63ce62011-09-09 01:45:06 +000011890bool Sema::CheckCaseExpression(Expr *E) {
11891 if (E->isTypeDependent())
Richard Trieu2c850c02011-04-21 21:44:26 +000011892 return true;
Richard Trieuba63ce62011-09-09 01:45:06 +000011893 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11894 return E->getType()->isIntegralOrEnumerationType();
Richard Trieu2c850c02011-04-21 21:44:26 +000011895 return false;
11896}
Ted Kremeneke65b0862012-03-06 20:05:56 +000011897
11898/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11899ExprResult
11900Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11901 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11902 "Unknown Objective-C Boolean value!");
Fariborz Jahanianf2578572012-08-30 18:49:41 +000011903 QualType BoolT = Context.ObjCBuiltinBoolTy;
11904 if (!Context.getBOOLDecl()) {
11905 LookupResult Result(*this, &Context.Idents.get("BOOL"), SourceLocation(),
11906 Sema::LookupOrdinaryName);
11907 if (LookupName(Result, getCurScope())) {
11908 NamedDecl *ND = Result.getFoundDecl();
11909 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
11910 Context.setBOOLDecl(TD);
11911 }
11912 }
11913 if (Context.getBOOLDecl())
11914 BoolT = Context.getBOOLType();
Ted Kremeneke65b0862012-03-06 20:05:56 +000011915 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanianf2578572012-08-30 18:49:41 +000011916 BoolT, OpLoc));
Ted Kremeneke65b0862012-03-06 20:05:56 +000011917}