blob: 41985328bb769a1d3e3798c75dafb4a02271e23e [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
1428 // Just in case we're building an illegal pointer-to-member.
Richard Smithcaf33902011-10-10 18:28:20 +00001429 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1430 if (FD && FD->isBitField())
John McCall086a4642010-11-24 05:12:34 +00001431 E->setObjectKind(OK_BitField);
1432
1433 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001434}
1435
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001436/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001437/// possibly a list of template arguments.
1438///
1439/// If this produces template arguments, it is permitted to call
1440/// DecomposeTemplateName.
1441///
1442/// This actually loses a lot of source location information for
1443/// non-standard name kinds; we should consider preserving that in
1444/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001445void
1446Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1447 TemplateArgumentListInfo &Buffer,
1448 DeclarationNameInfo &NameInfo,
1449 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001450 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1451 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1452 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1453
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001454 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
John McCall10eae182009-11-30 22:42:35 +00001455 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001456 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001457
John McCall3e56fd42010-08-23 07:28:44 +00001458 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001459 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001460 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001461 TemplateArgs = &Buffer;
1462 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001463 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001464 TemplateArgs = 0;
1465 }
1466}
1467
John McCalld681c392009-12-16 08:11:27 +00001468/// Diagnose an empty lookup.
1469///
1470/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001471bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001472 CorrectionCandidateCallback &CCC,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001473 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001474 llvm::ArrayRef<Expr *> Args) {
John McCalld681c392009-12-16 08:11:27 +00001475 DeclarationName Name = R.getLookupName();
1476
John McCalld681c392009-12-16 08:11:27 +00001477 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001478 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001479 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1480 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001481 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001482 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001483 diagnostic_suggest = diag::err_undeclared_use_suggest;
1484 }
John McCalld681c392009-12-16 08:11:27 +00001485
Douglas Gregor598b08f2009-12-31 05:20:13 +00001486 // If the original lookup was an unqualified lookup, fake an
1487 // unqualified lookup. This is useful when (for example) the
1488 // original lookup would not have found something because it was a
1489 // dependent name.
David Blaikiec4c0e8a2012-05-28 01:26:45 +00001490 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1491 ? CurContext : 0;
Francois Pichetde232cb2011-11-25 01:10:54 +00001492 while (DC) {
John McCalld681c392009-12-16 08:11:27 +00001493 if (isa<CXXRecordDecl>(DC)) {
1494 LookupQualifiedName(R, DC);
1495
1496 if (!R.empty()) {
1497 // Don't give errors about ambiguities in this lookup.
1498 R.suppressDiagnostics();
1499
Francois Pichet857f9d62011-11-17 03:44:24 +00001500 // During a default argument instantiation the CurContext points
1501 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1502 // function parameter list, hence add an explicit check.
1503 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1504 ActiveTemplateInstantiations.back().Kind ==
1505 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCalld681c392009-12-16 08:11:27 +00001506 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1507 bool isInstance = CurMethod &&
1508 CurMethod->isInstance() &&
Francois Pichet857f9d62011-11-17 03:44:24 +00001509 DC == CurMethod->getParent() && !isDefaultArgument;
1510
John McCalld681c392009-12-16 08:11:27 +00001511
1512 // Give a code modification hint to insert 'this->'.
1513 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1514 // Actually quite difficult!
Nico Weberdf7dffb2012-06-20 20:21:42 +00001515 if (getLangOpts().MicrosoftMode)
1516 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001517 if (isInstance) {
Nico Weber3c10fb12012-06-22 16:39:39 +00001518 Diag(R.getNameLoc(), diagnostic) << Name
1519 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001520 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1521 CallsUndergoingInstantiation.back()->getCallee());
Nico Weber3c10fb12012-06-22 16:39:39 +00001522
1523
1524 CXXMethodDecl *DepMethod;
1525 if (CurMethod->getTemplatedKind() ==
1526 FunctionDecl::TK_FunctionTemplateSpecialization)
1527 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1528 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1529 else
1530 DepMethod = cast<CXXMethodDecl>(
1531 CurMethod->getInstantiatedFromMemberFunction());
1532 assert(DepMethod && "No template pattern found");
1533
1534 QualType DepThisType = DepMethod->getThisType(Context);
1535 CheckCXXThisCapture(R.getNameLoc());
1536 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1537 R.getNameLoc(), DepThisType, false);
1538 TemplateArgumentListInfo TList;
1539 if (ULE->hasExplicitTemplateArgs())
1540 ULE->copyTemplateArgumentsInto(TList);
1541
1542 CXXScopeSpec SS;
1543 SS.Adopt(ULE->getQualifierLoc());
1544 CXXDependentScopeMemberExpr *DepExpr =
1545 CXXDependentScopeMemberExpr::Create(
1546 Context, DepThis, DepThisType, true, SourceLocation(),
1547 SS.getWithLocInContext(Context),
1548 ULE->getTemplateKeywordLoc(), 0,
1549 R.getLookupNameInfo(),
1550 ULE->hasExplicitTemplateArgs() ? &TList : 0);
1551 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001552 } else {
John McCalld681c392009-12-16 08:11:27 +00001553 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001554 }
John McCalld681c392009-12-16 08:11:27 +00001555
1556 // Do we really want to note all of these?
1557 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1558 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1559
Francois Pichet857f9d62011-11-17 03:44:24 +00001560 // Return true if we are inside a default argument instantiation
1561 // and the found name refers to an instance member function, otherwise
1562 // the function calling DiagnoseEmptyLookup will try to create an
1563 // implicit member call and this is wrong for default argument.
1564 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1565 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1566 return true;
1567 }
1568
John McCalld681c392009-12-16 08:11:27 +00001569 // Tell the callee to try to recover.
1570 return false;
1571 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001572
1573 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001574 }
Francois Pichetde232cb2011-11-25 01:10:54 +00001575
1576 // In Microsoft mode, if we are performing lookup from within a friend
1577 // function definition declared at class scope then we must set
1578 // DC to the lexical parent to be able to search into the parent
1579 // class.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001580 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetde232cb2011-11-25 01:10:54 +00001581 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1582 DC->getLexicalParent()->isRecord())
1583 DC = DC->getLexicalParent();
1584 else
1585 DC = DC->getParent();
John McCalld681c392009-12-16 08:11:27 +00001586 }
1587
Douglas Gregor598b08f2009-12-31 05:20:13 +00001588 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001589 TypoCorrection Corrected;
1590 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001591 S, &SS, CCC))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001592 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1593 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001594 R.setLookupName(Corrected.getCorrection());
1595
Hans Wennborg38198de2011-07-12 08:45:31 +00001596 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001597 if (Corrected.isOverloaded()) {
1598 OverloadCandidateSet OCS(R.getNameLoc());
1599 OverloadCandidateSet::iterator Best;
1600 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1601 CDEnd = Corrected.end();
1602 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001603 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001604 dyn_cast<FunctionTemplateDecl>(*CD))
1605 AddTemplateOverloadCandidate(
1606 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001607 Args, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001608 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1609 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1610 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001611 Args, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001612 }
1613 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1614 case OR_Success:
1615 ND = Best->Function;
1616 break;
1617 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001618 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001619 }
1620 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001621 R.addDecl(ND);
1622 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001623 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001624 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1625 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001626 else
1627 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001628 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001629 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001630 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1631 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001632 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001633 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001634
1635 // Tell the callee to try to recover.
1636 return false;
1637 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001638
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001639 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001640 // FIXME: If we ended up with a typo for a type name or
1641 // Objective-C class name, we're in trouble because the parser
1642 // is in the wrong place to recover. Suggest the typo
1643 // correction, but don't make it a fix-it since we're not going
1644 // to recover well anyway.
1645 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001646 Diag(R.getNameLoc(), diagnostic_suggest)
1647 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001648 else
1649 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001650 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001651 << SS.getRange();
1652
1653 // Don't try to recover; it won't work.
1654 return true;
1655 }
1656 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001657 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001658 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001659 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001660 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001661 else
Douglas Gregor25363982010-01-01 00:15:04 +00001662 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001663 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001664 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001665 return true;
1666 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001667 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001668 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001669
1670 // Emit a special diagnostic for failed member lookups.
1671 // FIXME: computing the declaration context might fail here (?)
1672 if (!SS.isEmpty()) {
1673 Diag(R.getNameLoc(), diag::err_no_member)
1674 << Name << computeDeclContext(SS, false)
1675 << SS.getRange();
1676 return true;
1677 }
1678
John McCalld681c392009-12-16 08:11:27 +00001679 // Give up, we can't recover.
1680 Diag(R.getNameLoc(), diagnostic) << Name;
1681 return true;
1682}
1683
John McCalldadc5752010-08-24 06:29:42 +00001684ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001685 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001686 SourceLocation TemplateKWLoc,
John McCall24d18942010-08-24 22:52:39 +00001687 UnqualifiedId &Id,
1688 bool HasTrailingLParen,
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001689 bool IsAddressOfOperand,
1690 CorrectionCandidateCallback *CCC) {
Richard Trieuba63ce62011-09-09 01:45:06 +00001691 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCalle66edc12009-11-24 19:00:30 +00001692 "cannot be direct & operand and have a trailing lparen");
1693
1694 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001695 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001696
John McCall10eae182009-11-30 22:42:35 +00001697 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001698
1699 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001700 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001701 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001702 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001703
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001704 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001705 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001706 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001707
John McCalle66edc12009-11-24 19:00:30 +00001708 // C++ [temp.dep.expr]p3:
1709 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001710 // -- an identifier that was declared with a dependent type,
1711 // (note: handled after lookup)
1712 // -- a template-id that is dependent,
1713 // (note: handled in BuildTemplateIdExpr)
1714 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001715 // -- a nested-name-specifier that contains a class-name that
1716 // names a dependent type.
1717 // Determine whether this is a member of an unknown specialization;
1718 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001719 bool DependentID = false;
1720 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1721 Name.getCXXNameType()->isDependentType()) {
1722 DependentID = true;
1723 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001724 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001725 if (RequireCompleteDeclContext(SS, DC))
1726 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001727 } else {
1728 DependentID = true;
1729 }
1730 }
1731
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001732 if (DependentID)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001733 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1734 IsAddressOfOperand, TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001735
John McCalle66edc12009-11-24 19:00:30 +00001736 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001737 LookupResult R(*this, NameInfo,
1738 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1739 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001740 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001741 // Lookup the template name again to correctly establish the context in
1742 // which it was found. This is really unfortunate as we already did the
1743 // lookup to determine that it was a template name in the first place. If
1744 // this becomes a performance hit, we can work harder to preserve those
1745 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001746 bool MemberOfUnknownSpecialization;
1747 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1748 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001749
1750 if (MemberOfUnknownSpecialization ||
1751 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001752 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1753 IsAddressOfOperand, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001754 } else {
Benjamin Kramer46921442012-01-20 14:57:34 +00001755 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001756 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001757
Douglas Gregora5226932011-02-04 13:35:07 +00001758 // If the result might be in a dependent base class, this is a dependent
1759 // id-expression.
1760 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001761 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1762 IsAddressOfOperand, TemplateArgs);
1763
John McCalle66edc12009-11-24 19:00:30 +00001764 // If this reference is in an Objective-C method, then we need to do
1765 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001766 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001767 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001768 if (E.isInvalid())
1769 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001770
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001771 if (Expr *Ex = E.takeAs<Expr>())
1772 return Owned(Ex);
Steve Naroffebf4cb42008-06-02 23:03:37 +00001773 }
Chris Lattner59a25942008-03-31 00:36:02 +00001774 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001775
John McCalle66edc12009-11-24 19:00:30 +00001776 if (R.isAmbiguous())
1777 return ExprError();
1778
Douglas Gregor171c45a2009-02-18 21:56:37 +00001779 // Determine whether this name might be a candidate for
1780 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001781 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001782
John McCalle66edc12009-11-24 19:00:30 +00001783 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001784 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001785 // in C90, extension in C99, forbidden in C++).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001786 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
John McCalle66edc12009-11-24 19:00:30 +00001787 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1788 if (D) R.addDecl(D);
1789 }
1790
1791 // If this name wasn't predeclared and if this is not a function
1792 // call, diagnose the problem.
1793 if (R.empty()) {
Francois Pichetd8e4e412011-09-24 10:38:05 +00001794
1795 // In Microsoft mode, if we are inside a template class member function
1796 // and we can't resolve an identifier then assume the identifier is type
1797 // dependent. The goal is to postpone name lookup to instantiation time
1798 // to be able to search into type dependent base classes.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001799 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetd8e4e412011-09-24 10:38:05 +00001800 isa<CXXMethodDecl>(CurContext))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001801 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1802 IsAddressOfOperand, TemplateArgs);
Francois Pichetd8e4e412011-09-24 10:38:05 +00001803
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001804 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001805 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCalld681c392009-12-16 08:11:27 +00001806 return ExprError();
1807
1808 assert(!R.empty() &&
1809 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001810
1811 // If we found an Objective-C instance variable, let
1812 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001813 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001814 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1815 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001816 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanian44653702011-09-23 23:11:38 +00001817 // In a hopelessly buggy code, Objective-C instance variable
1818 // lookup fails and no expression will be built to reference it.
1819 if (!E.isInvalid() && !E.get())
1820 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001821 return E;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001822 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001823 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001824 }
Mike Stump11289f42009-09-09 15:08:12 +00001825
John McCalle66edc12009-11-24 19:00:30 +00001826 // This is guaranteed from this point on.
1827 assert(!R.empty() || ADL);
1828
John McCall2d74de92009-12-01 22:10:20 +00001829 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001830 // C++ [class.mfct.non-static]p3:
1831 // When an id-expression that is not part of a class member access
1832 // syntax and not used to form a pointer to member is used in the
1833 // body of a non-static member function of class X, if name lookup
1834 // resolves the name in the id-expression to a non-static non-type
1835 // member of some class C, the id-expression is transformed into a
1836 // class member access expression using (*this) as the
1837 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001838 //
1839 // But we don't actually need to do this for '&' operands if R
1840 // resolved to a function or overloaded function set, because the
1841 // expression is ill-formed if it actually works out to be a
1842 // non-static member function:
1843 //
1844 // C++ [expr.ref]p4:
1845 // Otherwise, if E1.E2 refers to a non-static member function. . .
1846 // [t]he expression can be used only as the left-hand operand of a
1847 // member function call.
1848 //
1849 // There are other safeguards against such uses, but it's important
1850 // to get this right here so that we don't end up making a
1851 // spuriously dependent expression if we're inside a dependent
1852 // instance method.
John McCall57500772009-12-16 12:17:52 +00001853 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001854 bool MightBeImplicitMember;
Richard Trieuba63ce62011-09-09 01:45:06 +00001855 if (!IsAddressOfOperand)
John McCall8d08b9b2010-08-27 09:08:28 +00001856 MightBeImplicitMember = true;
1857 else if (!SS.isEmpty())
1858 MightBeImplicitMember = false;
1859 else if (R.isOverloadedResult())
1860 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001861 else if (R.isUnresolvableResult())
1862 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001863 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001864 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1865 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001866
1867 if (MightBeImplicitMember)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001868 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1869 R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001870 }
1871
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001872 if (TemplateArgs || TemplateKWLoc.isValid())
1873 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001874
John McCalle66edc12009-11-24 19:00:30 +00001875 return BuildDeclarationNameExpr(SS, R, ADL);
1876}
1877
John McCall10eae182009-11-30 22:42:35 +00001878/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1879/// declaration name, generally during template instantiation.
1880/// There's a large number of things which don't need to be done along
1881/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001882ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001883Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001884 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001885 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001886 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001887 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1888 NameInfo, /*TemplateArgs=*/0);
John McCalle66edc12009-11-24 19:00:30 +00001889
John McCall0b66eb32010-05-01 00:40:08 +00001890 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001891 return ExprError();
1892
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001893 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001894 LookupQualifiedName(R, DC);
1895
1896 if (R.isAmbiguous())
1897 return ExprError();
1898
1899 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001900 Diag(NameInfo.getLoc(), diag::err_no_member)
1901 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001902 return ExprError();
1903 }
1904
1905 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1906}
1907
1908/// LookupInObjCMethod - The parser has read a name in, and Sema has
1909/// detected that we're currently inside an ObjC method. Perform some
1910/// additional lookup.
1911///
1912/// Ideally, most of this would be done by lookup, but there's
1913/// actually quite a lot of extra work involved.
1914///
1915/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001916ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001917Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001918 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001919 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001920 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001921
John McCalle66edc12009-11-24 19:00:30 +00001922 // There are two cases to handle here. 1) scoped lookup could have failed,
1923 // in which case we should look for an ivar. 2) scoped lookup could have
1924 // found a decl, but that decl is outside the current instance method (i.e.
1925 // a global variable). In these two cases, we do a lookup for an ivar with
1926 // this name, if the lookup sucedes, we replace it our current decl.
1927
1928 // If we're in a class method, we don't normally want to look for
1929 // ivars. But if we don't find anything else, and there's an
1930 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001931 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001932
1933 bool LookForIvars;
1934 if (Lookup.empty())
1935 LookForIvars = true;
1936 else if (IsClassMethod)
1937 LookForIvars = false;
1938 else
1939 LookForIvars = (Lookup.isSingleResult() &&
1940 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001941 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001942 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001943 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001944 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis4e8b1362011-10-19 02:25:16 +00001945 ObjCIvarDecl *IV = 0;
1946 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCalle66edc12009-11-24 19:00:30 +00001947 // Diagnose using an ivar in a class method.
1948 if (IsClassMethod)
1949 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1950 << IV->getDeclName());
1951
1952 // If we're referencing an invalid decl, just return this as a silent
1953 // error node. The error diagnostic was already emitted on the decl.
1954 if (IV->isInvalidDecl())
1955 return ExprError();
1956
1957 // Check if referencing a field with __attribute__((deprecated)).
1958 if (DiagnoseUseOfDecl(IV, Loc))
1959 return ExprError();
1960
1961 // Diagnose the use of an ivar outside of the declaring class.
1962 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001963 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001964 !getLangOpts().DebuggerSupport)
John McCalle66edc12009-11-24 19:00:30 +00001965 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1966
1967 // FIXME: This should use a new expr for a direct reference, don't
1968 // turn this into Self->ivar, just return a BareIVarExpr or something.
1969 IdentifierInfo &II = Context.Idents.get("self");
1970 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001971 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001972 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001973 CXXScopeSpec SelfScopeSpec;
Abramo Bagnara7945c982012-01-27 09:46:47 +00001974 SourceLocation TemplateKWLoc;
1975 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001976 SelfName, false, false);
1977 if (SelfExpr.isInvalid())
1978 return ExprError();
1979
John Wiegley01296292011-04-08 18:41:53 +00001980 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1981 if (SelfExpr.isInvalid())
1982 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001983
Eli Friedmanfa0df832012-02-02 03:46:19 +00001984 MarkAnyDeclReferenced(Loc, IV);
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00001985
1986 ObjCMethodFamily MF = CurMethod->getMethodFamily();
1987 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize)
1988 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
John McCalle66edc12009-11-24 19:00:30 +00001989 return Owned(new (Context)
1990 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001991 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001992 }
Chris Lattner87313662010-04-12 05:10:17 +00001993 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001994 // We should warn if a local variable hides an ivar.
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00001995 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
1996 ObjCInterfaceDecl *ClassDeclared;
1997 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1998 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor0b144e12011-12-15 00:29:59 +00001999 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00002000 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2001 }
John McCalle66edc12009-11-24 19:00:30 +00002002 }
Fariborz Jahanian028b9e12011-12-20 22:21:08 +00002003 } else if (Lookup.isSingleResult() &&
2004 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2005 // If accessing a stand-alone ivar in a class method, this is an error.
2006 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2007 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2008 << IV->getDeclName());
John McCalle66edc12009-11-24 19:00:30 +00002009 }
2010
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002011 if (Lookup.empty() && II && AllowBuiltinCreation) {
2012 // FIXME. Consolidate this with similar code in LookupName.
2013 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002014 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002015 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2016 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2017 S, Lookup.isForRedeclaration(),
2018 Lookup.getNameLoc());
2019 if (D) Lookup.addDecl(D);
2020 }
2021 }
2022 }
John McCalle66edc12009-11-24 19:00:30 +00002023 // Sentinel value saying that we didn't do anything special.
2024 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00002025}
John McCalld14a8642009-11-21 08:51:07 +00002026
John McCall16df1e52010-03-30 21:47:33 +00002027/// \brief Cast a base object to a member's actual type.
2028///
2029/// Logically this happens in three phases:
2030///
2031/// * First we cast from the base type to the naming class.
2032/// The naming class is the class into which we were looking
2033/// when we found the member; it's the qualifier type if a
2034/// qualifier was provided, and otherwise it's the base type.
2035///
2036/// * Next we cast from the naming class to the declaring class.
2037/// If the member we found was brought into a class's scope by
2038/// a using declaration, this is that class; otherwise it's
2039/// the class declaring the member.
2040///
2041/// * Finally we cast from the declaring class to the "true"
2042/// declaring class of the member. This conversion does not
2043/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00002044ExprResult
2045Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002046 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002047 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002048 NamedDecl *Member) {
2049 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2050 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00002051 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002052
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002053 QualType DestRecordType;
2054 QualType DestType;
2055 QualType FromRecordType;
2056 QualType FromType = From->getType();
2057 bool PointerConversions = false;
2058 if (isa<FieldDecl>(Member)) {
2059 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002060
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002061 if (FromType->getAs<PointerType>()) {
2062 DestType = Context.getPointerType(DestRecordType);
2063 FromRecordType = FromType->getPointeeType();
2064 PointerConversions = true;
2065 } else {
2066 DestType = DestRecordType;
2067 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002068 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002069 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2070 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00002071 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002072
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002073 DestType = Method->getThisType(Context);
2074 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002075
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002076 if (FromType->getAs<PointerType>()) {
2077 FromRecordType = FromType->getPointeeType();
2078 PointerConversions = true;
2079 } else {
2080 FromRecordType = FromType;
2081 DestType = DestRecordType;
2082 }
2083 } else {
2084 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00002085 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002086 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002087
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002088 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00002089 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002090
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002091 // If the unqualified types are the same, no conversion is necessary.
2092 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002093 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002094
John McCall16df1e52010-03-30 21:47:33 +00002095 SourceRange FromRange = From->getSourceRange();
2096 SourceLocation FromLoc = FromRange.getBegin();
2097
Eli Friedmanbe4b3632011-09-27 21:58:52 +00002098 ExprValueKind VK = From->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002099
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002100 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002101 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002102 // class name.
2103 //
2104 // If the member was a qualified name and the qualified referred to a
2105 // specific base subobject type, we'll cast to that intermediate type
2106 // first and then to the object in which the member is declared. That allows
2107 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2108 //
2109 // class Base { public: int x; };
2110 // class Derived1 : public Base { };
2111 // class Derived2 : public Base { };
2112 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2113 //
2114 // void VeryDerived::f() {
2115 // x = 17; // error: ambiguous base subobjects
2116 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2117 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002118 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002119 QualType QType = QualType(Qualifier->getAsType(), 0);
2120 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2121 assert(QType->isRecordType() && "lookup done with non-record type");
2122
2123 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2124
2125 // In C++98, the qualifier type doesn't actually have to be a base
2126 // type of the object type, in which case we just ignore it.
2127 // Otherwise build the appropriate casts.
2128 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002129 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002130 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002131 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002132 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002133
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002134 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002135 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002136 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2137 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002138
2139 FromType = QType;
2140 FromRecordType = QRecordType;
2141
2142 // If the qualifier type was the same as the destination type,
2143 // we're done.
2144 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002145 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002146 }
2147 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002148
John McCall16df1e52010-03-30 21:47:33 +00002149 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002150
John McCall16df1e52010-03-30 21:47:33 +00002151 // If we actually found the member through a using declaration, cast
2152 // down to the using declaration's type.
2153 //
2154 // Pointer equality is fine here because only one declaration of a
2155 // class ever has member declarations.
2156 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2157 assert(isa<UsingShadowDecl>(FoundDecl));
2158 QualType URecordType = Context.getTypeDeclType(
2159 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2160
2161 // We only need to do this if the naming-class to declaring-class
2162 // conversion is non-trivial.
2163 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2164 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002165 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002166 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002167 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002168 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002169
John McCall16df1e52010-03-30 21:47:33 +00002170 QualType UType = URecordType;
2171 if (PointerConversions)
2172 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002173 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2174 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002175 FromType = UType;
2176 FromRecordType = URecordType;
2177 }
2178
2179 // We don't do access control for the conversion from the
2180 // declaring class to the true declaring class.
2181 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002182 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002183
John McCallcf142162010-08-07 06:22:56 +00002184 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002185 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2186 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002187 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002188 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002189
John Wiegley01296292011-04-08 18:41:53 +00002190 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2191 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002192}
Douglas Gregor3256d042009-06-30 15:47:41 +00002193
John McCalle66edc12009-11-24 19:00:30 +00002194bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002195 const LookupResult &R,
2196 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002197 // Only when used directly as the postfix-expression of a call.
2198 if (!HasTrailingLParen)
2199 return false;
2200
2201 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002202 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002203 return false;
2204
2205 // Only in C++ or ObjC++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002206 if (!getLangOpts().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002207 return false;
2208
2209 // Turn off ADL when we find certain kinds of declarations during
2210 // normal lookup:
2211 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2212 NamedDecl *D = *I;
2213
2214 // C++0x [basic.lookup.argdep]p3:
2215 // -- a declaration of a class member
2216 // Since using decls preserve this property, we check this on the
2217 // original decl.
John McCall57500772009-12-16 12:17:52 +00002218 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002219 return false;
2220
2221 // C++0x [basic.lookup.argdep]p3:
2222 // -- a block-scope function declaration that is not a
2223 // using-declaration
2224 // NOTE: we also trigger this for function templates (in fact, we
2225 // don't check the decl type at all, since all other decl types
2226 // turn off ADL anyway).
2227 if (isa<UsingShadowDecl>(D))
2228 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2229 else if (D->getDeclContext()->isFunctionOrMethod())
2230 return false;
2231
2232 // C++0x [basic.lookup.argdep]p3:
2233 // -- a declaration that is neither a function or a function
2234 // template
2235 // And also for builtin functions.
2236 if (isa<FunctionDecl>(D)) {
2237 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2238
2239 // But also builtin functions.
2240 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2241 return false;
2242 } else if (!isa<FunctionTemplateDecl>(D))
2243 return false;
2244 }
2245
2246 return true;
2247}
2248
2249
John McCalld14a8642009-11-21 08:51:07 +00002250/// Diagnoses obvious problems with the use of the given declaration
2251/// as an expression. This is only actually called for lookups that
2252/// were not overloaded, and it doesn't promise that the declaration
2253/// will in fact be used.
2254static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002255 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002256 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2257 return true;
2258 }
2259
2260 if (isa<ObjCInterfaceDecl>(D)) {
2261 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2262 return true;
2263 }
2264
2265 if (isa<NamespaceDecl>(D)) {
2266 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2267 return true;
2268 }
2269
2270 return false;
2271}
2272
John McCalldadc5752010-08-24 06:29:42 +00002273ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002274Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002275 LookupResult &R,
2276 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002277 // If this is a single, fully-resolved result and we don't need ADL,
2278 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002279 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002280 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2281 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002282
2283 // We only need to check the declaration if there's exactly one
2284 // result, because in the overloaded case the results can only be
2285 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002286 if (R.isSingleResult() &&
2287 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002288 return ExprError();
2289
John McCall58cc69d2010-01-27 01:50:18 +00002290 // Otherwise, just build an unresolved lookup expression. Suppress
2291 // any lookup-related diagnostics; we'll hash these out later, when
2292 // we've picked a target.
2293 R.suppressDiagnostics();
2294
John McCalld14a8642009-11-21 08:51:07 +00002295 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002296 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002297 SS.getWithLocInContext(Context),
2298 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002299 NeedsADL, R.isOverloadedResult(),
2300 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002301
2302 return Owned(ULE);
2303}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002304
John McCalld14a8642009-11-21 08:51:07 +00002305/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002306ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002307Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002308 const DeclarationNameInfo &NameInfo,
2309 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002310 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002311 assert(!isa<FunctionTemplateDecl>(D) &&
2312 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002313
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002314 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002315 if (CheckDeclInExpr(*this, Loc, D))
2316 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002317
Douglas Gregore7488b92009-12-01 16:58:18 +00002318 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2319 // Specifically diagnose references to class templates that are missing
2320 // a template argument list.
2321 Diag(Loc, diag::err_template_decl_ref)
2322 << Template << SS.getRange();
2323 Diag(Template->getLocation(), diag::note_template_decl_here);
2324 return ExprError();
2325 }
2326
2327 // Make sure that we're referring to a value.
2328 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2329 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002330 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002331 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002332 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002333 return ExprError();
2334 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002335
Douglas Gregor171c45a2009-02-18 21:56:37 +00002336 // Check whether this declaration can be used. Note that we suppress
2337 // this check when we're going to perform argument-dependent lookup
2338 // on this function name, because this might not be the function
2339 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002340 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002341 return ExprError();
2342
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002343 // Only create DeclRefExpr's for valid Decl's.
2344 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002345 return ExprError();
2346
John McCallf3a88602011-02-03 08:15:49 +00002347 // Handle members of anonymous structs and unions. If we got here,
2348 // and the reference is to a class member indirect field, then this
2349 // must be the subject of a pointer-to-member expression.
2350 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2351 if (!indirectField->isCXXClassMember())
2352 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2353 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002354
Eli Friedman9bb33f52012-02-03 02:04:35 +00002355 {
John McCallf4cd4f92011-02-09 01:13:10 +00002356 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002357 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002358
2359 switch (D->getKind()) {
2360 // Ignore all the non-ValueDecl kinds.
2361#define ABSTRACT_DECL(kind)
2362#define VALUE(type, base)
2363#define DECL(type, base) \
2364 case Decl::type:
2365#include "clang/AST/DeclNodes.inc"
2366 llvm_unreachable("invalid value decl kind");
John McCallf4cd4f92011-02-09 01:13:10 +00002367
2368 // These shouldn't make it here.
2369 case Decl::ObjCAtDefsField:
2370 case Decl::ObjCIvar:
2371 llvm_unreachable("forming non-member reference to ivar?");
John McCallf4cd4f92011-02-09 01:13:10 +00002372
2373 // Enum constants are always r-values and never references.
2374 // Unresolved using declarations are dependent.
2375 case Decl::EnumConstant:
2376 case Decl::UnresolvedUsingValue:
2377 valueKind = VK_RValue;
2378 break;
2379
2380 // Fields and indirect fields that got here must be for
2381 // pointer-to-member expressions; we just call them l-values for
2382 // internal consistency, because this subexpression doesn't really
2383 // exist in the high-level semantics.
2384 case Decl::Field:
2385 case Decl::IndirectField:
David Blaikiebbafb8a2012-03-11 07:00:24 +00002386 assert(getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002387 "building reference to field in C?");
2388
2389 // These can't have reference type in well-formed programs, but
2390 // for internal consistency we do this anyway.
2391 type = type.getNonReferenceType();
2392 valueKind = VK_LValue;
2393 break;
2394
2395 // Non-type template parameters are either l-values or r-values
2396 // depending on the type.
2397 case Decl::NonTypeTemplateParm: {
2398 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2399 type = reftype->getPointeeType();
2400 valueKind = VK_LValue; // even if the parameter is an r-value reference
2401 break;
2402 }
2403
2404 // For non-references, we need to strip qualifiers just in case
2405 // the template parameter was declared as 'const int' or whatever.
2406 valueKind = VK_RValue;
2407 type = type.getUnqualifiedType();
2408 break;
2409 }
2410
2411 case Decl::Var:
2412 // In C, "extern void blah;" is valid and is an r-value.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002413 if (!getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002414 !type.hasQualifiers() &&
2415 type->isVoidType()) {
2416 valueKind = VK_RValue;
2417 break;
2418 }
2419 // fallthrough
2420
2421 case Decl::ImplicitParam:
Douglas Gregor812d8f62012-02-18 05:51:20 +00002422 case Decl::ParmVar: {
John McCallf4cd4f92011-02-09 01:13:10 +00002423 // These are always l-values.
2424 valueKind = VK_LValue;
2425 type = type.getNonReferenceType();
Eli Friedman9bb33f52012-02-03 02:04:35 +00002426
Douglas Gregor812d8f62012-02-18 05:51:20 +00002427 // FIXME: Does the addition of const really only apply in
2428 // potentially-evaluated contexts? Since the variable isn't actually
2429 // captured in an unevaluated context, it seems that the answer is no.
David Blaikie131fcb42012-08-06 22:47:24 +00002430 if (!isUnevaluatedContext()) {
Douglas Gregor812d8f62012-02-18 05:51:20 +00002431 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2432 if (!CapturedType.isNull())
2433 type = CapturedType;
2434 }
2435
John McCallf4cd4f92011-02-09 01:13:10 +00002436 break;
Douglas Gregor812d8f62012-02-18 05:51:20 +00002437 }
2438
John McCallf4cd4f92011-02-09 01:13:10 +00002439 case Decl::Function: {
Eli Friedman34866c72012-08-31 00:14:07 +00002440 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2441 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2442 type = Context.BuiltinFnTy;
2443 valueKind = VK_RValue;
2444 break;
2445 }
2446 }
2447
John McCall2979fe02011-04-12 00:42:48 +00002448 const FunctionType *fty = type->castAs<FunctionType>();
2449
2450 // If we're referring to a function with an __unknown_anytype
2451 // result type, make the entire expression __unknown_anytype.
2452 if (fty->getResultType() == Context.UnknownAnyTy) {
2453 type = Context.UnknownAnyTy;
2454 valueKind = VK_RValue;
2455 break;
2456 }
2457
John McCallf4cd4f92011-02-09 01:13:10 +00002458 // Functions are l-values in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002459 if (getLangOpts().CPlusPlus) {
John McCallf4cd4f92011-02-09 01:13:10 +00002460 valueKind = VK_LValue;
2461 break;
2462 }
2463
2464 // C99 DR 316 says that, if a function type comes from a
2465 // function definition (without a prototype), that type is only
2466 // used for checking compatibility. Therefore, when referencing
2467 // the function, we pretend that we don't have the full function
2468 // type.
John McCall2979fe02011-04-12 00:42:48 +00002469 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2470 isa<FunctionProtoType>(fty))
2471 type = Context.getFunctionNoProtoType(fty->getResultType(),
2472 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002473
2474 // Functions are r-values in C.
2475 valueKind = VK_RValue;
2476 break;
2477 }
2478
2479 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002480 // If we're referring to a method with an __unknown_anytype
2481 // result type, make the entire expression __unknown_anytype.
2482 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002483 if (const FunctionProtoType *proto
2484 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002485 if (proto->getResultType() == Context.UnknownAnyTy) {
2486 type = Context.UnknownAnyTy;
2487 valueKind = VK_RValue;
2488 break;
2489 }
2490
John McCallf4cd4f92011-02-09 01:13:10 +00002491 // C++ methods are l-values if static, r-values if non-static.
2492 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2493 valueKind = VK_LValue;
2494 break;
2495 }
2496 // fallthrough
2497
2498 case Decl::CXXConversion:
2499 case Decl::CXXDestructor:
2500 case Decl::CXXConstructor:
2501 valueKind = VK_RValue;
2502 break;
2503 }
2504
2505 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2506 }
Chris Lattner17ed4872006-11-20 04:58:19 +00002507}
Chris Lattnere168f762006-11-10 05:29:30 +00002508
John McCall2979fe02011-04-12 00:42:48 +00002509ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002510 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002511
Chris Lattnere168f762006-11-10 05:29:30 +00002512 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002513 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002514 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2515 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
Nico Weber3a691a32012-06-23 02:07:59 +00002516 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
Chris Lattner6307f192008-08-10 01:53:14 +00002517 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002518 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002519
Chris Lattnera81a0272008-01-12 08:14:25 +00002520 // Pre-defined identifiers are of type char[x], where x is the length of the
2521 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002522
Anders Carlsson2fb08242009-09-08 18:24:21 +00002523 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002524 if (!currentDecl && getCurBlock())
2525 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002526 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002527 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002528 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002529 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002530
Anders Carlsson0b209a82009-09-11 01:22:35 +00002531 QualType ResTy;
2532 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2533 ResTy = Context.DependentTy;
2534 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002535 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002536
Anders Carlsson0b209a82009-09-11 01:22:35 +00002537 llvm::APInt LengthI(32, Length + 1);
Nico Weber3052abd2012-06-29 16:39:58 +00002538 if (IT == PredefinedExpr::LFunction)
Nico Weber3a691a32012-06-23 02:07:59 +00002539 ResTy = Context.WCharTy.withConst();
2540 else
2541 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002542 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2543 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002544 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002545}
2546
Richard Smithbcc22fc2012-03-09 08:00:36 +00002547ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002548 SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002549 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002550 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002551 if (Invalid)
2552 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002553
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002554 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002555 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002556 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002557 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002558
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002559 QualType Ty;
Seth Cantrell02f86052012-01-18 12:27:06 +00002560 if (Literal.isWide())
2561 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002562 else if (Literal.isUTF16())
Seth Cantrell02f86052012-01-18 12:27:06 +00002563 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002564 else if (Literal.isUTF32())
Seth Cantrell02f86052012-01-18 12:27:06 +00002565 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002566 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell02f86052012-01-18 12:27:06 +00002567 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002568 else
2569 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002570
Douglas Gregorfb65e592011-07-27 05:40:30 +00002571 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2572 if (Literal.isWide())
2573 Kind = CharacterLiteral::Wide;
2574 else if (Literal.isUTF16())
2575 Kind = CharacterLiteral::UTF16;
2576 else if (Literal.isUTF32())
2577 Kind = CharacterLiteral::UTF32;
2578
Richard Smith75b67d62012-03-08 01:34:56 +00002579 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2580 Tok.getLocation());
2581
2582 if (Literal.getUDSuffix().empty())
2583 return Owned(Lit);
2584
2585 // We're building a user-defined literal.
2586 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2587 SourceLocation UDSuffixLoc =
2588 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2589
Richard Smithbcc22fc2012-03-09 08:00:36 +00002590 // Make sure we're allowed user-defined literals here.
2591 if (!UDLScope)
2592 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2593
Richard Smith75b67d62012-03-08 01:34:56 +00002594 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2595 // operator "" X (ch)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002596 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2597 llvm::makeArrayRef(&Lit, 1),
2598 Tok.getLocation());
Steve Naroffae4143e2007-04-26 20:39:23 +00002599}
2600
Ted Kremeneke65b0862012-03-06 20:05:56 +00002601ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2602 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2603 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2604 Context.IntTy, Loc));
2605}
2606
Richard Smith39570d002012-03-08 08:45:32 +00002607static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2608 QualType Ty, SourceLocation Loc) {
2609 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2610
2611 using llvm::APFloat;
2612 APFloat Val(Format);
2613
2614 APFloat::opStatus result = Literal.GetFloatValue(Val);
2615
2616 // Overflow is always an error, but underflow is only an error if
2617 // we underflowed to zero (APFloat reports denormals as underflow).
2618 if ((result & APFloat::opOverflow) ||
2619 ((result & APFloat::opUnderflow) && Val.isZero())) {
2620 unsigned diagnostic;
2621 SmallString<20> buffer;
2622 if (result & APFloat::opOverflow) {
2623 diagnostic = diag::warn_float_overflow;
2624 APFloat::getLargest(Format).toString(buffer);
2625 } else {
2626 diagnostic = diag::warn_float_underflow;
2627 APFloat::getSmallest(Format).toString(buffer);
2628 }
2629
2630 S.Diag(Loc, diagnostic)
2631 << Ty
2632 << StringRef(buffer.data(), buffer.size());
2633 }
2634
2635 bool isExact = (result == APFloat::opOK);
2636 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2637}
2638
Richard Smithbcc22fc2012-03-09 08:00:36 +00002639ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002640 // Fast path for a single digit (which is quite common). A single digit
Richard Smithbcc22fc2012-03-09 08:00:36 +00002641 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Steve Narofff2fb89e2007-03-13 20:29:44 +00002642 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002643 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002644 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Steve Narofff2fb89e2007-03-13 20:29:44 +00002645 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002646
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002647 SmallString<128> SpellingBuffer;
2648 // NumericLiteralParser wants to overread by one character. Add padding to
2649 // the buffer in case the token is copied to the buffer. If getSpelling()
2650 // returns a StringRef to the memory buffer, it should have a null char at
2651 // the EOF, so it is also safe.
2652 SpellingBuffer.resize(Tok.getLength() + 1);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002653
Chris Lattner67ca9252007-05-21 01:08:44 +00002654 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002655 bool Invalid = false;
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002656 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002657 if (Invalid)
2658 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002659
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002660 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002661 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002662 return ExprError();
2663
Richard Smith39570d002012-03-08 08:45:32 +00002664 if (Literal.hasUDSuffix()) {
2665 // We're building a user-defined literal.
2666 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2667 SourceLocation UDSuffixLoc =
2668 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2669
Richard Smithbcc22fc2012-03-09 08:00:36 +00002670 // Make sure we're allowed user-defined literals here.
2671 if (!UDLScope)
2672 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smith39570d002012-03-08 08:45:32 +00002673
Richard Smithbcc22fc2012-03-09 08:00:36 +00002674 QualType CookedTy;
Richard Smith39570d002012-03-08 08:45:32 +00002675 if (Literal.isFloatingLiteral()) {
2676 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2677 // long double, the literal is treated as a call of the form
2678 // operator "" X (f L)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002679 CookedTy = Context.LongDoubleTy;
Richard Smith39570d002012-03-08 08:45:32 +00002680 } else {
2681 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2682 // unsigned long long, the literal is treated as a call of the form
2683 // operator "" X (n ULL)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002684 CookedTy = Context.UnsignedLongLongTy;
Richard Smith39570d002012-03-08 08:45:32 +00002685 }
2686
Richard Smithbcc22fc2012-03-09 08:00:36 +00002687 DeclarationName OpName =
2688 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2689 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2690 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2691
2692 // Perform literal operator lookup to determine if we're building a raw
2693 // literal or a cooked one.
2694 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2695 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2696 /*AllowRawAndTemplate*/true)) {
2697 case LOLR_Error:
2698 return ExprError();
2699
2700 case LOLR_Cooked: {
2701 Expr *Lit;
2702 if (Literal.isFloatingLiteral()) {
2703 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2704 } else {
2705 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2706 if (Literal.GetIntegerValue(ResultVal))
2707 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2708 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2709 Tok.getLocation());
2710 }
2711 return BuildLiteralOperatorCall(R, OpNameInfo,
2712 llvm::makeArrayRef(&Lit, 1),
2713 Tok.getLocation());
2714 }
2715
2716 case LOLR_Raw: {
2717 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2718 // literal is treated as a call of the form
2719 // operator "" X ("n")
2720 SourceLocation TokLoc = Tok.getLocation();
2721 unsigned Length = Literal.getUDSuffixOffset();
2722 QualType StrTy = Context.getConstantArrayType(
2723 Context.CharTy, llvm::APInt(32, Length + 1),
2724 ArrayType::Normal, 0);
2725 Expr *Lit = StringLiteral::Create(
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002726 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
Richard Smithbcc22fc2012-03-09 08:00:36 +00002727 /*Pascal*/false, StrTy, &TokLoc, 1);
2728 return BuildLiteralOperatorCall(R, OpNameInfo,
2729 llvm::makeArrayRef(&Lit, 1), TokLoc);
2730 }
2731
2732 case LOLR_Template:
2733 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2734 // template), L is treated as a call fo the form
2735 // operator "" X <'c1', 'c2', ... 'ck'>()
2736 // where n is the source character sequence c1 c2 ... ck.
2737 TemplateArgumentListInfo ExplicitArgs;
2738 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2739 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2740 llvm::APSInt Value(CharBits, CharIsUnsigned);
2741 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002742 Value = TokSpelling[I];
Benjamin Kramer6003ad52012-06-07 15:09:51 +00002743 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smithbcc22fc2012-03-09 08:00:36 +00002744 TemplateArgumentLocInfo ArgInfo;
2745 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2746 }
2747 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2748 Tok.getLocation(), &ExplicitArgs);
2749 }
2750
2751 llvm_unreachable("unexpected literal operator lookup result");
Richard Smith39570d002012-03-08 08:45:32 +00002752 }
2753
Chris Lattner1c20a172007-08-26 03:42:43 +00002754 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002755
Chris Lattner1c20a172007-08-26 03:42:43 +00002756 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002757 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002758 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002759 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002760 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002761 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002762 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002763 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002764
Richard Smith39570d002012-03-08 08:45:32 +00002765 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002766
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002767 if (Ty == Context.DoubleTy) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002768 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002769 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002770 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002771 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002772 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002773 }
2774 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002775 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002776 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002777 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002778 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002779
Dmitri Gribenko1cd23052012-09-24 18:19:21 +00002780 // 'long long' is a C99 or C++11 feature.
2781 if (!getLangOpts().C99 && Literal.isLongLong) {
2782 if (getLangOpts().CPlusPlus)
2783 Diag(Tok.getLocation(),
2784 getLangOpts().CPlusPlus0x ?
2785 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
2786 else
2787 Diag(Tok.getLocation(), diag::ext_c99_longlong);
2788 }
Neil Boothac582c52007-08-29 22:00:19 +00002789
Chris Lattner67ca9252007-05-21 01:08:44 +00002790 // Get the value in the widest-possible width.
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002791 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2792 // The microsoft literal suffix extensions support 128-bit literals, which
2793 // may be wider than [u]intmax_t.
2794 if (Literal.isMicrosoftInteger && MaxWidth < 128)
2795 MaxWidth = 128;
2796 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002797
Chris Lattner67ca9252007-05-21 01:08:44 +00002798 if (Literal.GetIntegerValue(ResultVal)) {
2799 // If this value didn't fit into uintmax_t, warn and force to ull.
2800 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002801 Ty = Context.UnsignedLongLongTy;
2802 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002803 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002804 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002805 // If this value fits into a ULL, try to figure out what else it fits into
2806 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002807
Chris Lattner67ca9252007-05-21 01:08:44 +00002808 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2809 // be an unsigned int.
2810 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2811
2812 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002813 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002814 if (!Literal.isLong && !Literal.isLongLong) {
2815 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00002816 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002817
Chris Lattner67ca9252007-05-21 01:08:44 +00002818 // Does it fit in a unsigned int?
2819 if (ResultVal.isIntN(IntSize)) {
2820 // Does it fit in a signed int?
2821 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002822 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002823 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002824 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002825 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002826 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002827 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002828
Chris Lattner67ca9252007-05-21 01:08:44 +00002829 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002830 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002831 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002832
Chris Lattner67ca9252007-05-21 01:08:44 +00002833 // Does it fit in a unsigned long?
2834 if (ResultVal.isIntN(LongSize)) {
2835 // Does it fit in a signed long?
2836 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002837 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002838 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002839 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002840 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002841 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002842 }
2843
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002844 // Check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002845 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002846 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002847
Chris Lattner67ca9252007-05-21 01:08:44 +00002848 // Does it fit in a unsigned long long?
2849 if (ResultVal.isIntN(LongLongSize)) {
2850 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002851 // To be compatible with MSVC, hex integer literals ending with the
2852 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002853 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00002854 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002855 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002856 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002857 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002858 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002859 }
2860 }
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002861
2862 // If it doesn't fit in unsigned long long, and we're using Microsoft
2863 // extensions, then its a 128-bit integer literal.
2864 if (Ty.isNull() && Literal.isMicrosoftInteger) {
2865 if (Literal.isUnsigned)
2866 Ty = Context.UnsignedInt128Ty;
2867 else
2868 Ty = Context.Int128Ty;
2869 Width = 128;
2870 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002871
Chris Lattner67ca9252007-05-21 01:08:44 +00002872 // If we still couldn't decide a type, we probably have something that
2873 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002874 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002875 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002876 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00002877 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002878 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002879
Chris Lattner55258cf2008-05-09 05:59:00 +00002880 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002881 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002882 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002883 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002884 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002885
Chris Lattner1c20a172007-08-26 03:42:43 +00002886 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2887 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002888 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002889 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002890
2891 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002892}
2893
Richard Trieuba63ce62011-09-09 01:45:06 +00002894ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002895 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002896 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002897}
2898
Chandler Carruth62da79c2011-05-26 08:53:12 +00002899static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2900 SourceLocation Loc,
2901 SourceRange ArgRange) {
2902 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2903 // scalar or vector data type argument..."
2904 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2905 // type (C99 6.2.5p18) or void.
2906 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2907 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2908 << T << ArgRange;
2909 return true;
2910 }
2911
2912 assert((T->isVoidType() || !T->isIncompleteType()) &&
2913 "Scalar types should always be complete");
2914 return false;
2915}
2916
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002917static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2918 SourceLocation Loc,
2919 SourceRange ArgRange,
2920 UnaryExprOrTypeTrait TraitKind) {
2921 // C99 6.5.3.4p1:
2922 if (T->isFunctionType()) {
2923 // alignof(function) is allowed as an extension.
2924 if (TraitKind == UETT_SizeOf)
2925 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2926 return false;
2927 }
2928
2929 // Allow sizeof(void)/alignof(void) as an extension.
2930 if (T->isVoidType()) {
2931 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2932 return false;
2933 }
2934
2935 return true;
2936}
2937
2938static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2939 SourceLocation Loc,
2940 SourceRange ArgRange,
2941 UnaryExprOrTypeTrait TraitKind) {
John McCallf2538342012-07-31 05:14:30 +00002942 // Reject sizeof(interface) and sizeof(interface<proto>) if the
2943 // runtime doesn't allow it.
2944 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002945 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2946 << T << (TraitKind == UETT_SizeOf)
2947 << ArgRange;
2948 return true;
2949 }
2950
2951 return false;
2952}
2953
Chandler Carruth14502c22011-05-26 08:53:10 +00002954/// \brief Check the constrains on expression operands to unary type expression
2955/// and type traits.
2956///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002957/// Completes any types necessary and validates the constraints on the operand
2958/// expression. The logic mostly mirrors the type-based overload, but may modify
2959/// the expression as it completes the type for that expression through template
2960/// instantiation, etc.
Richard Trieuba63ce62011-09-09 01:45:06 +00002961bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth14502c22011-05-26 08:53:10 +00002962 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002963 QualType ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002964
2965 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2966 // the result is the size of the referenced type."
2967 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2968 // result shall be the alignment of the referenced type."
2969 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2970 ExprTy = Ref->getPointeeType();
2971
2972 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002973 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2974 E->getSourceRange());
Chandler Carruth7c430c02011-05-27 01:33:31 +00002975
2976 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002977 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2978 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002979 return false;
2980
Richard Trieuba63ce62011-09-09 01:45:06 +00002981 if (RequireCompleteExprType(E,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002982 diag::err_sizeof_alignof_incomplete_type,
2983 ExprKind, E->getSourceRange()))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002984 return true;
2985
2986 // Completeing the expression's type may have changed it.
Richard Trieuba63ce62011-09-09 01:45:06 +00002987 ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002988 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2989 ExprTy = Ref->getPointeeType();
2990
Richard Trieuba63ce62011-09-09 01:45:06 +00002991 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2992 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002993 return true;
2994
Nico Weber0870deb2011-06-15 02:47:03 +00002995 if (ExprKind == UETT_SizeOf) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002996 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Weber0870deb2011-06-15 02:47:03 +00002997 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2998 QualType OType = PVD->getOriginalType();
2999 QualType Type = PVD->getType();
3000 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003001 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Weber0870deb2011-06-15 02:47:03 +00003002 << Type << OType;
3003 Diag(PVD->getLocation(), diag::note_declared_at);
3004 }
3005 }
3006 }
3007 }
3008
Chandler Carruth7c430c02011-05-27 01:33:31 +00003009 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00003010}
3011
3012/// \brief Check the constraints on operands to unary expression and type
3013/// traits.
3014///
3015/// This will complete any types necessary, and validate the various constraints
3016/// on those operands.
3017///
Steve Naroff71b59a92007-06-04 22:22:31 +00003018/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00003019/// C99 6.3.2.1p[2-4] all state:
3020/// Except when it is the operand of the sizeof operator ...
3021///
3022/// C++ [expr.sizeof]p4
3023/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3024/// standard conversions are not applied to the operand of sizeof.
3025///
3026/// This policy is followed for all of the unary trait expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00003027bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00003028 SourceLocation OpLoc,
3029 SourceRange ExprRange,
3030 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003031 if (ExprType->isDependentType())
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003032 return false;
3033
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003034 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3035 // the result is the size of the referenced type."
3036 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3037 // result shall be the alignment of the referenced type."
Richard Trieuba63ce62011-09-09 01:45:06 +00003038 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3039 ExprType = Ref->getPointeeType();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003040
Chandler Carruth62da79c2011-05-26 08:53:12 +00003041 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00003042 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003043
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003044 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00003045 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003046 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00003047 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003048
Richard Trieuba63ce62011-09-09 01:45:06 +00003049 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003050 diag::err_sizeof_alignof_incomplete_type,
3051 ExprKind, ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00003052 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003053
Richard Trieuba63ce62011-09-09 01:45:06 +00003054 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003055 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00003056 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003057
Chris Lattner62975a72009-04-24 00:30:45 +00003058 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00003059}
3060
Chandler Carruth14502c22011-05-26 08:53:10 +00003061static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00003062 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003063
Mike Stump11289f42009-09-09 15:08:12 +00003064 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00003065 if (isa<DeclRefExpr>(E))
3066 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003067
3068 // Cannot know anything else if the expression is dependent.
3069 if (E->isTypeDependent())
3070 return false;
3071
Douglas Gregor71235ec2009-05-02 02:18:30 +00003072 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003073 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3074 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003075 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00003076 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00003077
3078 // Alignment of a field access is always okay, so long as it isn't a
3079 // bit-field.
3080 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00003081 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003082 return false;
3083
Chandler Carruth14502c22011-05-26 08:53:10 +00003084 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003085}
3086
Chandler Carruth14502c22011-05-26 08:53:10 +00003087bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00003088 E = E->IgnoreParens();
3089
3090 // Cannot know anything else if the expression is dependent.
3091 if (E->isTypeDependent())
3092 return false;
3093
Chandler Carruth14502c22011-05-26 08:53:10 +00003094 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00003095}
3096
Douglas Gregor0950e412009-03-13 21:01:28 +00003097/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00003098ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003099Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3100 SourceLocation OpLoc,
3101 UnaryExprOrTypeTrait ExprKind,
3102 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00003103 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00003104 return ExprError();
3105
John McCallbcd03502009-12-07 02:54:59 +00003106 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00003107
Douglas Gregor0950e412009-03-13 21:01:28 +00003108 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00003109 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00003110 return ExprError();
3111
3112 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003113 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3114 Context.getSizeType(),
3115 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003116}
3117
3118/// \brief Build a sizeof or alignof expression given an expression
3119/// operand.
John McCalldadc5752010-08-24 06:29:42 +00003120ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00003121Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3122 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00003123 ExprResult PE = CheckPlaceholderExpr(E);
3124 if (PE.isInvalid())
3125 return ExprError();
3126
3127 E = PE.get();
3128
Douglas Gregor0950e412009-03-13 21:01:28 +00003129 // Verify that the operand is valid.
3130 bool isInvalid = false;
3131 if (E->isTypeDependent()) {
3132 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003133 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003134 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003135 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003136 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00003137 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00003138 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00003139 isInvalid = true;
3140 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00003141 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00003142 }
3143
3144 if (isInvalid)
3145 return ExprError();
3146
Eli Friedmane0afc982012-01-21 01:01:51 +00003147 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3148 PE = TranformToPotentiallyEvaluated(E);
3149 if (PE.isInvalid()) return ExprError();
3150 E = PE.take();
3151 }
3152
Douglas Gregor0950e412009-03-13 21:01:28 +00003153 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00003154 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00003155 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00003156 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003157}
3158
Peter Collingbournee190dee2011-03-11 19:24:49 +00003159/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3160/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00003161/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00003162ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003163Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003164 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00003165 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00003166 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003167 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00003168
Richard Trieuba63ce62011-09-09 01:45:06 +00003169 if (IsType) {
John McCallbcd03502009-12-07 02:54:59 +00003170 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00003171 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003172 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00003173 }
Sebastian Redl6f282892008-11-11 17:56:53 +00003174
Douglas Gregor0950e412009-03-13 21:01:28 +00003175 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00003176 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003177 return Result;
Chris Lattnere168f762006-11-10 05:29:30 +00003178}
3179
John Wiegley01296292011-04-08 18:41:53 +00003180static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003181 bool IsReal) {
John Wiegley01296292011-04-08 18:41:53 +00003182 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00003183 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00003184
John McCall34376a62010-12-04 03:47:34 +00003185 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00003186 if (V.get()->getObjectKind() != OK_Ordinary) {
3187 V = S.DefaultLvalueConversion(V.take());
3188 if (V.isInvalid())
3189 return QualType();
3190 }
John McCall34376a62010-12-04 03:47:34 +00003191
Chris Lattnere267f5d2007-08-26 05:39:26 +00003192 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00003193 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00003194 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00003195
Chris Lattnere267f5d2007-08-26 05:39:26 +00003196 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00003197 if (V.get()->getType()->isArithmeticType())
3198 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003199
John McCall36226622010-10-12 02:09:17 +00003200 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00003201 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00003202 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003203 if (PR.get() != V.get()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003204 V = PR;
Richard Trieuba63ce62011-09-09 01:45:06 +00003205 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall36226622010-10-12 02:09:17 +00003206 }
3207
Chris Lattnere267f5d2007-08-26 05:39:26 +00003208 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00003209 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuba63ce62011-09-09 01:45:06 +00003210 << (IsReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00003211 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00003212}
3213
3214
Chris Lattnere168f762006-11-10 05:29:30 +00003215
John McCalldadc5752010-08-24 06:29:42 +00003216ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003217Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003218 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00003219 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00003220 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003221 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003222 case tok::plusplus: Opc = UO_PostInc; break;
3223 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003224 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003225
Sebastian Redla9351792012-02-11 23:51:47 +00003226 // Since this might is a postfix expression, get rid of ParenListExprs.
3227 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3228 if (Result.isInvalid()) return ExprError();
3229 Input = Result.take();
3230
John McCallb268a282010-08-23 23:25:46 +00003231 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003232}
3233
John McCallf2538342012-07-31 05:14:30 +00003234/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3235///
3236/// \return true on error
3237static bool checkArithmeticOnObjCPointer(Sema &S,
3238 SourceLocation opLoc,
3239 Expr *op) {
3240 assert(op->getType()->isObjCObjectPointerType());
3241 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3242 return false;
3243
3244 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3245 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3246 << op->getSourceRange();
3247 return true;
3248}
3249
John McCalldadc5752010-08-24 06:29:42 +00003250ExprResult
John McCallb268a282010-08-23 23:25:46 +00003251Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3252 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003253 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003254 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003255 if (Result.isInvalid()) return ExprError();
3256 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003257
John McCallb268a282010-08-23 23:25:46 +00003258 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003259
David Blaikiebbafb8a2012-03-11 07:00:24 +00003260 if (getLangOpts().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003261 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003262 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003263 Context.DependentTy,
3264 VK_LValue, OK_Ordinary,
3265 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003266 }
3267
David Blaikiebbafb8a2012-03-11 07:00:24 +00003268 if (getLangOpts().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003269 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003270 LHSExp->getType()->isEnumeralType() ||
3271 RHSExp->getType()->isRecordType() ||
Ted Kremeneke65b0862012-03-06 20:05:56 +00003272 RHSExp->getType()->isEnumeralType()) &&
3273 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCallb268a282010-08-23 23:25:46 +00003274 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003275 }
3276
John McCallb268a282010-08-23 23:25:46 +00003277 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003278}
3279
John McCalldadc5752010-08-24 06:29:42 +00003280ExprResult
John McCallb268a282010-08-23 23:25:46 +00003281Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003282 Expr *Idx, SourceLocation RLoc) {
John McCallb268a282010-08-23 23:25:46 +00003283 Expr *LHSExp = Base;
3284 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003285
Chris Lattner36d572b2007-07-16 00:14:47 +00003286 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003287 if (!LHSExp->getType()->getAs<VectorType>()) {
3288 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3289 if (Result.isInvalid())
3290 return ExprError();
3291 LHSExp = Result.take();
3292 }
3293 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3294 if (Result.isInvalid())
3295 return ExprError();
3296 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003297
Chris Lattner36d572b2007-07-16 00:14:47 +00003298 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003299 ExprValueKind VK = VK_LValue;
3300 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003301
Steve Naroffc1aadb12007-03-28 21:49:40 +00003302 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003303 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003304 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003305 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003306 Expr *BaseExpr, *IndexExpr;
3307 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003308 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3309 BaseExpr = LHSExp;
3310 IndexExpr = RHSExp;
3311 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003312 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003313 BaseExpr = LHSExp;
3314 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003315 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003316 } else if (const ObjCObjectPointerType *PTy =
John McCallf2538342012-07-31 05:14:30 +00003317 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003318 BaseExpr = LHSExp;
3319 IndexExpr = RHSExp;
John McCallf2538342012-07-31 05:14:30 +00003320
3321 // Use custom logic if this should be the pseudo-object subscript
3322 // expression.
3323 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3324 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3325
Steve Naroff7cae42b2009-07-10 23:34:53 +00003326 ResultType = PTy->getPointeeType();
John McCallf2538342012-07-31 05:14:30 +00003327 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3328 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3329 << ResultType << BaseExpr->getSourceRange();
3330 return ExprError();
3331 }
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00003332 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3333 // Handle the uncommon case of "123[Ptr]".
3334 BaseExpr = RHSExp;
3335 IndexExpr = LHSExp;
3336 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003337 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003338 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003339 // Handle the uncommon case of "123[Ptr]".
3340 BaseExpr = RHSExp;
3341 IndexExpr = LHSExp;
3342 ResultType = PTy->getPointeeType();
John McCallf2538342012-07-31 05:14:30 +00003343 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3344 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3345 << ResultType << BaseExpr->getSourceRange();
3346 return ExprError();
3347 }
John McCall9dd450b2009-09-21 23:43:11 +00003348 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003349 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003350 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003351 VK = LHSExp->getValueKind();
3352 if (VK != VK_RValue)
3353 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003354
Chris Lattner36d572b2007-07-16 00:14:47 +00003355 // FIXME: need to deal with const...
3356 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003357 } else if (LHSTy->isArrayType()) {
3358 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003359 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003360 // wasn't promoted because of the C90 rule that doesn't
3361 // allow promoting non-lvalue arrays. Warn, then
3362 // force the promotion here.
3363 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3364 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003365 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3366 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003367 LHSTy = LHSExp->getType();
3368
3369 BaseExpr = LHSExp;
3370 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003371 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003372 } else if (RHSTy->isArrayType()) {
3373 // Same as previous, except for 123[f().a] case
3374 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3375 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003376 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3377 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003378 RHSTy = RHSExp->getType();
3379
3380 BaseExpr = RHSExp;
3381 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003382 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003383 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003384 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3385 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003386 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003387 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003388 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003389 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3390 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003391
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003392 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003393 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3394 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003395 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3396
Douglas Gregorac1fb652009-03-24 19:52:54 +00003397 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003398 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3399 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003400 // incomplete types are not object types.
3401 if (ResultType->isFunctionType()) {
3402 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3403 << ResultType << BaseExpr->getSourceRange();
3404 return ExprError();
3405 }
Mike Stump11289f42009-09-09 15:08:12 +00003406
David Blaikiebbafb8a2012-03-11 07:00:24 +00003407 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003408 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003409 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3410 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003411
3412 // C forbids expressions of unqualified void type from being l-values.
3413 // See IsCForbiddenLValueType.
3414 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003415 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003416 RequireCompleteType(LLoc, ResultType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003417 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003418 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003419
John McCall4bc41ae2010-11-18 19:01:18 +00003420 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003421 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003422
Mike Stump4e1f26a2009-02-19 03:04:26 +00003423 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003424 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003425}
3426
John McCalldadc5752010-08-24 06:29:42 +00003427ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003428 FunctionDecl *FD,
3429 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003430 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003431 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003432 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003433 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003434 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003435 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003436 return ExprError();
3437 }
3438
3439 if (Param->hasUninstantiatedDefaultArg()) {
3440 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003441
Richard Smith505df232012-07-22 23:45:10 +00003442 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3443 Param);
3444
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003445 // Instantiate the expression.
3446 MultiLevelTemplateArgumentList ArgList
3447 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003448
Nico Weber44887f62010-11-29 18:19:25 +00003449 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003450 = ArgList.getInnermost();
Richard Smith80934652012-07-16 01:09:10 +00003451 InstantiatingTemplate Inst(*this, CallLoc, Param,
3452 ArrayRef<TemplateArgument>(Innermost.first,
3453 Innermost.second));
Richard Smith8a874c92012-07-08 02:38:24 +00003454 if (Inst)
3455 return ExprError();
Anders Carlsson355933d2009-08-25 03:49:14 +00003456
Nico Weber44887f62010-11-29 18:19:25 +00003457 ExprResult Result;
3458 {
3459 // C++ [dcl.fct.default]p5:
3460 // The names in the [default argument] expression are bound, and
3461 // the semantic constraints are checked, at the point where the
3462 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003463 ContextRAII SavedContext(*this, FD);
Douglas Gregora86bc002012-02-16 21:36:18 +00003464 LocalInstantiationScope Local(*this);
Nico Weber44887f62010-11-29 18:19:25 +00003465 Result = SubstExpr(UninstExpr, ArgList);
3466 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003467 if (Result.isInvalid())
3468 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003469
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003470 // Check the expression as an initializer for the parameter.
3471 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003472 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003473 InitializationKind Kind
3474 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003475 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003476 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003477
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003478 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003479 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003480 if (Result.isInvalid())
3481 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003482
David Blaikief68e8092012-04-30 18:21:31 +00003483 Expr *Arg = Result.takeAs<Expr>();
David Blaikie18e9ac72012-05-15 21:57:38 +00003484 CheckImplicitConversions(Arg, Param->getOuterLocStart());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003485 // Build the default argument expression.
David Blaikief68e8092012-04-30 18:21:31 +00003486 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson355933d2009-08-25 03:49:14 +00003487 }
3488
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003489 // If the default expression creates temporaries, we need to
3490 // push them to the current stack of expression temporaries so they'll
3491 // be properly destroyed.
3492 // FIXME: We should really be rebuilding the default argument with new
3493 // bound temporaries; see the comment in PR5810.
John McCall28fc7092011-11-10 05:35:25 +00003494 // We don't need to do that with block decls, though, because
3495 // blocks in default argument expression can never capture anything.
3496 if (isa<ExprWithCleanups>(Param->getInit())) {
3497 // Set the "needs cleanups" bit regardless of whether there are
3498 // any explicit objects.
John McCall31168b02011-06-15 23:02:42 +00003499 ExprNeedsCleanups = true;
John McCall28fc7092011-11-10 05:35:25 +00003500
3501 // Append all the objects to the cleanup list. Right now, this
3502 // should always be a no-op, because blocks in default argument
3503 // expressions should never be able to capture anything.
3504 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3505 "default argument expression has capturing blocks?");
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003506 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003507
3508 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003509 // Just mark all of the declarations in this potentially-evaluated expression
3510 // as being "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +00003511 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3512 /*SkipLocalVariables=*/true);
Douglas Gregor033f6752009-12-23 23:03:06 +00003513 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003514}
3515
Richard Smith55ce3522012-06-25 20:30:08 +00003516
3517Sema::VariadicCallType
3518Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3519 Expr *Fn) {
3520 if (Proto && Proto->isVariadic()) {
3521 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3522 return VariadicConstructor;
3523 else if (Fn && Fn->getType()->isBlockPointerType())
3524 return VariadicBlock;
3525 else if (FDecl) {
3526 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3527 if (Method->isInstance())
3528 return VariadicMethod;
3529 }
3530 return VariadicFunction;
3531 }
3532 return VariadicDoesNotApply;
3533}
3534
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003535/// ConvertArgumentsForCall - Converts the arguments specified in
3536/// Args/NumArgs to the parameter types of the function FDecl with
3537/// function prototype Proto. Call is the call expression itself, and
3538/// Fn is the function expression. For a C++ member function, this
3539/// routine does not attempt to convert the object argument. Returns
3540/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003541bool
3542Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003543 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003544 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003545 Expr **Args, unsigned NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003546 SourceLocation RParenLoc,
3547 bool IsExecConfig) {
John McCallbebede42011-02-26 05:39:39 +00003548 // Bail out early if calling a builtin with custom typechecking.
3549 // We don't need to do this in the
3550 if (FDecl)
3551 if (unsigned ID = FDecl->getBuiltinID())
3552 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3553 return false;
3554
Mike Stump4e1f26a2009-02-19 03:04:26 +00003555 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003556 // assignment, to the types of the corresponding parameter, ...
3557 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003558 bool Invalid = false;
Peter Collingbourne740afe22011-10-02 23:49:20 +00003559 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003560 unsigned FnKind = Fn->getType()->isBlockPointerType()
3561 ? 1 /* block */
3562 : (IsExecConfig ? 3 /* kernel function (exec config) */
3563 : 0 /* function */);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003564
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003565 // If too few arguments are available (and we don't have default
3566 // arguments for the remaining parameters), don't make the call.
3567 if (NumArgs < NumArgsInProto) {
Peter Collingbourne740afe22011-10-02 23:49:20 +00003568 if (NumArgs < MinArgs) {
Richard Smith10ff50d2012-05-11 05:16:41 +00003569 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3570 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3571 ? diag::err_typecheck_call_too_few_args_one
3572 : diag::err_typecheck_call_too_few_args_at_least_one)
3573 << FnKind
3574 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3575 else
3576 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3577 ? diag::err_typecheck_call_too_few_args
3578 : diag::err_typecheck_call_too_few_args_at_least)
3579 << FnKind
3580 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003581
3582 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003583 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003584 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3585 << FDecl;
3586
3587 return true;
3588 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003589 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003590 }
3591
3592 // If too many are passed and not variadic, error on the extras and drop
3593 // them.
3594 if (NumArgs > NumArgsInProto) {
3595 if (!Proto->isVariadic()) {
Richard Smithd72da152012-05-15 06:21:54 +00003596 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3597 Diag(Args[NumArgsInProto]->getLocStart(),
3598 MinArgs == NumArgsInProto
3599 ? diag::err_typecheck_call_too_many_args_one
3600 : diag::err_typecheck_call_too_many_args_at_most_one)
3601 << FnKind
3602 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3603 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3604 Args[NumArgs-1]->getLocEnd());
3605 else
3606 Diag(Args[NumArgsInProto]->getLocStart(),
3607 MinArgs == NumArgsInProto
3608 ? diag::err_typecheck_call_too_many_args
3609 : diag::err_typecheck_call_too_many_args_at_most)
3610 << FnKind
3611 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3612 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3613 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003614
3615 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003616 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003617 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3618 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003619
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003620 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003621 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003622 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003623 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003624 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003625 SmallVector<Expr *, 8> AllArgs;
Richard Smith55ce3522012-06-25 20:30:08 +00003626 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3627
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003628 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003629 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003630 if (Invalid)
3631 return true;
3632 unsigned TotalNumArgs = AllArgs.size();
3633 for (unsigned i = 0; i < TotalNumArgs; ++i)
3634 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003635
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003636 return false;
3637}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003638
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003639bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3640 FunctionDecl *FDecl,
3641 const FunctionProtoType *Proto,
3642 unsigned FirstProtoArg,
3643 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003644 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003645 VariadicCallType CallType,
3646 bool AllowExplicit) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003647 unsigned NumArgsInProto = Proto->getNumArgs();
3648 unsigned NumArgsToCheck = NumArgs;
3649 bool Invalid = false;
3650 if (NumArgs != NumArgsInProto)
3651 // Use default arguments for missing arguments
3652 NumArgsToCheck = NumArgsInProto;
3653 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003654 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003655 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003656 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003657
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003658 Expr *Arg;
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003659 ParmVarDecl *Param;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003660 if (ArgIx < NumArgs) {
3661 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003662
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003663 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedman3164fb12009-03-22 22:00:50 +00003664 ProtoArgType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003665 diag::err_call_incomplete_argument, Arg))
Eli Friedman3164fb12009-03-22 22:00:50 +00003666 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003667
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003668 // Pass the argument
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003669 Param = 0;
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003670 if (FDecl && i < FDecl->getNumParams())
3671 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003672
John McCall4124c492011-10-17 18:40:02 +00003673 // Strip the unbridged-cast placeholder expression off, if applicable.
3674 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3675 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3676 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3677 Arg = stripARCUnbridgedCast(Arg);
3678
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003679 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003680 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003681 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3682 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003683 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003684 SourceLocation(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00003685 Owned(Arg),
3686 /*TopLevelOfInitList=*/false,
3687 AllowExplicit);
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003688 if (ArgE.isInvalid())
3689 return true;
3690
3691 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003692 } else {
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003693 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003694
John McCalldadc5752010-08-24 06:29:42 +00003695 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003696 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003697 if (ArgExpr.isInvalid())
3698 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003699
Anders Carlsson355933d2009-08-25 03:49:14 +00003700 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003701 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003702
3703 // Check for array bounds violations for each argument to the call. This
3704 // check only triggers warnings when the argument isn't a more complex Expr
3705 // with its own checking, such as a BinaryOperator.
3706 CheckArrayAccess(Arg);
3707
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003708 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3709 CheckStaticArrayArgument(CallLoc, Param, Arg);
3710
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003711 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003712 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003713
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003714 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003715 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003716 // Assume that extern "C" functions with variadic arguments that
3717 // return __unknown_anytype aren't *really* variadic.
3718 if (Proto->getResultType() == Context.UnknownAnyTy &&
3719 FDecl && FDecl->isExternC()) {
3720 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3721 ExprResult arg;
3722 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3723 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3724 else
3725 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3726 Invalid |= arg.isInvalid();
3727 AllArgs.push_back(arg.take());
3728 }
3729
3730 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3731 } else {
3732 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003733 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3734 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003735 Invalid |= Arg.isInvalid();
3736 AllArgs.push_back(Arg.take());
3737 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003738 }
Ted Kremenekd41f3462011-09-26 23:36:13 +00003739
3740 // Check for array bounds violations.
3741 for (unsigned i = ArgIx; i != NumArgs; ++i)
3742 CheckArrayAccess(Args[i]);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003743 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003744 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003745}
3746
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003747static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3748 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3749 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3750 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3751 << ATL->getLocalSourceRange();
3752}
3753
3754/// CheckStaticArrayArgument - If the given argument corresponds to a static
3755/// array parameter, check that it is non-null, and that if it is formed by
3756/// array-to-pointer decay, the underlying array is sufficiently large.
3757///
3758/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3759/// array type derivation, then for each call to the function, the value of the
3760/// corresponding actual argument shall provide access to the first element of
3761/// an array with at least as many elements as specified by the size expression.
3762void
3763Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3764 ParmVarDecl *Param,
3765 const Expr *ArgExpr) {
3766 // Static array parameters are not supported in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003767 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003768 return;
3769
3770 QualType OrigTy = Param->getOriginalType();
3771
3772 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3773 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3774 return;
3775
3776 if (ArgExpr->isNullPointerConstant(Context,
3777 Expr::NPC_NeverValueDependent)) {
3778 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3779 DiagnoseCalleeStaticArrayParam(*this, Param);
3780 return;
3781 }
3782
3783 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3784 if (!CAT)
3785 return;
3786
3787 const ConstantArrayType *ArgCAT =
3788 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3789 if (!ArgCAT)
3790 return;
3791
3792 if (ArgCAT->getSize().ult(CAT->getSize())) {
3793 Diag(CallLoc, diag::warn_static_array_too_small)
3794 << ArgExpr->getSourceRange()
3795 << (unsigned) ArgCAT->getSize().getZExtValue()
3796 << (unsigned) CAT->getSize().getZExtValue();
3797 DiagnoseCalleeStaticArrayParam(*this, Param);
3798 }
3799}
3800
John McCall2979fe02011-04-12 00:42:48 +00003801/// Given a function expression of unknown-any type, try to rebuild it
3802/// to have a function type.
3803static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3804
Steve Naroff83895f72007-09-16 03:34:24 +00003805/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003806/// This provides the location of the left/right parens and a list of comma
3807/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003808ExprResult
John McCallb268a282010-08-23 23:25:46 +00003809Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003810 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003811 Expr *ExecConfig, bool IsExecConfig) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003812 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003813 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003814 if (Result.isInvalid()) return ExprError();
3815 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003816
David Blaikiebbafb8a2012-03-11 07:00:24 +00003817 if (getLangOpts().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003818 // If this is a pseudo-destructor expression, build the call immediately.
3819 if (isa<CXXPseudoDestructorExpr>(Fn)) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003820 if (!ArgExprs.empty()) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003821 // Pseudo-destructor calls should not have any arguments.
3822 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003823 << FixItHint::CreateRemoval(
Benjamin Kramerc215e762012-08-24 11:54:20 +00003824 SourceRange(ArgExprs[0]->getLocStart(),
3825 ArgExprs.back()->getLocEnd()));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003826 }
Mike Stump11289f42009-09-09 15:08:12 +00003827
Benjamin Kramerc215e762012-08-24 11:54:20 +00003828 return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(),
3829 Context.VoidTy, VK_RValue,
3830 RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003831 }
Mike Stump11289f42009-09-09 15:08:12 +00003832
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003833 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003834 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003835 // FIXME: Will need to cache the results of name lookup (including ADL) in
3836 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003837 bool Dependent = false;
3838 if (Fn->isTypeDependent())
3839 Dependent = true;
Benjamin Kramerc215e762012-08-24 11:54:20 +00003840 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003841 Dependent = true;
3842
Peter Collingbourne41f85462011-02-09 21:07:24 +00003843 if (Dependent) {
3844 if (ExecConfig) {
3845 return Owned(new (Context) CUDAKernelCallExpr(
Benjamin Kramerc215e762012-08-24 11:54:20 +00003846 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003847 Context.DependentTy, VK_RValue, RParenLoc));
3848 } else {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003849 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003850 Context.DependentTy, VK_RValue,
3851 RParenLoc));
3852 }
3853 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003854
3855 // Determine whether this is a call to an object (C++ [over.call.object]).
3856 if (Fn->getType()->isRecordType())
Benjamin Kramerc215e762012-08-24 11:54:20 +00003857 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
3858 ArgExprs.data(),
3859 ArgExprs.size(), RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003860
John McCall2979fe02011-04-12 00:42:48 +00003861 if (Fn->getType() == Context.UnknownAnyTy) {
3862 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3863 if (result.isInvalid()) return ExprError();
3864 Fn = result.take();
3865 }
3866
John McCall0009fcc2011-04-26 20:42:42 +00003867 if (Fn->getType() == Context.BoundMemberTy) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003868 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3869 ArgExprs.size(), RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003870 }
John McCall0009fcc2011-04-26 20:42:42 +00003871 }
John McCall10eae182009-11-30 22:42:35 +00003872
John McCall0009fcc2011-04-26 20:42:42 +00003873 // Check for overloaded calls. This can happen even in C due to extensions.
3874 if (Fn->getType() == Context.OverloadTy) {
3875 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3876
Douglas Gregorcda22702011-10-13 18:10:35 +00003877 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregorf4a06c22011-10-13 18:26:27 +00003878 if (!find.HasFormOfMemberPointer) {
John McCall0009fcc2011-04-26 20:42:42 +00003879 OverloadExpr *ovl = find.Expression;
3880 if (isa<UnresolvedLookupExpr>(ovl)) {
3881 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
Benjamin Kramerc215e762012-08-24 11:54:20 +00003882 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(),
3883 ArgExprs.size(), RParenLoc, ExecConfig);
John McCall0009fcc2011-04-26 20:42:42 +00003884 } else {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003885 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3886 ArgExprs.size(), RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003887 }
3888 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003889 }
3890
Douglas Gregore254f902009-02-04 00:32:51 +00003891 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregord8fb1e32011-12-01 01:37:36 +00003892 if (Fn->getType() == Context.UnknownAnyTy) {
3893 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3894 if (result.isInvalid()) return ExprError();
3895 Fn = result.take();
3896 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003897
Eli Friedmane14b1992009-12-26 03:35:45 +00003898 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003899
John McCall57500772009-12-16 12:17:52 +00003900 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003901 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3902 if (UnOp->getOpcode() == UO_AddrOf)
3903 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3904
John McCall57500772009-12-16 12:17:52 +00003905 if (isa<DeclRefExpr>(NakedFn))
3906 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003907 else if (isa<MemberExpr>(NakedFn))
3908 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003909
Benjamin Kramerc215e762012-08-24 11:54:20 +00003910 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(),
3911 ArgExprs.size(), RParenLoc, ExecConfig,
3912 IsExecConfig);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003913}
3914
3915ExprResult
3916Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003917 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbourne41f85462011-02-09 21:07:24 +00003918 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3919 if (!ConfigDecl)
3920 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3921 << "cudaConfigureCall");
3922 QualType ConfigQTy = ConfigDecl->getType();
3923
3924 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCall113bee02012-03-10 09:33:50 +00003925 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedmanfa0df832012-02-02 03:46:19 +00003926 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003927
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003928 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3929 /*IsExecConfig=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003930}
3931
Tanya Lattner55808c12011-06-04 00:47:47 +00003932/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3933///
3934/// __builtin_astype( value, dst type )
3935///
Richard Trieuba63ce62011-09-09 01:45:06 +00003936ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00003937 SourceLocation BuiltinLoc,
3938 SourceLocation RParenLoc) {
3939 ExprValueKind VK = VK_RValue;
3940 ExprObjectKind OK = OK_Ordinary;
Richard Trieuba63ce62011-09-09 01:45:06 +00003941 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3942 QualType SrcTy = E->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00003943 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3944 return ExprError(Diag(BuiltinLoc,
3945 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003946 << DstTy
3947 << SrcTy
Richard Trieuba63ce62011-09-09 01:45:06 +00003948 << E->getSourceRange());
3949 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieucfc491d2011-08-02 04:35:43 +00003950 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003951}
3952
John McCall57500772009-12-16 12:17:52 +00003953/// BuildResolvedCallExpr - Build a call to a resolved expression,
3954/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003955/// unary-convert to an expression of function-pointer or
3956/// block-pointer type.
3957///
3958/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003959ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003960Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3961 SourceLocation LParenLoc,
3962 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003963 SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003964 Expr *Config, bool IsExecConfig) {
John McCall2d74de92009-12-01 22:10:20 +00003965 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
Eli Friedman34866c72012-08-31 00:14:07 +00003966 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
John McCall2d74de92009-12-01 22:10:20 +00003967
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003968 // Promote the function operand.
Eli Friedman34866c72012-08-31 00:14:07 +00003969 // We special-case function promotion here because we only allow promoting
3970 // builtin functions to function pointers in the callee of a call.
3971 ExprResult Result;
3972 if (BuiltinID &&
3973 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
3974 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
3975 CK_BuiltinFnToFnPtr).take();
3976 } else {
3977 Result = UsualUnaryConversions(Fn);
3978 }
John Wiegley01296292011-04-08 18:41:53 +00003979 if (Result.isInvalid())
3980 return ExprError();
3981 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003982
Chris Lattner08464942007-12-28 05:29:59 +00003983 // Make the call expr early, before semantic checks. This guarantees cleanup
3984 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003985 CallExpr *TheCall;
Eric Christopher13586ab2012-05-30 01:14:28 +00003986 if (Config)
Peter Collingbourne41f85462011-02-09 21:07:24 +00003987 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3988 cast<CallExpr>(Config),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003989 llvm::makeArrayRef(Args,NumArgs),
Peter Collingbourne41f85462011-02-09 21:07:24 +00003990 Context.BoolTy,
3991 VK_RValue,
3992 RParenLoc);
Eric Christopher13586ab2012-05-30 01:14:28 +00003993 else
Peter Collingbourne41f85462011-02-09 21:07:24 +00003994 TheCall = new (Context) CallExpr(Context, Fn,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003995 llvm::makeArrayRef(Args, NumArgs),
Peter Collingbourne41f85462011-02-09 21:07:24 +00003996 Context.BoolTy,
3997 VK_RValue,
3998 RParenLoc);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003999
John McCallbebede42011-02-26 05:39:39 +00004000 // Bail out early if calling a builtin with custom typechecking.
4001 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4002 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4003
John McCall31996342011-04-07 08:22:57 +00004004 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004005 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00004006 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004007 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4008 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00004009 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00004010 if (FuncT == 0)
4011 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4012 << Fn->getType() << Fn->getSourceRange());
4013 } else if (const BlockPointerType *BPT =
4014 Fn->getType()->getAs<BlockPointerType>()) {
4015 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4016 } else {
John McCall31996342011-04-07 08:22:57 +00004017 // Handle calls to expressions of unknown-any type.
4018 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00004019 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00004020 if (rewrite.isInvalid()) return ExprError();
4021 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00004022 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00004023 goto retry;
4024 }
4025
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004026 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4027 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00004028 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004029
David Blaikiebbafb8a2012-03-11 07:00:24 +00004030 if (getLangOpts().CUDA) {
Peter Collingbourne4b66c472011-02-23 01:53:29 +00004031 if (Config) {
4032 // CUDA: Kernel calls must be to global functions
4033 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4034 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4035 << FDecl->getName() << Fn->getSourceRange());
4036
4037 // CUDA: Kernel function must have 'void' return type
4038 if (!FuncT->getResultType()->isVoidType())
4039 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4040 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne34a20b02011-10-02 23:49:15 +00004041 } else {
4042 // CUDA: Calls to global functions must be configured
4043 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4044 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4045 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne4b66c472011-02-23 01:53:29 +00004046 }
4047 }
4048
Eli Friedman3164fb12009-03-22 22:00:50 +00004049 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004050 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004051 Fn->getLocStart(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004052 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00004053 return ExprError();
4054
Chris Lattner08464942007-12-28 05:29:59 +00004055 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004056 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00004057 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004058
Richard Smith55ce3522012-06-25 20:30:08 +00004059 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4060 if (Proto) {
John McCallb268a282010-08-23 23:25:46 +00004061 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00004062 RParenLoc, IsExecConfig))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004063 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00004064 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004065 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004066
Douglas Gregord8e97de2009-04-02 15:37:10 +00004067 if (FDecl) {
4068 // Check if we have too few/too many template arguments, based
4069 // on our knowledge of the function definition.
4070 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00004071 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Richard Smith55ce3522012-06-25 20:30:08 +00004072 Proto = Def->getType()->getAs<FunctionProtoType>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00004073 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004074 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4075 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004076 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00004077
4078 // If the function we're calling isn't a function prototype, but we have
4079 // a function prototype from a prior declaratiom, use that prototype.
4080 if (!FDecl->hasPrototype())
4081 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00004082 }
4083
Steve Naroff0b661582007-08-28 23:30:39 +00004084 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00004085 for (unsigned i = 0; i != NumArgs; i++) {
4086 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00004087
4088 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004089 InitializedEntity Entity
4090 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00004091 Proto->getArgType(i),
4092 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00004093 ExprResult ArgE = PerformCopyInitialization(Entity,
4094 SourceLocation(),
4095 Owned(Arg));
4096 if (ArgE.isInvalid())
4097 return true;
4098
4099 Arg = ArgE.takeAs<Expr>();
4100
4101 } else {
John Wiegley01296292011-04-08 18:41:53 +00004102 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4103
4104 if (ArgE.isInvalid())
4105 return true;
4106
4107 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00004108 }
4109
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004110 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor83025412010-10-26 05:45:40 +00004111 Arg->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004112 diag::err_call_incomplete_argument, Arg))
Douglas Gregor83025412010-10-26 05:45:40 +00004113 return ExprError();
4114
Chris Lattner08464942007-12-28 05:29:59 +00004115 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00004116 }
Steve Naroffae4143e2007-04-26 20:39:23 +00004117 }
Chris Lattner08464942007-12-28 05:29:59 +00004118
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004119 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4120 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004121 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4122 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004123
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00004124 // Check for sentinels
4125 if (NDecl)
4126 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004127
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004128 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004129 if (FDecl) {
Richard Smith55ce3522012-06-25 20:30:08 +00004130 if (CheckFunctionCall(FDecl, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004131 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004132
John McCallbebede42011-02-26 05:39:39 +00004133 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00004134 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004135 } else if (NDecl) {
Richard Smith55ce3522012-06-25 20:30:08 +00004136 if (CheckBlockCall(NDecl, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004137 return ExprError();
4138 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004139
John McCallb268a282010-08-23 23:25:46 +00004140 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00004141}
4142
John McCalldadc5752010-08-24 06:29:42 +00004143ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004144Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004145 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00004146 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00004147 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00004148 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00004149
4150 TypeSourceInfo *TInfo;
4151 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4152 if (!TInfo)
4153 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4154
John McCallb268a282010-08-23 23:25:46 +00004155 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00004156}
4157
John McCalldadc5752010-08-24 06:29:42 +00004158ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00004159Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00004160 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00004161 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00004162
Eli Friedman37a186d2008-05-20 05:22:08 +00004163 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004164 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004165 diag::err_illegal_decl_array_incomplete_type,
4166 SourceRange(LParenLoc,
4167 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004168 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00004169 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004170 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuba63ce62011-09-09 01:45:06 +00004171 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00004172 } else if (!literalType->isDependentType() &&
4173 RequireCompleteType(LParenLoc, literalType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004174 diag::err_typecheck_decl_incomplete_type,
4175 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004176 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00004177
Douglas Gregor85dabae2009-12-16 01:38:02 +00004178 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00004179 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004180 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00004181 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl0501c632012-02-12 16:37:36 +00004182 SourceRange(LParenLoc, RParenLoc),
4183 /*InitList=*/true);
Richard Trieuba63ce62011-09-09 01:45:06 +00004184 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004185 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4186 &literalType);
Eli Friedmana553d4a2009-12-22 02:35:53 +00004187 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004188 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004189 LiteralExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00004190
Chris Lattner79413952008-12-04 23:50:19 +00004191 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00004192 if (isFileScope) { // 6.5.2.5p3
Richard Trieuba63ce62011-09-09 01:45:06 +00004193 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004194 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004195 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004196
John McCall7decc9e2010-11-18 06:31:45 +00004197 // In C, compound literals are l-values for some reason.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004198 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00004199
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00004200 return MaybeBindToTemporary(
4201 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuba63ce62011-09-09 01:45:06 +00004202 VK, LiteralExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004203}
4204
John McCalldadc5752010-08-24 06:29:42 +00004205ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004206Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004207 SourceLocation RBraceLoc) {
John McCall526ab472011-10-25 17:37:35 +00004208 // Immediately handle non-overload placeholders. Overloads can be
4209 // resolved contextually, but everything else here can't.
Benjamin Kramerc215e762012-08-24 11:54:20 +00004210 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4211 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4212 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
John McCall526ab472011-10-25 17:37:35 +00004213
4214 // Ignore failures; dropping the entire initializer list because
4215 // of one failure would be terrible for indexing/etc.
4216 if (result.isInvalid()) continue;
4217
Benjamin Kramerc215e762012-08-24 11:54:20 +00004218 InitArgList[I] = result.take();
John McCall526ab472011-10-25 17:37:35 +00004219 }
4220 }
4221
Steve Naroff30d242c2007-09-15 18:49:24 +00004222 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004223 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004224
Benjamin Kramerc215e762012-08-24 11:54:20 +00004225 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4226 RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004227 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004228 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004229}
4230
John McCallcd78e802011-09-10 01:16:55 +00004231/// Do an explicit extend of the given block pointer if we're in ARC.
4232static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4233 assert(E.get()->getType()->isBlockPointerType());
4234 assert(E.get()->isRValue());
4235
4236 // Only do this in an r-value context.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004237 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallcd78e802011-09-10 01:16:55 +00004238
4239 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall2d637d22011-09-10 06:18:15 +00004240 CK_ARCExtendBlockObject, E.get(),
John McCallcd78e802011-09-10 01:16:55 +00004241 /*base path*/ 0, VK_RValue);
4242 S.ExprNeedsCleanups = true;
4243}
4244
4245/// Prepare a conversion of the given expression to an ObjC object
4246/// pointer type.
4247CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4248 QualType type = E.get()->getType();
4249 if (type->isObjCObjectPointerType()) {
4250 return CK_BitCast;
4251 } else if (type->isBlockPointerType()) {
4252 maybeExtendBlockObject(*this, E);
4253 return CK_BlockPointerToObjCPointerCast;
4254 } else {
4255 assert(type->isPointerType());
4256 return CK_CPointerToObjCPointerCast;
4257 }
4258}
4259
John McCalld7646252010-11-14 08:17:51 +00004260/// Prepares for a scalar cast, performing all the necessary stages
4261/// except the final cast and returning the kind required.
John McCall9776e432011-10-06 23:25:11 +00004262CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00004263 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4264 // Also, callers should have filtered out the invalid cases with
4265 // pointers. Everything else should be possible.
4266
John Wiegley01296292011-04-08 18:41:53 +00004267 QualType SrcTy = Src.get()->getType();
John McCall9776e432011-10-06 23:25:11 +00004268 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004269 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004270
John McCall9320b872011-09-09 05:25:32 +00004271 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00004272 case Type::STK_MemberPointer:
4273 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00004274
John McCall9320b872011-09-09 05:25:32 +00004275 case Type::STK_CPointer:
4276 case Type::STK_BlockPointer:
4277 case Type::STK_ObjCObjectPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004278 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004279 case Type::STK_CPointer:
4280 return CK_BitCast;
4281 case Type::STK_BlockPointer:
4282 return (SrcKind == Type::STK_BlockPointer
4283 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4284 case Type::STK_ObjCObjectPointer:
4285 if (SrcKind == Type::STK_ObjCObjectPointer)
4286 return CK_BitCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004287 if (SrcKind == Type::STK_CPointer)
John McCall9320b872011-09-09 05:25:32 +00004288 return CK_CPointerToObjCPointerCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004289 maybeExtendBlockObject(*this, Src);
4290 return CK_BlockPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00004291 case Type::STK_Bool:
4292 return CK_PointerToBoolean;
4293 case Type::STK_Integral:
4294 return CK_PointerToIntegral;
4295 case Type::STK_Floating:
4296 case Type::STK_FloatingComplex:
4297 case Type::STK_IntegralComplex:
4298 case Type::STK_MemberPointer:
4299 llvm_unreachable("illegal cast from pointer");
4300 }
David Blaikie8a40f702012-01-17 06:56:22 +00004301 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004302
John McCall8cb679e2010-11-15 09:13:47 +00004303 case Type::STK_Bool: // casting from bool is like casting from an integer
4304 case Type::STK_Integral:
4305 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004306 case Type::STK_CPointer:
4307 case Type::STK_ObjCObjectPointer:
4308 case Type::STK_BlockPointer:
John McCall9776e432011-10-06 23:25:11 +00004309 if (Src.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00004310 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004311 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004312 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004313 case Type::STK_Bool:
4314 return CK_IntegralToBoolean;
4315 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004316 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004317 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004318 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004319 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004320 Src = ImpCastExprToType(Src.take(),
4321 DestTy->castAs<ComplexType>()->getElementType(),
4322 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004323 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004324 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004325 Src = ImpCastExprToType(Src.take(),
4326 DestTy->castAs<ComplexType>()->getElementType(),
4327 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00004328 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004329 case Type::STK_MemberPointer:
4330 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004331 }
David Blaikie8a40f702012-01-17 06:56:22 +00004332 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004333
John McCall8cb679e2010-11-15 09:13:47 +00004334 case Type::STK_Floating:
4335 switch (DestTy->getScalarTypeKind()) {
4336 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004337 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004338 case Type::STK_Bool:
4339 return CK_FloatingToBoolean;
4340 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004341 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004342 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004343 Src = ImpCastExprToType(Src.take(),
4344 DestTy->castAs<ComplexType>()->getElementType(),
4345 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004346 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004347 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004348 Src = ImpCastExprToType(Src.take(),
4349 DestTy->castAs<ComplexType>()->getElementType(),
4350 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00004351 return CK_IntegralRealToComplex;
John McCall9320b872011-09-09 05:25:32 +00004352 case Type::STK_CPointer:
4353 case Type::STK_ObjCObjectPointer:
4354 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004355 llvm_unreachable("valid float->pointer cast?");
4356 case Type::STK_MemberPointer:
4357 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004358 }
David Blaikie8a40f702012-01-17 06:56:22 +00004359 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004360
John McCall8cb679e2010-11-15 09:13:47 +00004361 case Type::STK_FloatingComplex:
4362 switch (DestTy->getScalarTypeKind()) {
4363 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004364 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004365 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004366 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004367 case Type::STK_Floating: {
John McCall9776e432011-10-06 23:25:11 +00004368 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4369 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004370 return CK_FloatingComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004371 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004372 return CK_FloatingCast;
4373 }
John McCall8cb679e2010-11-15 09:13:47 +00004374 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004375 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004376 case Type::STK_Integral:
John McCall9776e432011-10-06 23:25:11 +00004377 Src = ImpCastExprToType(Src.take(),
4378 SrcTy->castAs<ComplexType>()->getElementType(),
4379 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004380 return CK_FloatingToIntegral;
John McCall9320b872011-09-09 05:25:32 +00004381 case Type::STK_CPointer:
4382 case Type::STK_ObjCObjectPointer:
4383 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004384 llvm_unreachable("valid complex float->pointer cast?");
4385 case Type::STK_MemberPointer:
4386 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004387 }
David Blaikie8a40f702012-01-17 06:56:22 +00004388 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004389
John McCall8cb679e2010-11-15 09:13:47 +00004390 case Type::STK_IntegralComplex:
4391 switch (DestTy->getScalarTypeKind()) {
4392 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004393 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004394 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004395 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004396 case Type::STK_Integral: {
John McCall9776e432011-10-06 23:25:11 +00004397 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4398 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004399 return CK_IntegralComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004400 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004401 return CK_IntegralCast;
4402 }
John McCall8cb679e2010-11-15 09:13:47 +00004403 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004404 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004405 case Type::STK_Floating:
John McCall9776e432011-10-06 23:25:11 +00004406 Src = ImpCastExprToType(Src.take(),
4407 SrcTy->castAs<ComplexType>()->getElementType(),
4408 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004409 return CK_IntegralToFloating;
John McCall9320b872011-09-09 05:25:32 +00004410 case Type::STK_CPointer:
4411 case Type::STK_ObjCObjectPointer:
4412 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004413 llvm_unreachable("valid complex int->pointer cast?");
4414 case Type::STK_MemberPointer:
4415 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004416 }
David Blaikie8a40f702012-01-17 06:56:22 +00004417 llvm_unreachable("Should have returned before this");
Anders Carlsson094c4592009-10-18 18:12:03 +00004418 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004419
John McCalld7646252010-11-14 08:17:51 +00004420 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson094c4592009-10-18 18:12:03 +00004421}
4422
Anders Carlsson525b76b2009-10-16 02:48:28 +00004423bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004424 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004425 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004426
Anders Carlssonde71adf2007-11-27 05:51:55 +00004427 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004428 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004429 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004430 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004431 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004432 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004433 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004434 } else
4435 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004436 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004437 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004438
John McCalle3027922010-08-25 11:45:40 +00004439 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004440 return false;
4441}
4442
John Wiegley01296292011-04-08 18:41:53 +00004443ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4444 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004445 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004446
Anders Carlsson43d70f82009-10-16 05:23:41 +00004447 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004448
Nate Begemanc8961a42009-06-27 22:05:55 +00004449 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4450 // an ExtVectorType.
Tobias Grosser766bcc22011-09-22 13:03:14 +00004451 // In OpenCL, casts between vectors of different types are not allowed.
4452 // (See OpenCL 6.2).
Nate Begemanc69b7402009-06-26 00:50:28 +00004453 if (SrcTy->isVectorType()) {
Tobias Grosser766bcc22011-09-22 13:03:14 +00004454 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikiebbafb8a2012-03-11 07:00:24 +00004455 || (getLangOpts().OpenCL &&
Tobias Grosser766bcc22011-09-22 13:03:14 +00004456 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004457 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004458 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004459 return ExprError();
4460 }
John McCalle3027922010-08-25 11:45:40 +00004461 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004462 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004463 }
4464
Nate Begemanbd956c42009-06-28 02:36:38 +00004465 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004466 // conversion will take place first from scalar to elt type, and then
4467 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004468 if (SrcTy->isPointerType())
4469 return Diag(R.getBegin(),
4470 diag::err_invalid_conversion_between_vector_and_scalar)
4471 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004472
4473 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004474 ExprResult CastExprRes = Owned(CastExpr);
John McCall9776e432011-10-06 23:25:11 +00004475 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley01296292011-04-08 18:41:53 +00004476 if (CastExprRes.isInvalid())
4477 return ExprError();
4478 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004479
John McCalle3027922010-08-25 11:45:40 +00004480 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004481 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004482}
4483
John McCalldadc5752010-08-24 06:29:42 +00004484ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004485Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4486 Declarator &D, ParsedType &Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004487 SourceLocation RParenLoc, Expr *CastExpr) {
4488 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004489 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004490
Richard Trieuba63ce62011-09-09 01:45:06 +00004491 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004492 if (D.isInvalidType())
4493 return ExprError();
4494
David Blaikiebbafb8a2012-03-11 07:00:24 +00004495 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004496 // Check that there are no default arguments (C++ only).
4497 CheckExtraCXXDefaultArguments(D);
4498 }
4499
John McCall42856de2011-10-01 05:17:03 +00004500 checkUnusedDeclAttributes(D);
4501
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004502 QualType castType = castTInfo->getType();
4503 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004504
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004505 bool isVectorLiteral = false;
4506
4507 // Check for an altivec or OpenCL literal,
4508 // i.e. all the elements are integer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00004509 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4510 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004511 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser0a3a22f2011-09-21 18:28:29 +00004512 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004513 if (PLE && PLE->getNumExprs() == 0) {
4514 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4515 return ExprError();
4516 }
4517 if (PE || PLE->getNumExprs() == 1) {
4518 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4519 if (!E->getType()->isVectorType())
4520 isVectorLiteral = true;
4521 }
4522 else
4523 isVectorLiteral = true;
4524 }
4525
4526 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4527 // then handle it as such.
4528 if (isVectorLiteral)
Richard Trieuba63ce62011-09-09 01:45:06 +00004529 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004530
Nate Begeman5ec4b312009-08-10 23:49:36 +00004531 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004532 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4533 // sequence of BinOp comma operators.
Richard Trieuba63ce62011-09-09 01:45:06 +00004534 if (isa<ParenListExpr>(CastExpr)) {
4535 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004536 if (Result.isInvalid()) return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004537 CastExpr = Result.take();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004538 }
John McCallebe54742010-01-15 18:56:44 +00004539
Richard Trieuba63ce62011-09-09 01:45:06 +00004540 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallebe54742010-01-15 18:56:44 +00004541}
4542
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004543ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4544 SourceLocation RParenLoc, Expr *E,
4545 TypeSourceInfo *TInfo) {
4546 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4547 "Expected paren or paren list expression");
4548
4549 Expr **exprs;
4550 unsigned numExprs;
4551 Expr *subExpr;
4552 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4553 exprs = PE->getExprs();
4554 numExprs = PE->getNumExprs();
4555 } else {
4556 subExpr = cast<ParenExpr>(E)->getSubExpr();
4557 exprs = &subExpr;
4558 numExprs = 1;
4559 }
4560
4561 QualType Ty = TInfo->getType();
4562 assert(Ty->isVectorType() && "Expected vector type");
4563
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004564 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004565 const VectorType *VTy = Ty->getAs<VectorType>();
4566 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4567
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004568 // '(...)' form of vector initialization in AltiVec: the number of
4569 // initializers must be one or must match the size of the vector.
4570 // If a single value is specified in the initializer then it will be
4571 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004572 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004573 // The number of initializers must be one or must match the size of the
4574 // vector. If a single value is specified in the initializer then it will
4575 // be replicated to all the components of the vector
4576 if (numExprs == 1) {
4577 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004578 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4579 if (Literal.isInvalid())
4580 return ExprError();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004581 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004582 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004583 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4584 }
4585 else if (numExprs < numElems) {
4586 Diag(E->getExprLoc(),
4587 diag::err_incorrect_number_of_vector_initializers);
4588 return ExprError();
4589 }
4590 else
Benjamin Kramer8001f742012-02-14 12:06:21 +00004591 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004592 }
Tanya Lattner83559382011-07-15 23:07:01 +00004593 else {
4594 // For OpenCL, when the number of initializers is a single value,
4595 // it will be replicated to all components of the vector.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004596 if (getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +00004597 VTy->getVectorKind() == VectorType::GenericVector &&
4598 numExprs == 1) {
4599 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004600 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4601 if (Literal.isInvalid())
4602 return ExprError();
Tanya Lattner83559382011-07-15 23:07:01 +00004603 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004604 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner83559382011-07-15 23:07:01 +00004605 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4606 }
4607
Benjamin Kramer8001f742012-02-14 12:06:21 +00004608 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner83559382011-07-15 23:07:01 +00004609 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004610 // FIXME: This means that pretty-printing the final AST will produce curly
4611 // braces instead of the original commas.
4612 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00004613 initExprs, RParenLoc);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004614 initE->setType(Ty);
4615 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4616}
4617
Sebastian Redla9351792012-02-11 23:51:47 +00004618/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4619/// the ParenListExpr into a sequence of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004620ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004621Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4622 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004623 if (!E)
Richard Trieuba63ce62011-09-09 01:45:06 +00004624 return Owned(OrigExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004625
John McCalldadc5752010-08-24 06:29:42 +00004626 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004627
Nate Begeman5ec4b312009-08-10 23:49:36 +00004628 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004629 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4630 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004631
John McCallb268a282010-08-23 23:25:46 +00004632 if (Result.isInvalid()) return ExprError();
4633
4634 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004635}
4636
Sebastian Redla9351792012-02-11 23:51:47 +00004637ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4638 SourceLocation R,
4639 MultiExprArg Val) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00004640 assert(Val.data() != 0 && "ActOnParenOrParenListExpr() missing expr list");
4641 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004642 return Owned(expr);
4643}
4644
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004645/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004646/// constant and the other is not a pointer. Returns true if a diagnostic is
4647/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00004648bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004649 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004650 Expr *NullExpr = LHSExpr;
4651 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004652 Expr::NullPointerConstantKind NullKind =
4653 NullExpr->isNullPointerConstant(Context,
4654 Expr::NPC_ValueDependentIsNotNull);
4655
4656 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004657 NullExpr = RHSExpr;
4658 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004659 NullKind =
4660 NullExpr->isNullPointerConstant(Context,
4661 Expr::NPC_ValueDependentIsNotNull);
4662 }
4663
4664 if (NullKind == Expr::NPCK_NotNull)
4665 return false;
4666
David Blaikie1c7c8f72012-08-08 17:33:31 +00004667 if (NullKind == Expr::NPCK_ZeroExpression)
4668 return false;
4669
4670 if (NullKind == Expr::NPCK_ZeroLiteral) {
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004671 // In this case, check to make sure that we got here from a "NULL"
4672 // string in the source code.
4673 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004674 SourceLocation loc = NullExpr->getExprLoc();
4675 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004676 return false;
4677 }
4678
4679 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4680 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4681 << NonPointerExpr->getType() << DiagType
4682 << NonPointerExpr->getSourceRange();
4683 return true;
4684}
4685
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004686/// \brief Return false if the condition expression is valid, true otherwise.
4687static bool checkCondition(Sema &S, Expr *Cond) {
4688 QualType CondTy = Cond->getType();
4689
4690 // C99 6.5.15p2
4691 if (CondTy->isScalarType()) return false;
4692
4693 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004694 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004695 return false;
4696
4697 // Emit the proper error message.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004698 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004699 diag::err_typecheck_cond_expect_scalar :
4700 diag::err_typecheck_cond_expect_scalar_or_vector)
4701 << CondTy;
4702 return true;
4703}
4704
4705/// \brief Return false if the two expressions can be converted to a vector,
4706/// true otherwise
4707static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4708 ExprResult &RHS,
4709 QualType CondTy) {
4710 // Both operands should be of scalar type.
4711 if (!LHS.get()->getType()->isScalarType()) {
4712 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4713 << CondTy;
4714 return true;
4715 }
4716 if (!RHS.get()->getType()->isScalarType()) {
4717 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4718 << CondTy;
4719 return true;
4720 }
4721
4722 // Implicity convert these scalars to the type of the condition.
4723 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4724 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4725 return false;
4726}
4727
4728/// \brief Handle when one or both operands are void type.
4729static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4730 ExprResult &RHS) {
4731 Expr *LHSExpr = LHS.get();
4732 Expr *RHSExpr = RHS.get();
4733
4734 if (!LHSExpr->getType()->isVoidType())
4735 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4736 << RHSExpr->getSourceRange();
4737 if (!RHSExpr->getType()->isVoidType())
4738 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4739 << LHSExpr->getSourceRange();
4740 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4741 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4742 return S.Context.VoidTy;
4743}
4744
4745/// \brief Return false if the NullExpr can be promoted to PointerTy,
4746/// true otherwise.
4747static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4748 QualType PointerTy) {
4749 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4750 !NullExpr.get()->isNullPointerConstant(S.Context,
4751 Expr::NPC_ValueDependentIsNull))
4752 return true;
4753
4754 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4755 return false;
4756}
4757
4758/// \brief Checks compatibility between two pointers and return the resulting
4759/// type.
4760static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4761 ExprResult &RHS,
4762 SourceLocation Loc) {
4763 QualType LHSTy = LHS.get()->getType();
4764 QualType RHSTy = RHS.get()->getType();
4765
4766 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4767 // Two identical pointers types are always compatible.
4768 return LHSTy;
4769 }
4770
4771 QualType lhptee, rhptee;
4772
4773 // Get the pointee types.
John McCall9320b872011-09-09 05:25:32 +00004774 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4775 lhptee = LHSBTy->getPointeeType();
4776 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004777 } else {
John McCall9320b872011-09-09 05:25:32 +00004778 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4779 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004780 }
4781
Eli Friedman57a75392012-04-05 22:30:04 +00004782 // C99 6.5.15p6: If both operands are pointers to compatible types or to
4783 // differently qualified versions of compatible types, the result type is
4784 // a pointer to an appropriately qualified version of the composite
4785 // type.
4786
4787 // Only CVR-qualifiers exist in the standard, and the differently-qualified
4788 // clause doesn't make sense for our extensions. E.g. address space 2 should
4789 // be incompatible with address space 3: they may live on different devices or
4790 // anything.
4791 Qualifiers lhQual = lhptee.getQualifiers();
4792 Qualifiers rhQual = rhptee.getQualifiers();
4793
4794 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4795 lhQual.removeCVRQualifiers();
4796 rhQual.removeCVRQualifiers();
4797
4798 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4799 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4800
4801 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4802
4803 if (CompositeTy.isNull()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004804 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4805 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4806 << RHS.get()->getSourceRange();
4807 // In this situation, we assume void* type. No especially good
4808 // reason, but this is what gcc does, and we do have to pick
4809 // to get a consistent AST.
4810 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4811 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4812 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4813 return incompatTy;
4814 }
4815
4816 // The pointer types are compatible.
Eli Friedman57a75392012-04-05 22:30:04 +00004817 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4818 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004819
Eli Friedman57a75392012-04-05 22:30:04 +00004820 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4821 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4822 return ResultTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004823}
4824
4825/// \brief Return the resulting type when the operands are both block pointers.
4826static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4827 ExprResult &LHS,
4828 ExprResult &RHS,
4829 SourceLocation Loc) {
4830 QualType LHSTy = LHS.get()->getType();
4831 QualType RHSTy = RHS.get()->getType();
4832
4833 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4834 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4835 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4836 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4837 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4838 return destType;
4839 }
4840 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4841 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4842 << RHS.get()->getSourceRange();
4843 return QualType();
4844 }
4845
4846 // We have 2 block pointer types.
4847 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4848}
4849
4850/// \brief Return the resulting type when the operands are both pointers.
4851static QualType
4852checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4853 ExprResult &RHS,
4854 SourceLocation Loc) {
4855 // get the pointer types
4856 QualType LHSTy = LHS.get()->getType();
4857 QualType RHSTy = RHS.get()->getType();
4858
4859 // get the "pointed to" types
4860 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4861 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4862
4863 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4864 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4865 // Figure out necessary qualifiers (C99 6.5.15p6)
4866 QualType destPointee
4867 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4868 QualType destType = S.Context.getPointerType(destPointee);
4869 // Add qualifiers if necessary.
4870 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4871 // Promote to void*.
4872 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4873 return destType;
4874 }
4875 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4876 QualType destPointee
4877 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4878 QualType destType = S.Context.getPointerType(destPointee);
4879 // Add qualifiers if necessary.
4880 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4881 // Promote to void*.
4882 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4883 return destType;
4884 }
4885
4886 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4887}
4888
4889/// \brief Return false if the first expression is not an integer and the second
4890/// expression is not a pointer, true otherwise.
4891static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4892 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004893 bool IsIntFirstExpr) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004894 if (!PointerExpr->getType()->isPointerType() ||
4895 !Int.get()->getType()->isIntegerType())
4896 return false;
4897
Richard Trieuba63ce62011-09-09 01:45:06 +00004898 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4899 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004900
4901 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4902 << Expr1->getType() << Expr2->getType()
4903 << Expr1->getSourceRange() << Expr2->getSourceRange();
4904 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4905 CK_IntegralToPointer);
4906 return true;
4907}
4908
Richard Trieud33e46e2011-09-06 20:06:39 +00004909/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4910/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004911/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004912QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4913 ExprResult &RHS, ExprValueKind &VK,
4914 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004915 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004916
Richard Trieud33e46e2011-09-06 20:06:39 +00004917 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4918 if (!LHSResult.isUsable()) return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004919 LHS = LHSResult;
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004920
Richard Trieud33e46e2011-09-06 20:06:39 +00004921 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4922 if (!RHSResult.isUsable()) return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004923 RHS = RHSResult;
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004924
Sebastian Redl1a99f442009-04-16 17:51:27 +00004925 // C++ is sufficiently different to merit its own checker.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004926 if (getLangOpts().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004927 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004928
4929 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004930 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004931
John Wiegley01296292011-04-08 18:41:53 +00004932 Cond = UsualUnaryConversions(Cond.take());
4933 if (Cond.isInvalid())
4934 return QualType();
4935 LHS = UsualUnaryConversions(LHS.take());
4936 if (LHS.isInvalid())
4937 return QualType();
4938 RHS = UsualUnaryConversions(RHS.take());
4939 if (RHS.isInvalid())
4940 return QualType();
4941
4942 QualType CondTy = Cond.get()->getType();
4943 QualType LHSTy = LHS.get()->getType();
4944 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004945
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004946 // first, check the condition.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004947 if (checkCondition(*this, Cond.get()))
4948 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004949
Chris Lattnere2949f42008-01-06 22:42:25 +00004950 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004951 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004952 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004953
Nate Begemanabb5a732010-09-20 22:41:17 +00004954 // OpenCL: If the condition is a vector, and both operands are scalar,
4955 // attempt to implicity convert them to the vector type to act like the
4956 // built in select.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004957 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004958 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begemanabb5a732010-09-20 22:41:17 +00004959 return QualType();
Nate Begemanabb5a732010-09-20 22:41:17 +00004960
Chris Lattnere2949f42008-01-06 22:42:25 +00004961 // If both operands have arithmetic type, do the usual arithmetic conversions
4962 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004963 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4964 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004965 if (LHS.isInvalid() || RHS.isInvalid())
4966 return QualType();
4967 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004968 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004969
Chris Lattnere2949f42008-01-06 22:42:25 +00004970 // If both operands are the same structure or union type, the result is that
4971 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004972 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4973 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004974 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004975 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004976 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004977 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004978 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004979 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004980
Chris Lattnere2949f42008-01-06 22:42:25 +00004981 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004982 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004983 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004984 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00004985 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004986
Steve Naroff039ad3c2008-01-08 01:11:38 +00004987 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4988 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004989 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4990 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004991
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004992 // All objective-c pointer type analysis is done here.
4993 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4994 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004995 if (LHS.isInvalid() || RHS.isInvalid())
4996 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004997 if (!compositeType.isNull())
4998 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004999
5000
Steve Naroff05efa972009-07-01 14:36:47 +00005001 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005002 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5003 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5004 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005005
Steve Naroff05efa972009-07-01 14:36:47 +00005006 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005007 if (LHSTy->isPointerType() && RHSTy->isPointerType())
5008 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5009 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00005010
John McCalle84af4e2010-11-13 01:35:44 +00005011 // GCC compatibility: soften pointer/integer mismatch. Note that
5012 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005013 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5014 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00005015 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005016 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5017 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00005018 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00005019
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005020 // Emit a better diagnostic if one of the expressions is a null pointer
5021 // constant and the other is not a pointer type. In this case, the user most
5022 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005023 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005024 return QualType();
5025
Chris Lattnere2949f42008-01-06 22:42:25 +00005026 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00005027 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00005028 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5029 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005030 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00005031}
5032
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005033/// FindCompositeObjCPointerType - Helper method to find composite type of
5034/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00005035QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00005036 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005037 QualType LHSTy = LHS.get()->getType();
5038 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005039
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005040 // Handle things like Class and struct objc_class*. Here we case the result
5041 // to the pseudo-builtin, because that will be implicitly cast back to the
5042 // redefinition type if an attempt is made to access its fields.
5043 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005044 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005045 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005046 return LHSTy;
5047 }
5048 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005049 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005050 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005051 return RHSTy;
5052 }
5053 // And the same for struct objc_object* / id
5054 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005055 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005056 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005057 return LHSTy;
5058 }
5059 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005060 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005061 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005062 return RHSTy;
5063 }
5064 // And the same for struct objc_selector* / SEL
5065 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00005066 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005067 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005068 return LHSTy;
5069 }
5070 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00005071 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005072 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005073 return RHSTy;
5074 }
5075 // Check constraints for Objective-C object pointers types.
5076 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005077
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005078 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5079 // Two identical object pointer types are always compatible.
5080 return LHSTy;
5081 }
John McCall9320b872011-09-09 05:25:32 +00005082 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5083 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005084 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005085
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005086 // If both operands are interfaces and either operand can be
5087 // assigned to the other, use that type as the composite
5088 // type. This allows
5089 // xxx ? (A*) a : (B*) b
5090 // where B is a subclass of A.
5091 //
5092 // Additionally, as for assignment, if either type is 'id'
5093 // allow silent coercion. Finally, if the types are
5094 // incompatible then make sure to use 'id' as the composite
5095 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005096
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005097 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5098 // It could return the composite type.
5099 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5100 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5101 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5102 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5103 } else if ((LHSTy->isObjCQualifiedIdType() ||
5104 RHSTy->isObjCQualifiedIdType()) &&
5105 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5106 // Need to handle "id<xx>" explicitly.
5107 // GCC allows qualified id and any Objective-C type to devolve to
5108 // id. Currently localizing to here until clear this should be
5109 // part of ObjCQualifiedIdTypesAreCompatible.
5110 compositeType = Context.getObjCIdType();
5111 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5112 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005113 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005114 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5115 ;
5116 else {
5117 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5118 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00005119 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005120 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00005121 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5122 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005123 return incompatTy;
5124 }
5125 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00005126 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5127 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005128 return compositeType;
5129 }
5130 // Check Objective-C object pointer types and 'void *'
5131 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005132 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00005133 // ARC forbids the implicit conversion of object pointers to 'void *',
5134 // so these types are not compatible.
5135 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5136 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5137 LHS = RHS = true;
5138 return QualType();
5139 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005140 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5141 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5142 QualType destPointee
5143 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5144 QualType destType = Context.getPointerType(destPointee);
5145 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005146 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005147 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005148 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005149 return destType;
5150 }
5151 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005152 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00005153 // ARC forbids the implicit conversion of object pointers to 'void *',
5154 // so these types are not compatible.
5155 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5156 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5157 LHS = RHS = true;
5158 return QualType();
5159 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005160 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5161 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5162 QualType destPointee
5163 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5164 QualType destType = Context.getPointerType(destPointee);
5165 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005166 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005167 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005168 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005169 return destType;
5170 }
5171 return QualType();
5172}
5173
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005174/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005175/// ParenRange in parentheses.
5176static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005177 const PartialDiagnostic &Note,
5178 SourceRange ParenRange) {
5179 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5180 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5181 EndLoc.isValid()) {
5182 Self.Diag(Loc, Note)
5183 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5184 << FixItHint::CreateInsertion(EndLoc, ")");
5185 } else {
5186 // We can't display the parentheses, so just show the bare note.
5187 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005188 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005189}
5190
5191static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5192 return Opc >= BO_Mul && Opc <= BO_Shr;
5193}
5194
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005195/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5196/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00005197/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5198/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005199static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00005200 Expr **RHSExprs) {
Hans Wennborgbe207b32011-09-12 12:07:30 +00005201 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5202 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005203 E = E->IgnoreConversionOperator();
Hans Wennborgbe207b32011-09-12 12:07:30 +00005204 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005205
5206 // Built-in binary operator.
5207 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5208 if (IsArithmeticOp(OP->getOpcode())) {
5209 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00005210 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005211 return true;
5212 }
5213 }
5214
5215 // Overloaded operator.
5216 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5217 if (Call->getNumArgs() != 2)
5218 return false;
5219
5220 // Make sure this is really a binary operator that is safe to pass into
5221 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5222 OverloadedOperatorKind OO = Call->getOperator();
5223 if (OO < OO_Plus || OO > OO_Arrow)
5224 return false;
5225
5226 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5227 if (IsArithmeticOp(OpKind)) {
5228 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00005229 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005230 return true;
5231 }
5232 }
5233
5234 return false;
5235}
5236
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005237static bool IsLogicOp(BinaryOperatorKind Opc) {
5238 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5239}
5240
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005241/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5242/// or is a logical expression such as (x==y) which has int type, but is
5243/// commonly interpreted as boolean.
5244static bool ExprLooksBoolean(Expr *E) {
5245 E = E->IgnoreParenImpCasts();
5246
5247 if (E->getType()->isBooleanType())
5248 return true;
5249 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5250 return IsLogicOp(OP->getOpcode());
5251 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5252 return OP->getOpcode() == UO_LNot;
5253
5254 return false;
5255}
5256
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005257/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5258/// and binary operator are mixed in a way that suggests the programmer assumed
5259/// the conditional operator has higher precedence, for example:
5260/// "int x = a + someBinaryCondition ? 1 : 2".
5261static void DiagnoseConditionalPrecedence(Sema &Self,
5262 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005263 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00005264 Expr *LHSExpr,
5265 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005266 BinaryOperatorKind CondOpcode;
5267 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005268
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005269 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005270 return;
5271 if (!ExprLooksBoolean(CondRHS))
5272 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005273
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005274 // The condition is an arithmetic binary expression, with a right-
5275 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005276
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005277 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005278 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005279 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005280
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005281 SuggestParentheses(Self, OpLoc,
5282 Self.PDiag(diag::note_precedence_conditional_silence)
5283 << BinaryOperator::getOpcodeStr(CondOpcode),
5284 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00005285
5286 SuggestParentheses(Self, OpLoc,
5287 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00005288 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005289}
5290
Steve Naroff83895f72007-09-16 03:34:24 +00005291/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005292/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005293ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005294 SourceLocation ColonLoc,
5295 Expr *CondExpr, Expr *LHSExpr,
5296 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005297 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5298 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005299 OpaqueValueExpr *opaqueValue = 0;
5300 Expr *commonExpr = 0;
5301 if (LHSExpr == 0) {
5302 commonExpr = CondExpr;
5303
5304 // We usually want to apply unary conversions *before* saving, except
5305 // in the special case of a C++ l-value conditional.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005306 if (!(getLangOpts().CPlusPlus
John McCallc07a0c72011-02-17 10:25:35 +00005307 && !commonExpr->isTypeDependent()
5308 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5309 && commonExpr->isGLValue()
5310 && commonExpr->isOrdinaryOrBitFieldObject()
5311 && RHSExpr->isOrdinaryOrBitFieldObject()
5312 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005313 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5314 if (commonRes.isInvalid())
5315 return ExprError();
5316 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00005317 }
5318
5319 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5320 commonExpr->getType(),
5321 commonExpr->getValueKind(),
Douglas Gregor2d5aea02012-02-23 22:17:26 +00005322 commonExpr->getObjectKind(),
5323 commonExpr);
John McCallc07a0c72011-02-17 10:25:35 +00005324 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005325 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005326
John McCall7decc9e2010-11-18 06:31:45 +00005327 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005328 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005329 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5330 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005331 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005332 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5333 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005334 return ExprError();
5335
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005336 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5337 RHS.get());
5338
John McCallc07a0c72011-02-17 10:25:35 +00005339 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005340 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5341 LHS.take(), ColonLoc,
5342 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005343
5344 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005345 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005346 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5347 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005348}
5349
John McCallaba90822011-01-31 23:13:11 +00005350// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005351// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005352// routine is it effectively iqnores the qualifiers on the top level pointee.
5353// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5354// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005355static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005356checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5357 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5358 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005359
Steve Naroff1f4d7272007-05-11 04:00:31 +00005360 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005361 const Type *lhptee, *rhptee;
5362 Qualifiers lhq, rhq;
Richard Trieua871b972011-09-06 20:21:22 +00005363 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5364 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005365
John McCallaba90822011-01-31 23:13:11 +00005366 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005367
5368 // C99 6.5.16.1p1: This following citation is common to constraints
5369 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5370 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005371 Qualifiers lq;
5372
John McCall31168b02011-06-15 23:02:42 +00005373 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5374 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5375 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5376 // Ignore lifetime for further calculation.
5377 lhq.removeObjCLifetime();
5378 rhq.removeObjCLifetime();
5379 }
5380
John McCall4fff8f62011-02-01 00:10:29 +00005381 if (!lhq.compatiblyIncludes(rhq)) {
5382 // Treat address-space mismatches as fatal. TODO: address subspaces
5383 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5384 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5385
John McCall31168b02011-06-15 23:02:42 +00005386 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005387 // and from void*.
John McCall18ce25e2012-02-08 00:46:36 +00005388 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCall31168b02011-06-15 23:02:42 +00005389 .compatiblyIncludes(
John McCall18ce25e2012-02-08 00:46:36 +00005390 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall78535952011-03-26 02:56:45 +00005391 && (lhptee->isVoidType() || rhptee->isVoidType()))
5392 ; // keep old
5393
John McCall31168b02011-06-15 23:02:42 +00005394 // Treat lifetime mismatches as fatal.
5395 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5396 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5397
John McCall4fff8f62011-02-01 00:10:29 +00005398 // For GCC compatibility, other qualifier mismatches are treated
5399 // as still compatible in C.
5400 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5401 }
Steve Naroff3f597292007-05-11 22:18:03 +00005402
Mike Stump4e1f26a2009-02-19 03:04:26 +00005403 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5404 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005405 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005406 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005407 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005408 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005409
Chris Lattner0a788432008-01-03 22:56:36 +00005410 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005411 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005412 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005413 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005414
Chris Lattner0a788432008-01-03 22:56:36 +00005415 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005416 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005417 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005418
5419 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005420 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005421 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005422 }
John McCall4fff8f62011-02-01 00:10:29 +00005423
Mike Stump4e1f26a2009-02-19 03:04:26 +00005424 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005425 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005426 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5427 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005428 // Check if the pointee types are compatible ignoring the sign.
5429 // We explicitly check for char so that we catch "char" vs
5430 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005431 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005432 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005433 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005434 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005435
Chris Lattnerec3a1562009-10-17 20:33:28 +00005436 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005437 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005438 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005439 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005440
John McCall4fff8f62011-02-01 00:10:29 +00005441 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005442 // Types are compatible ignoring the sign. Qualifier incompatibility
5443 // takes priority over sign incompatibility because the sign
5444 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005445 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005446 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005447
John McCallaba90822011-01-31 23:13:11 +00005448 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005449 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005450
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005451 // If we are a multi-level pointer, it's possible that our issue is simply
5452 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5453 // the eventual target type is the same and the pointers have the same
5454 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005455 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005456 do {
John McCall4fff8f62011-02-01 00:10:29 +00005457 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5458 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005459 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005460
John McCall4fff8f62011-02-01 00:10:29 +00005461 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005462 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005463 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005464
Eli Friedman80160bd2009-03-22 23:59:44 +00005465 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005466 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005467 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00005468 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005469 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5470 return Sema::IncompatiblePointer;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005471 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005472}
5473
John McCallaba90822011-01-31 23:13:11 +00005474/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005475/// block pointer types are compatible or whether a block and normal pointer
5476/// are compatible. It is more restrict than comparing two function pointer
5477// types.
John McCallaba90822011-01-31 23:13:11 +00005478static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005479checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5480 QualType RHSType) {
5481 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5482 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005483
Steve Naroff081c7422008-09-04 15:10:53 +00005484 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005485
Steve Naroff081c7422008-09-04 15:10:53 +00005486 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00005487 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5488 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005489
John McCallaba90822011-01-31 23:13:11 +00005490 // In C++, the types have to match exactly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005491 if (S.getLangOpts().CPlusPlus)
John McCallaba90822011-01-31 23:13:11 +00005492 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005493
John McCallaba90822011-01-31 23:13:11 +00005494 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005495
Steve Naroff081c7422008-09-04 15:10:53 +00005496 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005497 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5498 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005499
Richard Trieua871b972011-09-06 20:21:22 +00005500 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005501 return Sema::IncompatibleBlockPointer;
5502
Steve Naroff081c7422008-09-04 15:10:53 +00005503 return ConvTy;
5504}
5505
John McCallaba90822011-01-31 23:13:11 +00005506/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005507/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005508static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005509checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5510 QualType RHSType) {
5511 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5512 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005513
Richard Trieua871b972011-09-06 20:21:22 +00005514 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005515 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00005516 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5517 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005518 return Sema::IncompatiblePointer;
5519 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005520 }
Richard Trieua871b972011-09-06 20:21:22 +00005521 if (RHSType->isObjCBuiltinType()) {
Richard Trieua871b972011-09-06 20:21:22 +00005522 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5523 !LHSType->isObjCQualifiedClassType())
Fariborz Jahaniand923eb02011-09-15 20:40:18 +00005524 return Sema::IncompatiblePointer;
John McCallaba90822011-01-31 23:13:11 +00005525 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005526 }
Richard Trieua871b972011-09-06 20:21:22 +00005527 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5528 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005529
Fariborz Jahaniane74d47e2012-01-12 22:12:08 +00005530 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5531 // make an exception for id<P>
5532 !LHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005533 return Sema::CompatiblePointerDiscardsQualifiers;
5534
Richard Trieua871b972011-09-06 20:21:22 +00005535 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005536 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00005537 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005538 return Sema::IncompatibleObjCQualifiedId;
5539 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005540}
5541
John McCall29600e12010-11-16 02:32:08 +00005542Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005543Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00005544 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00005545 // Fake up an opaque expression. We don't actually care about what
5546 // cast operations are required, so if CheckAssignmentConstraints
5547 // adds casts to this they'll be wasted, but fortunately that doesn't
5548 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00005549 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5550 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00005551 CastKind K = CK_Invalid;
5552
Richard Trieua871b972011-09-06 20:21:22 +00005553 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall29600e12010-11-16 02:32:08 +00005554}
5555
Mike Stump4e1f26a2009-02-19 03:04:26 +00005556/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5557/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005558/// pointers. Here are some objectionable examples that GCC considers warnings:
5559///
5560/// int a, *pint;
5561/// short *pshort;
5562/// struct foo *pfoo;
5563///
5564/// pint = pshort; // warning: assignment from incompatible pointer type
5565/// a = pint; // warning: assignment makes integer from pointer without a cast
5566/// pint = a; // warning: assignment makes pointer from integer without a cast
5567/// pint = pfoo; // warning: assignment from incompatible pointer type
5568///
5569/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005570/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005571///
John McCall8cb679e2010-11-15 09:13:47 +00005572/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005573Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00005574Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCall8cb679e2010-11-15 09:13:47 +00005575 CastKind &Kind) {
Richard Trieude4958f2011-09-06 20:30:53 +00005576 QualType RHSType = RHS.get()->getType();
5577 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00005578
Chris Lattnera52c2f22008-01-04 23:18:45 +00005579 // Get canonical types. We're not formatting these types, just comparing
5580 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00005581 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5582 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005583
Eli Friedman0dfb8892011-10-06 23:00:33 +00005584
John McCalle5255932011-01-31 22:28:28 +00005585 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00005586 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00005587 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005588 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005589 }
5590
Eli Friedman93ee5ca2012-06-16 02:19:17 +00005591 // If we have an atomic type, try a non-atomic assignment, then just add an
5592 // atomic qualification step.
David Chisnallfa35df62012-01-16 17:27:18 +00005593 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman93ee5ca2012-06-16 02:19:17 +00005594 Sema::AssignConvertType result =
5595 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5596 if (result != Compatible)
5597 return result;
5598 if (Kind != CK_NoOp)
5599 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5600 Kind = CK_NonAtomicToAtomic;
5601 return Compatible;
David Chisnallfa35df62012-01-16 17:27:18 +00005602 }
5603
Douglas Gregor6b754842008-10-28 00:22:11 +00005604 // If the left-hand side is a reference type, then we are in a
5605 // (rare!) case where we've allowed the use of references in C,
5606 // e.g., as a parameter type in a built-in function. In this case,
5607 // just make sure that the type referenced is compatible with the
5608 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00005609 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00005610 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00005611 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5612 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005613 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005614 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005615 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005616 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005617 }
John McCalle5255932011-01-31 22:28:28 +00005618
Nate Begemanbd956c42009-06-28 02:36:38 +00005619 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5620 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005621 if (LHSType->isExtVectorType()) {
5622 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005623 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00005624 if (RHSType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005625 // CK_VectorSplat does T -> vector T, so first cast to the
5626 // element type.
Richard Trieude4958f2011-09-06 20:30:53 +00005627 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5628 if (elType != RHSType) {
John McCall9776e432011-10-06 23:25:11 +00005629 Kind = PrepareScalarCast(RHS, elType);
Richard Trieude4958f2011-09-06 20:30:53 +00005630 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005631 }
5632 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005633 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005634 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005635 }
Mike Stump11289f42009-09-09 15:08:12 +00005636
John McCalle5255932011-01-31 22:28:28 +00005637 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005638 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5639 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005640 // Allow assignments of an AltiVec vector type to an equivalent GCC
5641 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00005642 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00005643 Kind = CK_BitCast;
5644 return Compatible;
5645 }
5646
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005647 // If we are allowing lax vector conversions, and LHS and RHS are both
5648 // vectors, the total size only needs to be the same. This is a bitcast;
5649 // no bits are changed but the result type is different.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005650 if (getLangOpts().LaxVectorConversions &&
Richard Trieude4958f2011-09-06 20:30:53 +00005651 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall3065d042010-11-15 10:08:00 +00005652 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005653 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005654 }
Chris Lattner881a2122008-01-04 23:32:24 +00005655 }
5656 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005657 }
Eli Friedman3360d892008-05-30 18:07:22 +00005658
John McCalle5255932011-01-31 22:28:28 +00005659 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00005660 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00005661 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCall9776e432011-10-06 23:25:11 +00005662 Kind = PrepareScalarCast(RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005663 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005664 }
Eli Friedman3360d892008-05-30 18:07:22 +00005665
John McCalle5255932011-01-31 22:28:28 +00005666 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005667 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005668 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005669 if (isa<PointerType>(RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005670 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005671 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005672 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005673
John McCalle5255932011-01-31 22:28:28 +00005674 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005675 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00005676 Kind = CK_IntegralToPointer; // FIXME: null?
5677 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005678 }
John McCalle5255932011-01-31 22:28:28 +00005679
5680 // C pointers are not compatible with ObjC object pointers,
5681 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005682 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005683 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00005684 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall9320b872011-09-09 05:25:32 +00005685 Kind = CK_BitCast;
John McCalle5255932011-01-31 22:28:28 +00005686 return Compatible;
5687 }
5688
5689 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005690 if (RHSType->isObjCClassType() &&
5691 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005692 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00005693 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005694 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005695 }
Douglas Gregor486b74e2011-09-27 16:10:05 +00005696
John McCalle5255932011-01-31 22:28:28 +00005697 Kind = CK_BitCast;
5698 return IncompatiblePointer;
5699 }
5700
5701 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00005702 if (RHSType->getAs<BlockPointerType>()) {
5703 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00005704 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005705 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005706 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005707 }
John McCalle5255932011-01-31 22:28:28 +00005708
Steve Naroff081c7422008-09-04 15:10:53 +00005709 return Incompatible;
5710 }
5711
John McCalle5255932011-01-31 22:28:28 +00005712 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005713 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005714 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005715 if (RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00005716 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005717 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00005718 }
5719
5720 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005721 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005722 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005723 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005724 }
5725
John McCalle5255932011-01-31 22:28:28 +00005726 // id -> T^
David Blaikiebbafb8a2012-03-11 07:00:24 +00005727 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00005728 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005729 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005730 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005731
John McCalle5255932011-01-31 22:28:28 +00005732 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005733 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005734 if (RHSPT->getPointeeType()->isVoidType()) {
5735 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005736 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005737 }
John McCall8cb679e2010-11-15 09:13:47 +00005738
Chris Lattnera52c2f22008-01-04 23:18:45 +00005739 return Incompatible;
5740 }
5741
John McCalle5255932011-01-31 22:28:28 +00005742 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005743 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005744 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00005745 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00005746 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005747 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00005748 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikiebbafb8a2012-03-11 07:00:24 +00005749 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005750 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00005751 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005752 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005753 return result;
John McCalle5255932011-01-31 22:28:28 +00005754 }
5755
5756 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005757 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005758 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005759 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005760 }
5761
John McCalle5255932011-01-31 22:28:28 +00005762 // In general, C pointers are not compatible with ObjC object pointers,
5763 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005764 if (isa<PointerType>(RHSType)) {
John McCall9320b872011-09-09 05:25:32 +00005765 Kind = CK_CPointerToObjCPointerCast;
5766
John McCalle5255932011-01-31 22:28:28 +00005767 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00005768 if (RHSType->isVoidPointerType()) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005769 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005770 }
5771
5772 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005773 if (LHSType->isObjCClassType() &&
5774 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005775 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00005776 return Compatible;
5777 }
5778
Steve Naroffaccc4882009-07-20 17:56:53 +00005779 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005780 }
John McCalle5255932011-01-31 22:28:28 +00005781
5782 // T^ -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005783 if (RHSType->isBlockPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00005784 maybeExtendBlockObject(*this, RHS);
John McCall9320b872011-09-09 05:25:32 +00005785 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005786 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005787 }
5788
Steve Naroff7cae42b2009-07-10 23:34:53 +00005789 return Incompatible;
5790 }
John McCalle5255932011-01-31 22:28:28 +00005791
5792 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005793 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005794 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005795 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005796 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005797 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005798 }
Eli Friedman3360d892008-05-30 18:07:22 +00005799
John McCalle5255932011-01-31 22:28:28 +00005800 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005801 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005802 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005803 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005804 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005805
Chris Lattnera52c2f22008-01-04 23:18:45 +00005806 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005807 }
John McCalle5255932011-01-31 22:28:28 +00005808
5809 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005810 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005811 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005812 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005813 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005814 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005815 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005816
John McCalle5255932011-01-31 22:28:28 +00005817 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005818 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005819 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005820 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005821 }
5822
Steve Naroff7cae42b2009-07-10 23:34:53 +00005823 return Incompatible;
5824 }
Eli Friedman3360d892008-05-30 18:07:22 +00005825
John McCalle5255932011-01-31 22:28:28 +00005826 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00005827 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5828 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005829 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005830 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005831 }
Bill Wendling216423b2007-05-30 06:30:29 +00005832 }
John McCalle5255932011-01-31 22:28:28 +00005833
Steve Naroff98cf3e92007-06-06 18:38:38 +00005834 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005835}
5836
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005837/// \brief Constructs a transparent union from an expression that is
5838/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005839static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5840 ExprResult &EResult, QualType UnionType,
5841 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005842 // Build an initializer list that designates the appropriate member
5843 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005844 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005845 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00005846 E, SourceLocation());
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005847 Initializer->setType(UnionType);
5848 Initializer->setInitializedFieldInUnion(Field);
5849
5850 // Build a compound literal constructing a value of the transparent
5851 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005852 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005853 EResult = S.Owned(
5854 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5855 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005856}
5857
5858Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005859Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00005860 ExprResult &RHS) {
5861 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005862
Mike Stump11289f42009-09-09 15:08:12 +00005863 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005864 // transparent_union GCC extension.
5865 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005866 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005867 return Incompatible;
5868
5869 // The field to initialize within the transparent union.
5870 RecordDecl *UD = UT->getDecl();
5871 FieldDecl *InitField = 0;
5872 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005873 for (RecordDecl::field_iterator it = UD->field_begin(),
5874 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005875 it != itend; ++it) {
5876 if (it->getType()->isPointerType()) {
5877 // If the transparent union contains a pointer type, we allow:
5878 // 1) void pointer
5879 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00005880 if (RHSType->isPointerType())
John McCall9320b872011-09-09 05:25:32 +00005881 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieueb299142011-09-06 20:40:12 +00005882 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie40ed2972012-06-06 20:45:41 +00005883 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005884 break;
5885 }
Mike Stump11289f42009-09-09 15:08:12 +00005886
Richard Trieueb299142011-09-06 20:40:12 +00005887 if (RHS.get()->isNullPointerConstant(Context,
5888 Expr::NPC_ValueDependentIsNull)) {
5889 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5890 CK_NullToPointer);
David Blaikie40ed2972012-06-06 20:45:41 +00005891 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005892 break;
5893 }
5894 }
5895
John McCall8cb679e2010-11-15 09:13:47 +00005896 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00005897 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005898 == Compatible) {
Richard Trieueb299142011-09-06 20:40:12 +00005899 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie40ed2972012-06-06 20:45:41 +00005900 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005901 break;
5902 }
5903 }
5904
5905 if (!InitField)
5906 return Incompatible;
5907
Richard Trieueb299142011-09-06 20:40:12 +00005908 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005909 return Compatible;
5910}
5911
Chris Lattner9bad62c2008-01-04 18:04:52 +00005912Sema::AssignConvertType
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005913Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5914 bool Diagnose) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005915 if (getLangOpts().CPlusPlus) {
Eli Friedman0dfb8892011-10-06 23:00:33 +00005916 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005917 // C++ 5.17p3: If the left operand is not of class type, the
5918 // expression is implicitly converted (C++ 4) to the
5919 // cv-unqualified type of the left operand.
Sebastian Redlcc152642011-10-16 18:19:06 +00005920 ExprResult Res;
5921 if (Diagnose) {
5922 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5923 AA_Assigning);
5924 } else {
5925 ImplicitConversionSequence ICS =
5926 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5927 /*SuppressUserConversions=*/false,
5928 /*AllowExplicit=*/false,
5929 /*InOverloadResolution=*/false,
5930 /*CStyle=*/false,
5931 /*AllowObjCWritebackConversion=*/false);
5932 if (ICS.isFailure())
5933 return Incompatible;
5934 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5935 ICS, AA_Assigning);
5936 }
John Wiegley01296292011-04-08 18:41:53 +00005937 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005938 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005939 Sema::AssignConvertType result = Compatible;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005940 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieueb299142011-09-06 20:40:12 +00005941 !CheckObjCARCUnavailableWeakConversion(LHSType,
5942 RHS.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005943 result = IncompatibleObjCWeakRef;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005944 RHS = Res;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005945 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005946 }
5947
5948 // FIXME: Currently, we fall through and treat C++ classes like C
5949 // structures.
Eli Friedman0dfb8892011-10-06 23:00:33 +00005950 // FIXME: We also fall through for atomics; not sure what should
5951 // happen there, though.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005952 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005953
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005954 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5955 // a null pointer constant.
Richard Trieueb299142011-09-06 20:40:12 +00005956 if ((LHSType->isPointerType() ||
5957 LHSType->isObjCObjectPointerType() ||
5958 LHSType->isBlockPointerType())
5959 && RHS.get()->isNullPointerConstant(Context,
5960 Expr::NPC_ValueDependentIsNull)) {
5961 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005962 return Compatible;
5963 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005964
Chris Lattnere6dcd502007-10-16 02:55:40 +00005965 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005966 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005967 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005968 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005969 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005970 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00005971 if (!LHSType->isReferenceType()) {
5972 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5973 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005974 return Incompatible;
5975 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005976
John McCall8cb679e2010-11-15 09:13:47 +00005977 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005978 Sema::AssignConvertType result =
Richard Trieueb299142011-09-06 20:40:12 +00005979 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005980
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005981 // C99 6.5.16.1p2: The value of the right operand is converted to the
5982 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005983 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5984 // so that we can use references in built-in functions even in C.
5985 // The getNonReferenceType() call makes sure that the resulting expression
5986 // does not have reference type.
Richard Trieueb299142011-09-06 20:40:12 +00005987 if (result != Incompatible && RHS.get()->getType() != LHSType)
5988 RHS = ImpCastExprToType(RHS.take(),
5989 LHSType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005990 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005991}
5992
Richard Trieueb299142011-09-06 20:40:12 +00005993QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5994 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005995 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00005996 << LHS.get()->getType() << RHS.get()->getType()
5997 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005998 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005999}
6000
Richard Trieu859d23f2011-09-06 21:01:04 +00006001QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006002 SourceLocation Loc, bool IsCompAssign) {
Richard Smith508ebf32011-10-28 03:31:48 +00006003 if (!IsCompAssign) {
6004 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6005 if (LHS.isInvalid())
6006 return QualType();
6007 }
6008 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6009 if (RHS.isInvalid())
6010 return QualType();
6011
Mike Stump4e1f26a2009-02-19 03:04:26 +00006012 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006013 // For example, "const float" and "float" are equivalent.
Richard Trieu859d23f2011-09-06 21:01:04 +00006014 QualType LHSType =
6015 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6016 QualType RHSType =
6017 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006018
Nate Begeman191a6b12008-07-14 18:02:46 +00006019 // If the vector types are identical, return.
Richard Trieu859d23f2011-09-06 21:01:04 +00006020 if (LHSType == RHSType)
6021 return LHSType;
Nate Begeman330aaa72007-12-30 02:59:45 +00006022
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006023 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu859d23f2011-09-06 21:01:04 +00006024 if (LHSType->isVectorType() && RHSType->isVectorType() &&
6025 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6026 if (LHSType->isExtVectorType()) {
6027 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6028 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00006029 }
6030
Richard Trieuba63ce62011-09-09 01:45:06 +00006031 if (!IsCompAssign)
Richard Trieu859d23f2011-09-06 21:01:04 +00006032 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6033 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006034 }
6035
David Blaikiebbafb8a2012-03-11 07:00:24 +00006036 if (getLangOpts().LaxVectorConversions &&
Richard Trieu859d23f2011-09-06 21:01:04 +00006037 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00006038 // If we are allowing lax vector conversions, and LHS and RHS are both
6039 // vectors, the total size only needs to be the same. This is a
6040 // bitcast; no bits are changed but the result type is different.
6041 // FIXME: Should we really be allowing this?
Richard Trieu859d23f2011-09-06 21:01:04 +00006042 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6043 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00006044 }
6045
Nate Begemanbd956c42009-06-28 02:36:38 +00006046 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6047 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6048 bool swapped = false;
Richard Trieuba63ce62011-09-09 01:45:06 +00006049 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006050 swapped = true;
Richard Trieu859d23f2011-09-06 21:01:04 +00006051 std::swap(RHS, LHS);
6052 std::swap(RHSType, LHSType);
Nate Begemanbd956c42009-06-28 02:36:38 +00006053 }
Mike Stump11289f42009-09-09 15:08:12 +00006054
Nate Begeman886448d2009-06-28 19:12:57 +00006055 // Handle the case of an ext vector and scalar.
Richard Trieu859d23f2011-09-06 21:01:04 +00006056 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006057 QualType EltTy = LV->getElementType();
Richard Trieu859d23f2011-09-06 21:01:04 +00006058 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6059 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00006060 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00006061 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00006062 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00006063 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6064 if (swapped) std::swap(RHS, LHS);
6065 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00006066 }
6067 }
Richard Trieu859d23f2011-09-06 21:01:04 +00006068 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6069 RHSType->isRealFloatingType()) {
6070 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00006071 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00006072 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00006073 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00006074 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6075 if (swapped) std::swap(RHS, LHS);
6076 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00006077 }
Nate Begeman330aaa72007-12-30 02:59:45 +00006078 }
6079 }
Mike Stump11289f42009-09-09 15:08:12 +00006080
Nate Begeman886448d2009-06-28 19:12:57 +00006081 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu859d23f2011-09-06 21:01:04 +00006082 if (swapped) std::swap(RHS, LHS);
Chris Lattner377d1f82008-11-18 22:52:51 +00006083 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu859d23f2011-09-06 21:01:04 +00006084 << LHS.get()->getType() << RHS.get()->getType()
6085 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00006086 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00006087}
6088
Richard Trieuf8916e12011-09-16 00:53:10 +00006089// checkArithmeticNull - Detect when a NULL constant is used improperly in an
6090// expression. These are mainly cases where the null pointer is used as an
6091// integer instead of a pointer.
6092static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6093 SourceLocation Loc, bool IsCompare) {
6094 // The canonical way to check for a GNU null is with isNullPointerConstant,
6095 // but we use a bit of a hack here for speed; this is a relatively
6096 // hot path, and isNullPointerConstant is slow.
6097 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6098 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6099
6100 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6101
6102 // Avoid analyzing cases where the result will either be invalid (and
6103 // diagnosed as such) or entirely valid and not something to warn about.
6104 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6105 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6106 return;
6107
6108 // Comparison operations would not make sense with a null pointer no matter
6109 // what the other expression is.
6110 if (!IsCompare) {
6111 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6112 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6113 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6114 return;
6115 }
6116
6117 // The rest of the operations only make sense with a null pointer
6118 // if the other expression is a pointer.
6119 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6120 NonNullType->canDecayToPointerType())
6121 return;
6122
6123 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6124 << LHSNull /* LHS is NULL */ << NonNullType
6125 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6126}
6127
Richard Trieu859d23f2011-09-06 21:01:04 +00006128QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006129 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006130 bool IsCompAssign, bool IsDiv) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006131 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6132
Richard Trieu859d23f2011-09-06 21:01:04 +00006133 if (LHS.get()->getType()->isVectorType() ||
6134 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006135 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006136
Richard Trieuba63ce62011-09-09 01:45:06 +00006137 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006138 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006139 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006140
David Chisnallfa35df62012-01-16 17:27:18 +00006141
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006142 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu859d23f2011-09-06 21:01:04 +00006143 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006144
Chris Lattnerfaa54172010-01-12 21:23:57 +00006145 // Check for division by zero.
Richard Trieuba63ce62011-09-09 01:45:06 +00006146 if (IsDiv &&
Richard Trieu859d23f2011-09-06 21:01:04 +00006147 RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00006148 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00006149 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6150 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006151
Chris Lattnerfaa54172010-01-12 21:23:57 +00006152 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006153}
6154
Chris Lattnerfaa54172010-01-12 21:23:57 +00006155QualType Sema::CheckRemainderOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00006156 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006157 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6158
Richard Trieu859d23f2011-09-06 21:01:04 +00006159 if (LHS.get()->getType()->isVectorType() ||
6160 RHS.get()->getType()->isVectorType()) {
6161 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6162 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00006163 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006164 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006165 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006166
Richard Trieuba63ce62011-09-09 01:45:06 +00006167 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006168 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006169 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006170
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006171 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu859d23f2011-09-06 21:01:04 +00006172 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006173
Chris Lattnerfaa54172010-01-12 21:23:57 +00006174 // Check for remainder by zero.
Richard Trieu859d23f2011-09-06 21:01:04 +00006175 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00006176 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00006177 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6178 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006179
Chris Lattnerfaa54172010-01-12 21:23:57 +00006180 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006181}
6182
Chandler Carruthc9332212011-06-27 08:02:19 +00006183/// \brief Diagnose invalid arithmetic on two void pointers.
6184static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006185 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006186 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006187 ? diag::err_typecheck_pointer_arith_void_type
6188 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006189 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6190 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00006191}
6192
6193/// \brief Diagnose invalid arithmetic on a void pointer.
6194static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6195 Expr *Pointer) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006196 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006197 ? diag::err_typecheck_pointer_arith_void_type
6198 : diag::ext_gnu_void_ptr)
6199 << 0 /* one pointer */ << Pointer->getSourceRange();
6200}
6201
6202/// \brief Diagnose invalid arithmetic on two function pointers.
6203static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6204 Expr *LHS, Expr *RHS) {
6205 assert(LHS->getType()->isAnyPointerType());
6206 assert(RHS->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006207 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006208 ? diag::err_typecheck_pointer_arith_function_type
6209 : diag::ext_gnu_ptr_func_arith)
6210 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6211 // We only show the second type if it differs from the first.
6212 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6213 RHS->getType())
6214 << RHS->getType()->getPointeeType()
6215 << LHS->getSourceRange() << RHS->getSourceRange();
6216}
6217
6218/// \brief Diagnose invalid arithmetic on a function pointer.
6219static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6220 Expr *Pointer) {
6221 assert(Pointer->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006222 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006223 ? diag::err_typecheck_pointer_arith_function_type
6224 : diag::ext_gnu_ptr_func_arith)
6225 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6226 << 0 /* one pointer, so only one type */
6227 << Pointer->getSourceRange();
6228}
6229
Richard Trieu993f3ab2011-09-12 18:08:02 +00006230/// \brief Emit error if Operand is incomplete pointer type
Richard Trieuaba22802011-09-02 02:15:37 +00006231///
6232/// \returns True if pointer has incomplete type
6233static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6234 Expr *Operand) {
John McCallf2538342012-07-31 05:14:30 +00006235 assert(Operand->getType()->isAnyPointerType() &&
6236 !Operand->getType()->isDependentType());
6237 QualType PointeeTy = Operand->getType()->getPointeeType();
6238 return S.RequireCompleteType(Loc, PointeeTy,
6239 diag::err_typecheck_arithmetic_incomplete_type,
6240 PointeeTy, Operand->getSourceRange());
Richard Trieuaba22802011-09-02 02:15:37 +00006241}
6242
Chandler Carruthc9332212011-06-27 08:02:19 +00006243/// \brief Check the validity of an arithmetic pointer operand.
6244///
6245/// If the operand has pointer type, this code will check for pointer types
6246/// which are invalid in arithmetic operations. These will be diagnosed
6247/// appropriately, including whether or not the use is supported as an
6248/// extension.
6249///
6250/// \returns True when the operand is valid to use (even if as an extension).
6251static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6252 Expr *Operand) {
6253 if (!Operand->getType()->isAnyPointerType()) return true;
6254
6255 QualType PointeeTy = Operand->getType()->getPointeeType();
6256 if (PointeeTy->isVoidType()) {
6257 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00006258 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006259 }
6260 if (PointeeTy->isFunctionType()) {
6261 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00006262 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006263 }
6264
Richard Trieuaba22802011-09-02 02:15:37 +00006265 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00006266
6267 return true;
6268}
6269
6270/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6271/// operands.
6272///
6273/// This routine will diagnose any invalid arithmetic on pointer operands much
6274/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6275/// for emitting a single diagnostic even for operations where both LHS and RHS
6276/// are (potentially problematic) pointers.
6277///
6278/// \returns True when the operand is valid to use (even if as an extension).
6279static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006280 Expr *LHSExpr, Expr *RHSExpr) {
6281 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6282 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006283 if (!isLHSPointer && !isRHSPointer) return true;
6284
6285 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00006286 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6287 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006288
6289 // Check for arithmetic on pointers to incomplete types.
6290 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6291 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6292 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006293 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6294 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6295 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006296
David Blaikiebbafb8a2012-03-11 07:00:24 +00006297 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006298 }
6299
6300 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6301 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6302 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006303 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6304 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6305 RHSExpr);
6306 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006307
David Blaikiebbafb8a2012-03-11 07:00:24 +00006308 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006309 }
6310
John McCallf2538342012-07-31 05:14:30 +00006311 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6312 return false;
6313 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6314 return false;
Richard Trieuaba22802011-09-02 02:15:37 +00006315
Chandler Carruthc9332212011-06-27 08:02:19 +00006316 return true;
6317}
6318
Nico Weberccec40d2012-03-02 22:01:22 +00006319/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6320/// literal.
6321static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6322 Expr *LHSExpr, Expr *RHSExpr) {
6323 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6324 Expr* IndexExpr = RHSExpr;
6325 if (!StrExpr) {
6326 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6327 IndexExpr = LHSExpr;
6328 }
6329
6330 bool IsStringPlusInt = StrExpr &&
6331 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6332 if (!IsStringPlusInt)
6333 return;
6334
6335 llvm::APSInt index;
6336 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6337 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6338 if (index.isNonNegative() &&
6339 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6340 index.isUnsigned()))
6341 return;
6342 }
6343
6344 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6345 Self.Diag(OpLoc, diag::warn_string_plus_int)
6346 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6347
6348 // Only print a fixit for "str" + int, not for int + "str".
6349 if (IndexExpr == RHSExpr) {
6350 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6351 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6352 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6353 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6354 << FixItHint::CreateInsertion(EndLoc, "]");
6355 } else
6356 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6357}
6358
Richard Trieu993f3ab2011-09-12 18:08:02 +00006359/// \brief Emit error when two pointers are incompatible.
Richard Trieub10c6312011-09-01 22:53:23 +00006360static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006361 Expr *LHSExpr, Expr *RHSExpr) {
6362 assert(LHSExpr->getType()->isAnyPointerType());
6363 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00006364 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006365 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6366 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00006367}
6368
Chris Lattnerfaa54172010-01-12 21:23:57 +00006369QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weberccec40d2012-03-02 22:01:22 +00006370 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6371 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006372 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6373
Richard Trieu4ae7e972011-09-06 21:13:51 +00006374 if (LHS.get()->getType()->isVectorType() ||
6375 RHS.get()->getType()->isVectorType()) {
6376 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006377 if (CompLHSTy) *CompLHSTy = compType;
6378 return compType;
6379 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006380
Richard Trieu4ae7e972011-09-06 21:13:51 +00006381 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6382 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006383 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006384
Nico Weberccec40d2012-03-02 22:01:22 +00006385 // Diagnose "string literal" '+' int.
6386 if (Opc == BO_Add)
6387 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6388
Steve Naroffe4718892007-04-27 18:30:00 +00006389 // handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006390 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006391 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006392 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006393 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006394
John McCallf2538342012-07-31 05:14:30 +00006395 // Type-checking. Ultimately the pointer's going to be in PExp;
6396 // note that we bias towards the LHS being the pointer.
6397 Expr *PExp = LHS.get(), *IExp = RHS.get();
Eli Friedman8e122982008-05-18 18:08:51 +00006398
John McCallf2538342012-07-31 05:14:30 +00006399 bool isObjCPointer;
6400 if (PExp->getType()->isPointerType()) {
6401 isObjCPointer = false;
6402 } else if (PExp->getType()->isObjCObjectPointerType()) {
6403 isObjCPointer = true;
6404 } else {
6405 std::swap(PExp, IExp);
6406 if (PExp->getType()->isPointerType()) {
6407 isObjCPointer = false;
6408 } else if (PExp->getType()->isObjCObjectPointerType()) {
6409 isObjCPointer = true;
6410 } else {
6411 return InvalidOperands(Loc, LHS, RHS);
6412 }
6413 }
6414 assert(PExp->getType()->isAnyPointerType());
Chandler Carruthc9332212011-06-27 08:02:19 +00006415
Richard Trieub420bca2011-09-12 18:37:54 +00006416 if (!IExp->getType()->isIntegerType())
6417 return InvalidOperands(Loc, LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006418
Richard Trieub420bca2011-09-12 18:37:54 +00006419 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6420 return QualType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006421
John McCallf2538342012-07-31 05:14:30 +00006422 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
Richard Trieub420bca2011-09-12 18:37:54 +00006423 return QualType();
6424
6425 // Check array bounds for pointer arithemtic
6426 CheckArrayAccess(PExp, IExp);
6427
6428 if (CompLHSTy) {
6429 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6430 if (LHSTy.isNull()) {
6431 LHSTy = LHS.get()->getType();
6432 if (LHSTy->isPromotableIntegerType())
6433 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006434 }
Richard Trieub420bca2011-09-12 18:37:54 +00006435 *CompLHSTy = LHSTy;
Eli Friedman8e122982008-05-18 18:08:51 +00006436 }
6437
Richard Trieub420bca2011-09-12 18:37:54 +00006438 return PExp->getType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00006439}
6440
Chris Lattner2a3569b2008-04-07 05:30:13 +00006441// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006442QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006443 SourceLocation Loc,
6444 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006445 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6446
Richard Trieu4ae7e972011-09-06 21:13:51 +00006447 if (LHS.get()->getType()->isVectorType() ||
6448 RHS.get()->getType()->isVectorType()) {
6449 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006450 if (CompLHSTy) *CompLHSTy = compType;
6451 return compType;
6452 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006453
Richard Trieu4ae7e972011-09-06 21:13:51 +00006454 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6455 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006456 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006457
Chris Lattner4d62f422007-12-09 21:53:25 +00006458 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006459
Chris Lattner4d62f422007-12-09 21:53:25 +00006460 // Handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006461 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006462 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006463 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006464 }
Mike Stump11289f42009-09-09 15:08:12 +00006465
Chris Lattner4d62f422007-12-09 21:53:25 +00006466 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006467 if (LHS.get()->getType()->isAnyPointerType()) {
6468 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006469
Chris Lattner12bdebb2009-04-24 23:50:08 +00006470 // Diagnose bad cases where we step over interface counts.
John McCallf2538342012-07-31 05:14:30 +00006471 if (LHS.get()->getType()->isObjCObjectPointerType() &&
6472 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00006473 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006474
Chris Lattner4d62f422007-12-09 21:53:25 +00006475 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006476 if (RHS.get()->getType()->isIntegerType()) {
6477 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006478 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006479
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006480 // Check array bounds for pointer arithemtic
Richard Smith13f67182011-12-16 19:31:14 +00006481 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6482 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006483
Richard Trieu4ae7e972011-09-06 21:13:51 +00006484 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6485 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006486 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006487
Chris Lattner4d62f422007-12-09 21:53:25 +00006488 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006489 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00006490 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006491 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006492
David Blaikiebbafb8a2012-03-11 07:00:24 +00006493 if (getLangOpts().CPlusPlus) {
Eli Friedman168fe152009-05-16 13:54:38 +00006494 // Pointee types must be the same: C++ [expr.add]
6495 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006496 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006497 }
6498 } else {
6499 // Pointee types must be compatible C99 6.5.6p3
6500 if (!Context.typesAreCompatible(
6501 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6502 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006503 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006504 return QualType();
6505 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006506 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006507
Chandler Carruthc9332212011-06-27 08:02:19 +00006508 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006509 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006510 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006511
Richard Trieu4ae7e972011-09-06 21:13:51 +00006512 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006513 return Context.getPointerDiffType();
6514 }
6515 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006516
Richard Trieu4ae7e972011-09-06 21:13:51 +00006517 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006518}
6519
Douglas Gregor0bf31402010-10-08 23:50:27 +00006520static bool isScopedEnumerationType(QualType T) {
6521 if (const EnumType *ET = dyn_cast<EnumType>(T))
6522 return ET->getDecl()->isScoped();
6523 return false;
6524}
6525
Richard Trieue4a19fb2011-09-06 21:21:28 +00006526static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006527 SourceLocation Loc, unsigned Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00006528 QualType LHSType) {
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006529 llvm::APSInt Right;
6530 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00006531 if (RHS.get()->isValueDependent() ||
6532 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006533 return;
6534
6535 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006536 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006537 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006538 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006539 return;
6540 }
6541 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00006542 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006543 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006544 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006545 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006546 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006547 return;
6548 }
6549 if (Opc != BO_Shl)
6550 return;
6551
6552 // When left shifting an ICE which is signed, we can check for overflow which
6553 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6554 // integers have defined behavior modulo one more than the maximum value
6555 // representable in the result type, so never warn for those.
6556 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00006557 if (LHS.get()->isValueDependent() ||
6558 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6559 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006560 return;
6561 llvm::APInt ResultBits =
6562 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6563 if (LeftBits.uge(ResultBits))
6564 return;
6565 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6566 Result = Result.shl(Right);
6567
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006568 // Print the bit representation of the signed integer as an unsigned
6569 // hexadecimal number.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006570 SmallString<40> HexResult;
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006571 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6572
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006573 // If we are only missing a sign bit, this is less likely to result in actual
6574 // bugs -- if the result is cast back to an unsigned type, it will have the
6575 // expected value. Thus we place this behind a different warning that can be
6576 // turned off separately if needed.
6577 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006578 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006579 << HexResult.str() << LHSType
6580 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006581 return;
6582 }
6583
6584 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006585 << HexResult.str() << Result.getMinSignedBits() << LHSType
6586 << Left.getBitWidth() << LHS.get()->getSourceRange()
6587 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006588}
6589
Chris Lattner2a3569b2008-04-07 05:30:13 +00006590// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00006591QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006592 SourceLocation Loc, unsigned Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006593 bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006594 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6595
Chris Lattner5c11c412007-12-12 05:47:28 +00006596 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006597 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6598 !RHS.get()->getType()->hasIntegerRepresentation())
6599 return InvalidOperands(Loc, LHS, RHS);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006600
Douglas Gregor0bf31402010-10-08 23:50:27 +00006601 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6602 // hasIntegerRepresentation() above instead of this.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006603 if (isScopedEnumerationType(LHS.get()->getType()) ||
6604 isScopedEnumerationType(RHS.get()->getType())) {
6605 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006606 }
6607
Nate Begemane46ee9a2009-10-25 02:26:48 +00006608 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006609 if (LHS.get()->getType()->isVectorType() ||
6610 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006611 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006612
Chris Lattner5c11c412007-12-12 05:47:28 +00006613 // Shifts don't perform usual arithmetic conversions, they just do integer
6614 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006615
John McCall57cdd882010-12-16 19:28:59 +00006616 // For the LHS, do usual unary conversions, but then reset them away
6617 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006618 ExprResult OldLHS = LHS;
6619 LHS = UsualUnaryConversions(LHS.take());
6620 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006621 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00006622 QualType LHSType = LHS.get()->getType();
Richard Trieuba63ce62011-09-09 01:45:06 +00006623 if (IsCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00006624
6625 // The RHS is simpler.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006626 RHS = UsualUnaryConversions(RHS.take());
6627 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006628 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006629
Ryan Flynnf53fab82009-08-07 16:20:20 +00006630 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00006631 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006632
Chris Lattner5c11c412007-12-12 05:47:28 +00006633 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00006634 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006635}
6636
Chandler Carruth17773fc2010-07-10 12:30:03 +00006637static bool IsWithinTemplateSpecialization(Decl *D) {
6638 if (DeclContext *DC = D->getDeclContext()) {
6639 if (isa<ClassTemplateSpecializationDecl>(DC))
6640 return true;
6641 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6642 return FD->isFunctionTemplateSpecialization();
6643 }
6644 return false;
6645}
6646
Richard Trieueea56f72011-09-02 03:48:46 +00006647/// If two different enums are compared, raise a warning.
Richard Trieu1762d7c2011-09-06 21:27:33 +00006648static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6649 ExprResult &RHS) {
6650 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6651 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00006652
6653 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6654 if (!LHSEnumType)
6655 return;
6656 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6657 if (!RHSEnumType)
6658 return;
6659
6660 // Ignore anonymous enums.
6661 if (!LHSEnumType->getDecl()->getIdentifier())
6662 return;
6663 if (!RHSEnumType->getDecl()->getIdentifier())
6664 return;
6665
6666 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6667 return;
6668
6669 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6670 << LHSStrippedType << RHSStrippedType
Richard Trieu1762d7c2011-09-06 21:27:33 +00006671 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00006672}
6673
Richard Trieudd82a5c2011-09-02 02:55:45 +00006674/// \brief Diagnose bad pointer comparisons.
6675static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006676 ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006677 bool IsError) {
6678 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieudd82a5c2011-09-02 02:55:45 +00006679 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006680 << LHS.get()->getType() << RHS.get()->getType()
6681 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006682}
6683
6684/// \brief Returns false if the pointers are converted to a composite type,
6685/// true otherwise.
6686static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006687 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006688 // C++ [expr.rel]p2:
6689 // [...] Pointer conversions (4.10) and qualification
6690 // conversions (4.4) are performed on pointer operands (or on
6691 // a pointer operand and a null pointer constant) to bring
6692 // them to their composite pointer type. [...]
6693 //
6694 // C++ [expr.eq]p1 uses the same notion for (in)equality
6695 // comparisons of pointers.
6696
6697 // C++ [expr.eq]p2:
6698 // In addition, pointers to members can be compared, or a pointer to
6699 // member and a null pointer constant. Pointer to member conversions
6700 // (4.11) and qualification conversions (4.4) are performed to bring
6701 // them to a common type. If one operand is a null pointer constant,
6702 // the common type is the type of the other operand. Otherwise, the
6703 // common type is a pointer to member type similar (4.4) to the type
6704 // of one of the operands, with a cv-qualification signature (4.4)
6705 // that is the union of the cv-qualification signatures of the operand
6706 // types.
6707
Richard Trieu1762d7c2011-09-06 21:27:33 +00006708 QualType LHSType = LHS.get()->getType();
6709 QualType RHSType = RHS.get()->getType();
6710 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6711 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieudd82a5c2011-09-02 02:55:45 +00006712
6713 bool NonStandardCompositeType = false;
Richard Trieu48277e52011-09-02 21:44:27 +00006714 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieu1762d7c2011-09-06 21:27:33 +00006715 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006716 if (T.isNull()) {
Richard Trieu1762d7c2011-09-06 21:27:33 +00006717 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006718 return true;
6719 }
6720
6721 if (NonStandardCompositeType)
6722 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006723 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6724 << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006725
Richard Trieu1762d7c2011-09-06 21:27:33 +00006726 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6727 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006728 return false;
6729}
6730
6731static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006732 ExprResult &LHS,
6733 ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006734 bool IsError) {
6735 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6736 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006737 << LHS.get()->getType() << RHS.get()->getType()
6738 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006739}
6740
Jordan Rosed49a33e2012-06-08 21:14:25 +00006741static bool isObjCObjectLiteral(ExprResult &E) {
6742 switch (E.get()->getStmtClass()) {
6743 case Stmt::ObjCArrayLiteralClass:
6744 case Stmt::ObjCDictionaryLiteralClass:
6745 case Stmt::ObjCStringLiteralClass:
6746 case Stmt::ObjCBoxedExprClass:
6747 return true;
6748 default:
6749 // Note that ObjCBoolLiteral is NOT an object literal!
6750 return false;
6751 }
6752}
6753
Jordan Rose7660f782012-07-17 17:46:40 +00006754static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6755 // Get the LHS object's interface type.
6756 QualType Type = LHS->getType();
6757 QualType InterfaceType;
6758 if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6759 InterfaceType = PTy->getPointeeType();
6760 if (const ObjCObjectType *iQFaceTy =
6761 InterfaceType->getAsObjCQualifiedInterfaceType())
6762 InterfaceType = iQFaceTy->getBaseType();
6763 } else {
6764 // If this is not actually an Objective-C object, bail out.
6765 return false;
6766 }
6767
6768 // If the RHS isn't an Objective-C object, bail out.
6769 if (!RHS->getType()->isObjCObjectPointerType())
6770 return false;
6771
6772 // Try to find the -isEqual: method.
6773 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6774 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6775 InterfaceType,
6776 /*instance=*/true);
6777 if (!Method) {
6778 if (Type->isObjCIdType()) {
6779 // For 'id', just check the global pool.
6780 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6781 /*receiverId=*/true,
6782 /*warn=*/false);
6783 } else {
6784 // Check protocols.
6785 Method = S.LookupMethodInQualifiedType(IsEqualSel,
6786 cast<ObjCObjectPointerType>(Type),
6787 /*instance=*/true);
6788 }
6789 }
6790
6791 if (!Method)
6792 return false;
6793
6794 QualType T = Method->param_begin()[0]->getType();
6795 if (!T->isObjCObjectPointerType())
6796 return false;
6797
6798 QualType R = Method->getResultType();
6799 if (!R->isScalarType())
6800 return false;
6801
6802 return true;
6803}
6804
6805static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
6806 ExprResult &LHS, ExprResult &RHS,
6807 BinaryOperator::Opcode Opc){
Jordan Rose63ffaa82012-07-17 17:46:48 +00006808 Expr *Literal;
6809 Expr *Other;
6810 if (isObjCObjectLiteral(LHS)) {
6811 Literal = LHS.get();
6812 Other = RHS.get();
6813 } else {
6814 Literal = RHS.get();
6815 Other = LHS.get();
6816 }
6817
6818 // Don't warn on comparisons against nil.
6819 Other = Other->IgnoreParenCasts();
6820 if (Other->isNullPointerConstant(S.getASTContext(),
6821 Expr::NPC_ValueDependentIsNotNull))
6822 return;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006823
Jordan Roseea70bf72012-07-17 17:46:44 +00006824 // This should be kept in sync with warn_objc_literal_comparison.
Jordan Rose63ffaa82012-07-17 17:46:48 +00006825 // LK_String should always be last, since it has its own warning flag.
Jordan Roseea70bf72012-07-17 17:46:44 +00006826 enum {
6827 LK_Array,
6828 LK_Dictionary,
6829 LK_Numeric,
6830 LK_Boxed,
6831 LK_String
6832 } LiteralKind;
6833
Jordan Rosed49a33e2012-06-08 21:14:25 +00006834 switch (Literal->getStmtClass()) {
6835 case Stmt::ObjCStringLiteralClass:
6836 // "string literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006837 LiteralKind = LK_String;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006838 break;
6839 case Stmt::ObjCArrayLiteralClass:
6840 // "array literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006841 LiteralKind = LK_Array;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006842 break;
6843 case Stmt::ObjCDictionaryLiteralClass:
6844 // "dictionary literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006845 LiteralKind = LK_Dictionary;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006846 break;
6847 case Stmt::ObjCBoxedExprClass: {
6848 Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6849 switch (Inner->getStmtClass()) {
6850 case Stmt::IntegerLiteralClass:
6851 case Stmt::FloatingLiteralClass:
6852 case Stmt::CharacterLiteralClass:
6853 case Stmt::ObjCBoolLiteralExprClass:
6854 case Stmt::CXXBoolLiteralExprClass:
6855 // "numeric literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006856 LiteralKind = LK_Numeric;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006857 break;
6858 case Stmt::ImplicitCastExprClass: {
6859 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6860 // Boolean literals can be represented by implicit casts.
6861 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
Jordan Roseea70bf72012-07-17 17:46:44 +00006862 LiteralKind = LK_Numeric;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006863 break;
6864 }
6865 // FALLTHROUGH
6866 }
6867 default:
6868 // "boxed expression"
Jordan Roseea70bf72012-07-17 17:46:44 +00006869 LiteralKind = LK_Boxed;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006870 break;
6871 }
6872 break;
6873 }
6874 default:
6875 llvm_unreachable("Unknown Objective-C object literal kind");
6876 }
6877
Jordan Roseea70bf72012-07-17 17:46:44 +00006878 if (LiteralKind == LK_String)
6879 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
6880 << Literal->getSourceRange();
6881 else
6882 S.Diag(Loc, diag::warn_objc_literal_comparison)
6883 << LiteralKind << Literal->getSourceRange();
Jordan Rosed49a33e2012-06-08 21:14:25 +00006884
Jordan Rose7660f782012-07-17 17:46:40 +00006885 if (BinaryOperator::isEqualityOp(Opc) &&
6886 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
6887 SourceLocation Start = LHS.get()->getLocStart();
6888 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
6889 SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc));
Jordan Rosef9198032012-07-09 16:54:44 +00006890
Jordan Rose7660f782012-07-17 17:46:40 +00006891 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
6892 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
6893 << FixItHint::CreateReplacement(OpRange, "isEqual:")
6894 << FixItHint::CreateInsertion(End, "]");
Jordan Rosed49a33e2012-06-08 21:14:25 +00006895 }
Jordan Rosed49a33e2012-06-08 21:14:25 +00006896}
6897
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006898// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00006899QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006900 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006901 bool IsRelational) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006902 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6903
John McCalle3027922010-08-25 11:45:40 +00006904 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006905
Chris Lattner9a152e22009-12-05 05:40:13 +00006906 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00006907 if (LHS.get()->getType()->isVectorType() ||
6908 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006909 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006910
Richard Trieub80728f2011-09-06 21:43:51 +00006911 QualType LHSType = LHS.get()->getType();
6912 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00006913
Richard Trieub80728f2011-09-06 21:43:51 +00006914 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6915 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006916
Richard Trieub80728f2011-09-06 21:43:51 +00006917 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth712563b2011-02-17 08:37:06 +00006918
Richard Trieub80728f2011-09-06 21:43:51 +00006919 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuba63ce62011-09-09 01:45:06 +00006920 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieub80728f2011-09-06 21:43:51 +00006921 !LHS.get()->getLocStart().isMacroID() &&
6922 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006923 // For non-floating point types, check for self-comparisons of the form
6924 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6925 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006926 //
6927 // NOTE: Don't warn about comparison expressions resulting from macro
6928 // expansion. Also don't warn about comparisons which are only self
6929 // comparisons within a template specialization. The warnings should catch
6930 // obvious cases in the definition of the template anyways. The idea is to
6931 // warn when the typed comparison operator will always evaluate to the same
6932 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006933 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006934 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006935 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006936 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006937 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006938 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006939 << (Opc == BO_EQ
6940 || Opc == BO_LE
6941 || Opc == BO_GE));
Richard Trieub80728f2011-09-06 21:43:51 +00006942 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregorec170db2010-06-08 19:50:34 +00006943 !DRL->getDecl()->getType()->isReferenceType() &&
6944 !DRR->getDecl()->getType()->isReferenceType()) {
6945 // what is it always going to eval to?
6946 char always_evals_to;
6947 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006948 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006949 always_evals_to = 0; // false
6950 break;
John McCalle3027922010-08-25 11:45:40 +00006951 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006952 always_evals_to = 1; // true
6953 break;
6954 default:
6955 // best we can say is 'a constant'
6956 always_evals_to = 2; // e.g. array1 <= array2
6957 break;
6958 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006959 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006960 << 1 // array
6961 << always_evals_to);
6962 }
6963 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006964 }
Mike Stump11289f42009-09-09 15:08:12 +00006965
Chris Lattner222b8bd2009-03-08 19:39:53 +00006966 if (isa<CastExpr>(LHSStripped))
6967 LHSStripped = LHSStripped->IgnoreParenCasts();
6968 if (isa<CastExpr>(RHSStripped))
6969 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006970
Chris Lattner222b8bd2009-03-08 19:39:53 +00006971 // Warn about comparisons against a string constant (unless the other
6972 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006973 Expr *literalString = 0;
6974 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006975 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006976 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006977 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006978 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006979 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006980 } else if ((isa<StringLiteral>(RHSStripped) ||
6981 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006982 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006983 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006984 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006985 literalStringStripped = RHSStripped;
6986 }
6987
6988 if (literalString) {
6989 std::string resultComparison;
6990 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006991 case BO_LT: resultComparison = ") < 0"; break;
6992 case BO_GT: resultComparison = ") > 0"; break;
6993 case BO_LE: resultComparison = ") <= 0"; break;
6994 case BO_GE: resultComparison = ") >= 0"; break;
6995 case BO_EQ: resultComparison = ") == 0"; break;
6996 case BO_NE: resultComparison = ") != 0"; break;
David Blaikie83d382b2011-09-23 05:06:16 +00006997 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006998 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006999
Ted Kremenek3427fac2011-02-23 01:52:04 +00007000 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00007001 PDiag(diag::warn_stringcompare)
7002 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00007003 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007004 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00007005 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007006
Douglas Gregorec170db2010-06-08 19:50:34 +00007007 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieub80728f2011-09-06 21:43:51 +00007008 if (LHS.get()->getType()->isArithmeticType() &&
7009 RHS.get()->getType()->isArithmeticType()) {
7010 UsualArithmeticConversions(LHS, RHS);
7011 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007012 return QualType();
7013 }
Douglas Gregorec170db2010-06-08 19:50:34 +00007014 else {
Richard Trieub80728f2011-09-06 21:43:51 +00007015 LHS = UsualUnaryConversions(LHS.take());
7016 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007017 return QualType();
7018
Richard Trieub80728f2011-09-06 21:43:51 +00007019 RHS = UsualUnaryConversions(RHS.take());
7020 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007021 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007022 }
7023
Richard Trieub80728f2011-09-06 21:43:51 +00007024 LHSType = LHS.get()->getType();
7025 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007026
Douglas Gregorca63811b2008-11-19 03:25:36 +00007027 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007028 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00007029
Richard Trieuba63ce62011-09-09 01:45:06 +00007030 if (IsRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00007031 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007032 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007033 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00007034 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00007035 if (LHSType->hasFloatingRepresentation())
7036 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007037
Richard Trieub80728f2011-09-06 21:43:51 +00007038 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007039 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007040 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007041
Richard Trieub80728f2011-09-06 21:43:51 +00007042 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007043 Expr::NPC_ValueDependentIsNull);
Richard Trieub80728f2011-09-06 21:43:51 +00007044 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007045 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007046
Douglas Gregorf267edd2010-06-15 21:38:40 +00007047 // All of the following pointer-related warnings are GCC extensions, except
7048 // when handling null pointer constants.
Richard Trieub80728f2011-09-06 21:43:51 +00007049 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00007050 QualType LCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00007051 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattner3a0702e2008-04-03 05:07:25 +00007052 QualType RCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00007053 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007054
David Blaikiebbafb8a2012-03-11 07:00:24 +00007055 if (getLangOpts().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00007056 if (LCanPointeeTy == RCanPointeeTy)
7057 return ResultTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00007058 if (!IsRelational &&
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007059 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7060 // Valid unless comparison between non-null pointer and function pointer
7061 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00007062 // In a SFINAE context, we treat this as a hard error to maintain
7063 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007064 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7065 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00007066 diagnoseFunctionPointerToVoidComparison(
Richard Trieub80728f2011-09-06 21:43:51 +00007067 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00007068
7069 if (isSFINAEContext())
7070 return QualType();
7071
Richard Trieub80728f2011-09-06 21:43:51 +00007072 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007073 return ResultTy;
7074 }
7075 }
Anders Carlssona95069c2010-11-04 03:17:43 +00007076
Richard Trieub80728f2011-09-06 21:43:51 +00007077 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007078 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00007079 else
7080 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007081 }
Eli Friedman16c209612009-08-23 00:27:47 +00007082 // C99 6.5.9p2 and C99 6.5.8p2
7083 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7084 RCanPointeeTy.getUnqualifiedType())) {
7085 // Valid unless a relational comparison of function pointers
Richard Trieuba63ce62011-09-09 01:45:06 +00007086 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman16c209612009-08-23 00:27:47 +00007087 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00007088 << LHSType << RHSType << LHS.get()->getSourceRange()
7089 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00007090 }
Richard Trieuba63ce62011-09-09 01:45:06 +00007091 } else if (!IsRelational &&
Eli Friedman16c209612009-08-23 00:27:47 +00007092 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7093 // Valid unless comparison between non-null pointer and function pointer
7094 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00007095 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007096 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007097 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00007098 } else {
7099 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00007100 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00007101 }
John McCall7684dde2011-03-11 04:25:25 +00007102 if (LCanPointeeTy != RCanPointeeTy) {
7103 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007104 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007105 else
Richard Trieub80728f2011-09-06 21:43:51 +00007106 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007107 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00007108 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00007109 }
Mike Stump11289f42009-09-09 15:08:12 +00007110
David Blaikiebbafb8a2012-03-11 07:00:24 +00007111 if (getLangOpts().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00007112 // Comparison of nullptr_t with itself.
Richard Trieub80728f2011-09-06 21:43:51 +00007113 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlssona95069c2010-11-04 03:17:43 +00007114 return ResultTy;
7115
Mike Stump11289f42009-09-09 15:08:12 +00007116 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007117 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00007118 if (RHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00007119 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00007120 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00007121 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7122 RHS = ImpCastExprToType(RHS.take(), LHSType,
7123 LHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007124 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007125 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007126 return ResultTy;
7127 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007128 if (LHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00007129 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00007130 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00007131 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7132 LHS = ImpCastExprToType(LHS.take(), RHSType,
7133 RHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007134 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007135 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007136 return ResultTy;
7137 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007138
7139 // Comparison of member pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00007140 if (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00007141 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7142 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007143 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00007144 else
7145 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007146 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007147
7148 // Handle scoped enumeration types specifically, since they don't promote
7149 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00007150 if (LHS.get()->getType()->isEnumeralType() &&
7151 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7152 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007153 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00007154 }
Mike Stump11289f42009-09-09 15:08:12 +00007155
Steve Naroff081c7422008-09-04 15:10:53 +00007156 // Handle block pointer types.
Richard Trieuba63ce62011-09-09 01:45:06 +00007157 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieub80728f2011-09-06 21:43:51 +00007158 RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00007159 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7160 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007161
Steve Naroff081c7422008-09-04 15:10:53 +00007162 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00007163 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007164 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00007165 << LHSType << RHSType << LHS.get()->getSourceRange()
7166 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00007167 }
Richard Trieub80728f2011-09-06 21:43:51 +00007168 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007169 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00007170 }
John Wiegley01296292011-04-08 18:41:53 +00007171
Steve Naroffe18f94c2008-09-28 01:11:11 +00007172 // Allow block pointers to be compared with null pointer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00007173 if (!IsRelational
Richard Trieub80728f2011-09-06 21:43:51 +00007174 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7175 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00007176 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00007177 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007178 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00007179 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007180 ->getPointeeType()->isVoidType())))
7181 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00007182 << LHSType << RHSType << LHS.get()->getSourceRange()
7183 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00007184 }
John McCall7684dde2011-03-11 04:25:25 +00007185 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00007186 LHS = ImpCastExprToType(LHS.take(), RHSType,
7187 RHSType->isPointerType() ? CK_BitCast
7188 : CK_AnyPointerToBlockPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00007189 else
John McCall9320b872011-09-09 05:25:32 +00007190 RHS = ImpCastExprToType(RHS.take(), LHSType,
7191 LHSType->isPointerType() ? CK_BitCast
7192 : CK_AnyPointerToBlockPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007193 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00007194 }
Steve Naroff081c7422008-09-04 15:10:53 +00007195
Richard Trieub80728f2011-09-06 21:43:51 +00007196 if (LHSType->isObjCObjectPointerType() ||
7197 RHSType->isObjCObjectPointerType()) {
7198 const PointerType *LPT = LHSType->getAs<PointerType>();
7199 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00007200 if (LPT || RPT) {
7201 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7202 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007203
Steve Naroff753567f2008-11-17 19:49:16 +00007204 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00007205 !Context.typesAreCompatible(LHSType, RHSType)) {
7206 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007207 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007208 }
John McCall7684dde2011-03-11 04:25:25 +00007209 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00007210 LHS = ImpCastExprToType(LHS.take(), RHSType,
7211 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00007212 else
John McCall9320b872011-09-09 05:25:32 +00007213 RHS = ImpCastExprToType(RHS.take(), LHSType,
7214 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007215 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00007216 }
Richard Trieub80728f2011-09-06 21:43:51 +00007217 if (LHSType->isObjCObjectPointerType() &&
7218 RHSType->isObjCObjectPointerType()) {
7219 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7220 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007221 /*isError*/false);
Jordan Rosed49a33e2012-06-08 21:14:25 +00007222 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
Jordan Rose7660f782012-07-17 17:46:40 +00007223 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
Jordan Rosed49a33e2012-06-08 21:14:25 +00007224
John McCall7684dde2011-03-11 04:25:25 +00007225 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007226 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007227 else
Richard Trieub80728f2011-09-06 21:43:51 +00007228 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007229 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00007230 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00007231 }
Richard Trieub80728f2011-09-06 21:43:51 +00007232 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7233 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00007234 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007235 bool isError = false;
Douglas Gregor0064c592012-09-14 04:35:37 +00007236 if (LangOpts.DebuggerSupport) {
7237 // Under a debugger, allow the comparison of pointers to integers,
7238 // since users tend to want to compare addresses.
7239 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
Richard Trieub80728f2011-09-06 21:43:51 +00007240 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007241 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007242 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007243 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007244 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007245 else if (getLangOpts().CPlusPlus) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00007246 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7247 isError = true;
7248 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00007249 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00007250
Chris Lattnerd99bd522009-08-23 00:03:44 +00007251 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007252 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00007253 << LHSType << RHSType << LHS.get()->getSourceRange()
7254 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007255 if (isError)
7256 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00007257 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007258
Richard Trieub80728f2011-09-06 21:43:51 +00007259 if (LHSType->isIntegerType())
7260 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00007261 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00007262 else
Richard Trieub80728f2011-09-06 21:43:51 +00007263 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00007264 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007265 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00007266 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007267
Steve Naroff4b191572008-09-04 16:56:14 +00007268 // Handle block pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00007269 if (!IsRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00007270 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7271 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007272 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007273 }
Richard Trieuba63ce62011-09-09 01:45:06 +00007274 if (!IsRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00007275 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7276 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007277 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007278 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007279
Richard Trieub80728f2011-09-06 21:43:51 +00007280 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007281}
7282
Tanya Lattner20248222012-01-16 21:02:28 +00007283
7284// Return a signed type that is of identical size and number of elements.
7285// For floating point vectors, return an integer type of identical size
7286// and number of elements.
7287QualType Sema::GetSignedVectorType(QualType V) {
7288 const VectorType *VTy = V->getAs<VectorType>();
7289 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7290 if (TypeSize == Context.getTypeSize(Context.CharTy))
7291 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7292 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7293 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7294 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7295 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7296 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7297 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7298 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7299 "Unhandled vector element size in vector compare");
7300 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7301}
7302
Nate Begeman191a6b12008-07-14 18:02:46 +00007303/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00007304/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00007305/// like a scalar comparison, a vector comparison produces a vector of integer
7306/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00007307QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007308 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007309 bool IsRelational) {
Nate Begeman191a6b12008-07-14 18:02:46 +00007310 // Check to make sure we're operating on vectors of the same type and width,
7311 // Allowing one side to be a scalar of element type.
Richard Trieubcce2f72011-09-07 01:19:57 +00007312 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00007313 if (vType.isNull())
7314 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007315
Richard Trieubcce2f72011-09-07 01:19:57 +00007316 QualType LHSType = LHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007317
Anton Yartsev530deb92011-03-27 15:36:07 +00007318 // If AltiVec, the comparison results in a numeric type, i.e.
7319 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00007320 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00007321 return Context.getLogicalOperationType();
7322
Nate Begeman191a6b12008-07-14 18:02:46 +00007323 // For non-floating point types, check for self-comparisons of the form
7324 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7325 // often indicate logic errors in the program.
Richard Trieubcce2f72011-09-07 01:19:57 +00007326 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith508ebf32011-10-28 03:31:48 +00007327 if (DeclRefExpr* DRL
7328 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7329 if (DeclRefExpr* DRR
7330 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begeman191a6b12008-07-14 18:02:46 +00007331 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007332 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007333 PDiag(diag::warn_comparison_always)
7334 << 0 // self-
7335 << 2 // "a constant"
7336 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007337 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007338
Nate Begeman191a6b12008-07-14 18:02:46 +00007339 // Check for comparisons of floating point operands using != and ==.
Richard Trieuba63ce62011-09-09 01:45:06 +00007340 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikieca043222012-01-16 05:16:03 +00007341 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieubcce2f72011-09-07 01:19:57 +00007342 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00007343 }
Tanya Lattner20248222012-01-16 21:02:28 +00007344
7345 // Return a signed type for the vector.
7346 return GetSignedVectorType(LHSType);
7347}
Mike Stump4e1f26a2009-02-19 03:04:26 +00007348
Tanya Lattner3dd33b22012-01-19 01:16:16 +00007349QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7350 SourceLocation Loc) {
Tanya Lattner20248222012-01-16 21:02:28 +00007351 // Ensure that either both operands are of the same vector type, or
7352 // one operand is of a vector type and the other is of its element type.
7353 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7354 if (vType.isNull() || vType->isFloatingType())
7355 return InvalidOperands(Loc, LHS, RHS);
7356
7357 return GetSignedVectorType(LHS.get()->getType());
Nate Begeman191a6b12008-07-14 18:02:46 +00007358}
7359
Steve Naroff218bc2b2007-05-04 21:54:46 +00007360inline QualType Sema::CheckBitwiseOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00007361 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00007362 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7363
Richard Trieubcce2f72011-09-07 01:19:57 +00007364 if (LHS.get()->getType()->isVectorType() ||
7365 RHS.get()->getType()->isVectorType()) {
7366 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7367 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00007368 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007369
Richard Trieubcce2f72011-09-07 01:19:57 +00007370 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007371 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007372
Richard Trieubcce2f72011-09-07 01:19:57 +00007373 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7374 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuba63ce62011-09-09 01:45:06 +00007375 IsCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00007376 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007377 return QualType();
Richard Trieubcce2f72011-09-07 01:19:57 +00007378 LHS = LHSResult.take();
7379 RHS = RHSResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007380
Eli Friedman93ee5ca2012-06-16 02:19:17 +00007381 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007382 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00007383 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007384}
7385
Steve Naroff218bc2b2007-05-04 21:54:46 +00007386inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieubcce2f72011-09-07 01:19:57 +00007387 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00007388
Tanya Lattner20248222012-01-16 21:02:28 +00007389 // Check vector operands differently.
7390 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7391 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7392
Chris Lattner8406c512010-07-13 19:41:32 +00007393 // Diagnose cases where the user write a logical and/or but probably meant a
7394 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7395 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00007396 if (LHS.get()->getType()->isIntegerType() &&
7397 !LHS.get()->getType()->isBooleanType() &&
7398 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00007399 // Don't warn in macros or template instantiations.
7400 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00007401 // If the RHS can be constant folded, and if it constant folds to something
7402 // that isn't 0 or 1 (which indicate a potential logical operation that
7403 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007404 // Parens on the RHS are ignored.
Richard Smith00ab3ae2011-10-16 23:01:09 +00007405 llvm::APSInt Result;
7406 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikiebbafb8a2012-03-11 07:00:24 +00007407 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith00ab3ae2011-10-16 23:01:09 +00007408 (Result != 0 && Result != 1)) {
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007409 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00007410 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007411 << (Opc == BO_LAnd ? "&&" : "||");
7412 // Suggest replacing the logical operator with the bitwise version
7413 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7414 << (Opc == BO_LAnd ? "&" : "|")
7415 << FixItHint::CreateReplacement(SourceRange(
7416 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00007417 getLangOpts())),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007418 Opc == BO_LAnd ? "&" : "|");
7419 if (Opc == BO_LAnd)
7420 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7421 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7422 << FixItHint::CreateRemoval(
7423 SourceRange(
Richard Trieubcce2f72011-09-07 01:19:57 +00007424 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007425 0, getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00007426 getLangOpts()),
Richard Trieubcce2f72011-09-07 01:19:57 +00007427 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007428 }
Chris Lattner938533d2010-07-24 01:10:11 +00007429 }
Chris Lattner8406c512010-07-13 19:41:32 +00007430
David Blaikiebbafb8a2012-03-11 07:00:24 +00007431 if (!Context.getLangOpts().CPlusPlus) {
Richard Trieubcce2f72011-09-07 01:19:57 +00007432 LHS = UsualUnaryConversions(LHS.take());
7433 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007434 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007435
Richard Trieubcce2f72011-09-07 01:19:57 +00007436 RHS = UsualUnaryConversions(RHS.take());
7437 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007438 return QualType();
7439
Richard Trieubcce2f72011-09-07 01:19:57 +00007440 if (!LHS.get()->getType()->isScalarType() ||
7441 !RHS.get()->getType()->isScalarType())
7442 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007443
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007444 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007445 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007446
John McCall4a2429a2010-06-04 00:29:51 +00007447 // The following is safe because we only use this method for
7448 // non-overloadable operands.
7449
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007450 // C++ [expr.log.and]p1
7451 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007452 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00007453 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7454 if (LHSRes.isInvalid())
7455 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007456 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00007457
Richard Trieubcce2f72011-09-07 01:19:57 +00007458 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7459 if (RHSRes.isInvalid())
7460 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007461 RHS = RHSRes;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007462
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007463 // C++ [expr.log.and]p2
7464 // C++ [expr.log.or]p2
7465 // The result is a bool.
7466 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007467}
7468
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007469/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7470/// is a read-only property; return true if so. A readonly property expression
7471/// depends on various declarations and thus must be treated specially.
7472///
Mike Stump11289f42009-09-09 15:08:12 +00007473static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007474 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7475 if (!PropExpr) return false;
7476 if (PropExpr->isImplicitProperty()) return false;
John McCallb7bd14f2010-12-02 01:19:52 +00007477
John McCall526ab472011-10-25 17:37:35 +00007478 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7479 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCallb7bd14f2010-12-02 01:19:52 +00007480 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007481 PropExpr->getBase()->getType();
7482
John McCall526ab472011-10-25 17:37:35 +00007483 if (const ObjCObjectPointerType *OPT =
7484 BaseType->getAsObjCInterfacePointerType())
7485 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7486 if (S.isPropertyReadonly(PDecl, IFace))
7487 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007488 return false;
7489}
7490
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007491static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007492 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7493 if (!ME) return false;
7494 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7495 ObjCMessageExpr *Base =
7496 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7497 if (!Base) return false;
7498 return Base->getMethodDecl() != 0;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007499}
7500
John McCall5fa2ef42012-03-13 00:37:01 +00007501/// Is the given expression (which must be 'const') a reference to a
7502/// variable which was originally non-const, but which has become
7503/// 'const' due to being captured within a block?
7504enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7505static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7506 assert(E->isLValue() && E->getType().isConstQualified());
7507 E = E->IgnoreParens();
7508
7509 // Must be a reference to a declaration from an enclosing scope.
7510 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7511 if (!DRE) return NCCK_None;
7512 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7513
7514 // The declaration must be a variable which is not declared 'const'.
7515 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7516 if (!var) return NCCK_None;
7517 if (var->getType().isConstQualified()) return NCCK_None;
7518 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7519
7520 // Decide whether the first capture was for a block or a lambda.
7521 DeclContext *DC = S.CurContext;
7522 while (DC->getParent() != var->getDeclContext())
7523 DC = DC->getParent();
7524 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7525}
7526
Chris Lattner30bd3272008-11-18 01:22:49 +00007527/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7528/// emit an error and return true. If so, return false.
7529static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianca5c5972012-04-10 17:30:10 +00007530 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007531 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007532 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007533 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007534 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7535 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007536 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7537 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007538 if (IsLV == Expr::MLV_Valid)
7539 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007540
Chris Lattner30bd3272008-11-18 01:22:49 +00007541 unsigned Diag = 0;
7542 bool NeedType = false;
7543 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00007544 case Expr::MLV_ConstQualified:
7545 Diag = diag::err_typecheck_assign_const;
7546
John McCall5fa2ef42012-03-13 00:37:01 +00007547 // Use a specialized diagnostic when we're assigning to an object
7548 // from an enclosing function or block.
7549 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7550 if (NCCK == NCCK_Block)
7551 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7552 else
7553 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7554 break;
7555 }
7556
John McCalld4631322011-06-17 06:42:21 +00007557 // In ARC, use some specialized diagnostics for occasions where we
7558 // infer 'const'. These are always pseudo-strong variables.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007559 if (S.getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00007560 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7561 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7562 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7563
John McCalld4631322011-06-17 06:42:21 +00007564 // Use the normal diagnostic if it's pseudo-__strong but the
7565 // user actually wrote 'const'.
7566 if (var->isARCPseudoStrong() &&
7567 (!var->getTypeSourceInfo() ||
7568 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7569 // There are two pseudo-strong cases:
7570 // - self
John McCall31168b02011-06-15 23:02:42 +00007571 ObjCMethodDecl *method = S.getCurMethodDecl();
7572 if (method && var == method->getSelfDecl())
Ted Kremenek1fcdaa92011-11-14 21:59:25 +00007573 Diag = method->isClassMethod()
7574 ? diag::err_typecheck_arc_assign_self_class_method
7575 : diag::err_typecheck_arc_assign_self;
John McCalld4631322011-06-17 06:42:21 +00007576
7577 // - fast enumeration variables
7578 else
John McCall31168b02011-06-15 23:02:42 +00007579 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00007580
John McCall31168b02011-06-15 23:02:42 +00007581 SourceRange Assign;
7582 if (Loc != OrigLoc)
7583 Assign = SourceRange(OrigLoc, OrigLoc);
7584 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7585 // We need to preserve the AST regardless, so migration tool
7586 // can do its job.
7587 return false;
7588 }
7589 }
7590 }
7591
7592 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007593 case Expr::MLV_ArrayType:
Richard Smitheb3cad52012-06-04 22:27:30 +00007594 case Expr::MLV_ArrayTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007595 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7596 NeedType = true;
7597 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007598 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007599 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7600 NeedType = true;
7601 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007602 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007603 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7604 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007605 case Expr::MLV_Valid:
7606 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007607 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007608 case Expr::MLV_MemberFunction:
7609 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007610 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7611 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007612 case Expr::MLV_IncompleteType:
7613 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007614 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007615 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner9bad62c2008-01-04 18:04:52 +00007616 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007617 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7618 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007619 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007620 case Expr::MLV_NoSetterProperty:
John McCall526ab472011-10-25 17:37:35 +00007621 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007622 case Expr::MLV_InvalidMessageExpression:
7623 Diag = diag::error_readonly_message_assignment;
7624 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007625 case Expr::MLV_SubObjCPropertySetting:
7626 Diag = diag::error_no_subobject_property_setting;
7627 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007628 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007629
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007630 SourceRange Assign;
7631 if (Loc != OrigLoc)
7632 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007633 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007634 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007635 else
Mike Stump11289f42009-09-09 15:08:12 +00007636 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007637 return true;
7638}
7639
Nico Weberb8124d12012-07-03 02:03:06 +00007640static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7641 SourceLocation Loc,
7642 Sema &Sema) {
7643 // C / C++ fields
Nico Weber33fd5232012-06-28 23:53:12 +00007644 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7645 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7646 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7647 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
Nico Weberb8124d12012-07-03 02:03:06 +00007648 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
Nico Weber33fd5232012-06-28 23:53:12 +00007649 }
Chris Lattner30bd3272008-11-18 01:22:49 +00007650
Nico Weberb8124d12012-07-03 02:03:06 +00007651 // Objective-C instance variables
Nico Weber33fd5232012-06-28 23:53:12 +00007652 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7653 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7654 if (OL && OR && OL->getDecl() == OR->getDecl()) {
7655 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7656 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7657 if (RL && RR && RL->getDecl() == RR->getDecl())
Nico Weberb8124d12012-07-03 02:03:06 +00007658 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
Nico Weber33fd5232012-06-28 23:53:12 +00007659 }
7660}
Chris Lattner30bd3272008-11-18 01:22:49 +00007661
7662// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +00007663QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007664 SourceLocation Loc,
7665 QualType CompoundType) {
John McCall526ab472011-10-25 17:37:35 +00007666 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7667
Chris Lattner326f7572008-11-18 01:30:42 +00007668 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007669 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007670 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007671
Richard Trieuda4f43a62011-09-07 01:33:52 +00007672 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00007673 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7674 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007675 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007676 if (CompoundType.isNull()) {
Nico Weber33fd5232012-06-28 23:53:12 +00007677 Expr *RHSCheck = RHS.get();
7678
Nico Weberb8124d12012-07-03 02:03:06 +00007679 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
Nico Weber33fd5232012-06-28 23:53:12 +00007680
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007681 QualType LHSTy(LHSType);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007682 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007683 if (RHS.isInvalid())
7684 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007685 // Special case of NSObject attributes on c-style pointer types.
7686 if (ConvTy == IncompatiblePointer &&
7687 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007688 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007689 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007690 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007691 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007692
John McCall7decc9e2010-11-18 06:31:45 +00007693 if (ConvTy == Compatible &&
Fariborz Jahaniane2a77762012-01-24 19:40:13 +00007694 LHSType->isObjCObjectType())
Fariborz Jahanian3c4225a2012-01-24 18:05:45 +00007695 Diag(Loc, diag::err_objc_object_assignment)
7696 << LHSType;
John McCall7decc9e2010-11-18 06:31:45 +00007697
Chris Lattnerea714382008-08-21 18:04:13 +00007698 // If the RHS is a unary plus or minus, check to see if they = and + are
7699 // right next to each other. If so, the user may have typo'd "x =+ 4"
7700 // instead of "x += 4".
Chris Lattnerea714382008-08-21 18:04:13 +00007701 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7702 RHSCheck = ICE->getSubExpr();
7703 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007704 if ((UO->getOpcode() == UO_Plus ||
7705 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007706 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007707 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007708 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner36c39c92009-03-08 06:51:10 +00007709 // And there is a space or other character before the subexpr of the
7710 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007711 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattnered9f14c2009-03-09 07:11:10 +00007712 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007713 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007714 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007715 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007716 }
Chris Lattnerea714382008-08-21 18:04:13 +00007717 }
John McCall31168b02011-06-15 23:02:42 +00007718
7719 if (ConvTy == Compatible) {
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007720 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
7721 // Warn about retain cycles where a block captures the LHS, but
7722 // not if the LHS is a simple variable into which the block is
7723 // being stored...unless that variable can be captured by reference!
7724 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
7725 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
7726 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
7727 checkRetainCycles(LHSExpr, RHS.get());
7728
7729 } else if (getLangOpts().ObjCAutoRefCount) {
Richard Trieuda4f43a62011-09-07 01:33:52 +00007730 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007731 }
John McCall31168b02011-06-15 23:02:42 +00007732 }
Chris Lattnerea714382008-08-21 18:04:13 +00007733 } else {
7734 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007735 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007736 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007737
Chris Lattner326f7572008-11-18 01:30:42 +00007738 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007739 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007740 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007741
Richard Trieuda4f43a62011-09-07 01:33:52 +00007742 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007743
Steve Naroff98cf3e92007-06-06 18:38:38 +00007744 // C99 6.5.16p3: The type of an assignment expression is the type of the
7745 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007746 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007747 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7748 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007749 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007750 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007751 return (getLangOpts().CPlusPlus
John McCall01cbf2d2010-10-12 02:19:57 +00007752 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007753}
7754
Chris Lattner326f7572008-11-18 01:30:42 +00007755// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007756static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007757 SourceLocation Loc) {
John McCall3aef3d82011-04-10 19:13:55 +00007758 LHS = S.CheckPlaceholderExpr(LHS.take());
7759 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007760 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007761 return QualType();
7762
John McCall73d36182010-10-12 07:14:40 +00007763 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7764 // operands, but not unary promotions.
7765 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007766
John McCall34376a62010-12-04 03:47:34 +00007767 // So we treat the LHS as a ignored value, and in C++ we allow the
7768 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007769 LHS = S.IgnoredValueConversions(LHS.take());
7770 if (LHS.isInvalid())
7771 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007772
Eli Friedmanc11535c2012-05-24 00:47:05 +00007773 S.DiagnoseUnusedExprResult(LHS.get());
7774
David Blaikiebbafb8a2012-03-11 07:00:24 +00007775 if (!S.getLangOpts().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007776 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7777 if (RHS.isInvalid())
7778 return QualType();
7779 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007780 S.RequireCompleteType(Loc, RHS.get()->getType(),
7781 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007782 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007783
John Wiegley01296292011-04-08 18:41:53 +00007784 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007785}
7786
Steve Naroff7a5af782007-07-13 16:58:59 +00007787/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7788/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007789static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7790 ExprValueKind &VK,
7791 SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007792 bool IsInc, bool IsPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007793 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007794 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007795
Chris Lattner6b0cf142008-11-21 07:05:48 +00007796 QualType ResType = Op->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00007797 // Atomic types can be used for increment / decrement where the non-atomic
7798 // versions can, so ignore the _Atomic() specifier for the purpose of
7799 // checking.
7800 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7801 ResType = ResAtomicType->getValueType();
7802
Chris Lattner6b0cf142008-11-21 07:05:48 +00007803 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007804
David Blaikiebbafb8a2012-03-11 07:00:24 +00007805 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007806 // Decrement of bool is not allowed.
Richard Trieuba63ce62011-09-09 01:45:06 +00007807 if (!IsInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007808 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007809 return QualType();
7810 }
7811 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007812 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007813 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007814 // OK!
John McCallf2538342012-07-31 05:14:30 +00007815 } else if (ResType->isPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007816 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007817 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007818 return QualType();
John McCallf2538342012-07-31 05:14:30 +00007819 } else if (ResType->isObjCObjectPointerType()) {
7820 // On modern runtimes, ObjC pointer arithmetic is forbidden.
7821 // Otherwise, we just need a complete type.
7822 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7823 checkArithmeticOnObjCPointer(S, OpLoc, Op))
7824 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +00007825 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007826 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007827 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007828 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007829 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007830 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007831 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007832 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007833 IsInc, IsPrefix);
David Blaikiebbafb8a2012-03-11 07:00:24 +00007834 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev85129b82011-02-07 02:17:30 +00007835 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007836 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007837 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuba63ce62011-09-09 01:45:06 +00007838 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007839 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007840 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007841 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007842 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007843 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007844 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007845 // In C++, a prefix increment is the same type as the operand. Otherwise
7846 // (in C or with postfix), the increment is the unqualified type of the
7847 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007848 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007849 VK = VK_LValue;
7850 return ResType;
7851 } else {
7852 VK = VK_RValue;
7853 return ResType.getUnqualifiedType();
7854 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007855}
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007856
7857
Anders Carlsson806700f2008-02-01 07:15:58 +00007858/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007859/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007860/// where the declaration is needed for type checking. We only need to
7861/// handle cases when the expression references a function designator
7862/// or is an lvalue. Here are some examples:
7863/// - &(x) => x
7864/// - &*****f => f for f a function designator.
7865/// - &s.xx => s
7866/// - &s.zz[1].yy -> s, if zz is an array
7867/// - *(x + 1) -> x, if x is an array
7868/// - &"123"[2] -> 0
7869/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007870static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007871 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007872 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007873 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007874 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007875 // If this is an arrow operator, the address is an offset from
7876 // the base's value, so the object the base refers to is
7877 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007878 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007879 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007880 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007881 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007882 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007883 // FIXME: This code shouldn't be necessary! We should catch the implicit
7884 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007885 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7886 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7887 if (ICE->getSubExpr()->getType()->isArrayType())
7888 return getPrimaryDecl(ICE->getSubExpr());
7889 }
7890 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007891 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007892 case Stmt::UnaryOperatorClass: {
7893 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007894
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007895 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007896 case UO_Real:
7897 case UO_Imag:
7898 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007899 return getPrimaryDecl(UO->getSubExpr());
7900 default:
7901 return 0;
7902 }
7903 }
Steve Naroff47500512007-04-19 23:00:49 +00007904 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007905 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007906 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007907 // If the result of an implicit cast is an l-value, we care about
7908 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007909 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007910 default:
7911 return 0;
7912 }
7913}
7914
Richard Trieu5f376f62011-09-07 21:46:33 +00007915namespace {
7916 enum {
7917 AO_Bit_Field = 0,
7918 AO_Vector_Element = 1,
7919 AO_Property_Expansion = 2,
7920 AO_Register_Variable = 3,
7921 AO_No_Error = 4
7922 };
7923}
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007924/// \brief Diagnose invalid operand for address of operations.
7925///
7926/// \param Type The type of operand which cannot have its address taken.
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007927static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7928 Expr *E, unsigned Type) {
7929 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7930}
7931
Steve Naroff47500512007-04-19 23:00:49 +00007932/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007933/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007934/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007935/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007936/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007937/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007938/// we allow the '&' but retain the overloaded-function type.
John McCall526ab472011-10-25 17:37:35 +00007939static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall4bc41ae2010-11-18 19:01:18 +00007940 SourceLocation OpLoc) {
John McCall526ab472011-10-25 17:37:35 +00007941 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7942 if (PTy->getKind() == BuiltinType::Overload) {
7943 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7944 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7945 << OrigOp.get()->getSourceRange();
7946 return QualType();
7947 }
7948
7949 return S.Context.OverloadTy;
7950 }
7951
7952 if (PTy->getKind() == BuiltinType::UnknownAny)
7953 return S.Context.UnknownAnyTy;
7954
7955 if (PTy->getKind() == BuiltinType::BoundMember) {
7956 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7957 << OrigOp.get()->getSourceRange();
Douglas Gregor668d3622011-10-09 19:10:41 +00007958 return QualType();
7959 }
John McCall526ab472011-10-25 17:37:35 +00007960
7961 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7962 if (OrigOp.isInvalid()) return QualType();
John McCall0009fcc2011-04-26 20:42:42 +00007963 }
John McCall8d08b9b2010-08-27 09:08:28 +00007964
John McCall526ab472011-10-25 17:37:35 +00007965 if (OrigOp.get()->isTypeDependent())
7966 return S.Context.DependentTy;
7967
7968 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007969
John McCall8d08b9b2010-08-27 09:08:28 +00007970 // Make sure to ignore parentheses in subsequent checks
John McCall526ab472011-10-25 17:37:35 +00007971 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007972
David Blaikiebbafb8a2012-03-11 07:00:24 +00007973 if (S.getLangOpts().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007974 // Implement C99-only parts of addressof rules.
7975 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007976 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007977 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7978 // (assuming the deref expression is valid).
7979 return uOp->getSubExpr()->getType();
7980 }
7981 // Technically, there should be a check for array subscript
7982 // expressions here, but the result of one is always an lvalue anyway.
7983 }
John McCallf3a88602011-02-03 08:15:49 +00007984 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007985 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5f376f62011-09-07 21:46:33 +00007986 unsigned AddressOfError = AO_No_Error;
Nuno Lopes17f345f2008-12-16 22:59:47 +00007987
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007988 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007989 bool sfinae = S.isSFINAEContext();
7990 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7991 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007992 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007993 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007994 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007995 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007996 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007997 } else if (lval == Expr::LV_MemberFunction) {
7998 // If it's an instance method, make a member pointer.
7999 // The expression must have exactly the form &A::foo.
8000
8001 // If the underlying expression isn't a decl ref, give up.
8002 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008003 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00008004 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00008005 return QualType();
8006 }
8007 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8008 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8009
8010 // The id-expression was parenthesized.
John McCall526ab472011-10-25 17:37:35 +00008011 if (OrigOp.get() != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00008012 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00008013 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00008014
8015 // The method was named without a qualifier.
8016 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008017 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008018 << op->getSourceRange();
8019 }
8020
John McCall4bc41ae2010-11-18 19:01:18 +00008021 return S.Context.getMemberPointerType(op->getType(),
8022 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00008023 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00008024 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008025 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00008026 if (!op->getType()->isFunctionType()) {
John McCall526ab472011-10-25 17:37:35 +00008027 // Use a special diagnostic for loads from property references.
John McCallfe96e0b2011-11-06 09:01:30 +00008028 if (isa<PseudoObjectExpr>(op)) {
John McCall526ab472011-10-25 17:37:35 +00008029 AddressOfError = AO_Property_Expansion;
8030 } else {
8031 // FIXME: emit more specific diag...
8032 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8033 << op->getSourceRange();
8034 return QualType();
8035 }
Steve Naroff35d85152007-05-07 00:24:15 +00008036 }
John McCall086a4642010-11-24 05:12:34 +00008037 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008038 // The operand cannot be a bit-field
Richard Trieu5f376f62011-09-07 21:46:33 +00008039 AddressOfError = AO_Bit_Field;
John McCall086a4642010-11-24 05:12:34 +00008040 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00008041 // The operand cannot be an element of a vector
Richard Trieu5f376f62011-09-07 21:46:33 +00008042 AddressOfError = AO_Vector_Element;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00008043 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00008044 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00008045 // with the register storage-class specifier.
8046 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00008047 // in C++ it is not error to take address of a register
8048 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00008049 if (vd->getStorageClass() == SC_Register &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008050 !S.getLangOpts().CPlusPlus) {
Richard Trieu5f376f62011-09-07 21:46:33 +00008051 AddressOfError = AO_Register_Variable;
Steve Naroff35d85152007-05-07 00:24:15 +00008052 }
John McCalld14a8642009-11-21 08:51:07 +00008053 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008054 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00008055 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00008056 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008057 // Could be a pointer to member, though, if there is an explicit
8058 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00008059 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008060 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008061 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00008062 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008063 S.Diag(OpLoc,
8064 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00008065 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008066 return QualType();
8067 }
Mike Stump11289f42009-09-09 15:08:12 +00008068
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00008069 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8070 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00008071 return S.Context.getMemberPointerType(op->getType(),
8072 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00008073 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008074 }
Eli Friedman755c0c92011-08-26 20:28:17 +00008075 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikie83d382b2011-09-23 05:06:16 +00008076 llvm_unreachable("Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00008077 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008078
Richard Trieu5f376f62011-09-07 21:46:33 +00008079 if (AddressOfError != AO_No_Error) {
8080 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8081 return QualType();
8082 }
8083
Eli Friedmance7f9002009-05-16 23:27:50 +00008084 if (lval == Expr::LV_IncompleteVoidType) {
8085 // Taking the address of a void variable is technically illegal, but we
8086 // allow it in cases which are otherwise valid.
8087 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00008088 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00008089 }
8090
Steve Naroff47500512007-04-19 23:00:49 +00008091 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00008092 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00008093 return S.Context.getObjCObjectPointerType(op->getType());
8094 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00008095}
8096
Chris Lattner9156f1b2010-07-05 19:17:26 +00008097/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00008098static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8099 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008100 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008101 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008102
John Wiegley01296292011-04-08 18:41:53 +00008103 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8104 if (ConvResult.isInvalid())
8105 return QualType();
8106 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00008107 QualType OpTy = Op->getType();
8108 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00008109
8110 if (isa<CXXReinterpretCastExpr>(Op)) {
8111 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8112 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8113 Op->getSourceRange());
8114 }
8115
Chris Lattner9156f1b2010-07-05 19:17:26 +00008116 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8117 // is an incomplete type or void. It would be possible to warn about
8118 // dereferencing a void pointer, but it's completely well-defined, and such a
8119 // warning is unlikely to catch any mistakes.
8120 if (const PointerType *PT = OpTy->getAs<PointerType>())
8121 Result = PT->getPointeeType();
8122 else if (const ObjCObjectPointerType *OPT =
8123 OpTy->getAs<ObjCObjectPointerType>())
8124 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00008125 else {
John McCall3aef3d82011-04-10 19:13:55 +00008126 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00008127 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008128 if (PR.take() != Op)
8129 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00008130 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008131
Chris Lattner9156f1b2010-07-05 19:17:26 +00008132 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008133 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00008134 << OpTy << Op->getSourceRange();
8135 return QualType();
8136 }
John McCall4bc41ae2010-11-18 19:01:18 +00008137
8138 // Dereferences are usually l-values...
8139 VK = VK_LValue;
8140
8141 // ...except that certain expressions are never l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008142 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00008143 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00008144
8145 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00008146}
Steve Naroff218bc2b2007-05-04 21:54:46 +00008147
John McCalle3027922010-08-25 11:45:40 +00008148static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00008149 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008150 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008151 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00008152 default: llvm_unreachable("Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00008153 case tok::periodstar: Opc = BO_PtrMemD; break;
8154 case tok::arrowstar: Opc = BO_PtrMemI; break;
8155 case tok::star: Opc = BO_Mul; break;
8156 case tok::slash: Opc = BO_Div; break;
8157 case tok::percent: Opc = BO_Rem; break;
8158 case tok::plus: Opc = BO_Add; break;
8159 case tok::minus: Opc = BO_Sub; break;
8160 case tok::lessless: Opc = BO_Shl; break;
8161 case tok::greatergreater: Opc = BO_Shr; break;
8162 case tok::lessequal: Opc = BO_LE; break;
8163 case tok::less: Opc = BO_LT; break;
8164 case tok::greaterequal: Opc = BO_GE; break;
8165 case tok::greater: Opc = BO_GT; break;
8166 case tok::exclaimequal: Opc = BO_NE; break;
8167 case tok::equalequal: Opc = BO_EQ; break;
8168 case tok::amp: Opc = BO_And; break;
8169 case tok::caret: Opc = BO_Xor; break;
8170 case tok::pipe: Opc = BO_Or; break;
8171 case tok::ampamp: Opc = BO_LAnd; break;
8172 case tok::pipepipe: Opc = BO_LOr; break;
8173 case tok::equal: Opc = BO_Assign; break;
8174 case tok::starequal: Opc = BO_MulAssign; break;
8175 case tok::slashequal: Opc = BO_DivAssign; break;
8176 case tok::percentequal: Opc = BO_RemAssign; break;
8177 case tok::plusequal: Opc = BO_AddAssign; break;
8178 case tok::minusequal: Opc = BO_SubAssign; break;
8179 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8180 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8181 case tok::ampequal: Opc = BO_AndAssign; break;
8182 case tok::caretequal: Opc = BO_XorAssign; break;
8183 case tok::pipeequal: Opc = BO_OrAssign; break;
8184 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008185 }
8186 return Opc;
8187}
8188
John McCalle3027922010-08-25 11:45:40 +00008189static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00008190 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008191 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00008192 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00008193 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00008194 case tok::plusplus: Opc = UO_PreInc; break;
8195 case tok::minusminus: Opc = UO_PreDec; break;
8196 case tok::amp: Opc = UO_AddrOf; break;
8197 case tok::star: Opc = UO_Deref; break;
8198 case tok::plus: Opc = UO_Plus; break;
8199 case tok::minus: Opc = UO_Minus; break;
8200 case tok::tilde: Opc = UO_Not; break;
8201 case tok::exclaim: Opc = UO_LNot; break;
8202 case tok::kw___real: Opc = UO_Real; break;
8203 case tok::kw___imag: Opc = UO_Imag; break;
8204 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00008205 }
8206 return Opc;
8207}
8208
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008209/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8210/// This warning is only emitted for builtin assignment operations. It is also
8211/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +00008212static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008213 SourceLocation OpLoc) {
8214 if (!S.ActiveTemplateInstantiations.empty())
8215 return;
8216 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8217 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008218 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8219 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8220 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8221 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8222 if (!LHSDeclRef || !RHSDeclRef ||
8223 LHSDeclRef->getLocation().isMacroID() ||
8224 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008225 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008226 const ValueDecl *LHSDecl =
8227 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8228 const ValueDecl *RHSDecl =
8229 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8230 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008231 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008232 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008233 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008234 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008235 if (RefTy->getPointeeType().isVolatileQualified())
8236 return;
8237
8238 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +00008239 << LHSDeclRef->getType()
8240 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008241}
8242
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008243/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8244/// operator @p Opc at location @c TokLoc. This routine only supports
8245/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00008246ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008247 BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008248 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008249 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl67766732012-02-27 20:34:02 +00008250 // The syntax only allows initializer lists on the RHS of assignment,
8251 // so we don't need to worry about accepting invalid code for
8252 // non-assignment operators.
8253 // C++11 5.17p9:
8254 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8255 // of x = {} is x = T().
8256 InitializationKind Kind =
8257 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8258 InitializedEntity Entity =
8259 InitializedEntity::InitializeTemporary(LHSExpr->getType());
8260 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00008261 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
Sebastian Redl67766732012-02-27 20:34:02 +00008262 if (Init.isInvalid())
8263 return Init;
8264 RHSExpr = Init.take();
8265 }
8266
Richard Trieu4a287fb2011-09-07 01:49:20 +00008267 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008268 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008269 // The following two variables are used for compound assignment operators
8270 QualType CompLHSTy; // Type of LHS after promotions for computation
8271 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00008272 ExprValueKind VK = VK_RValue;
8273 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008274
8275 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008276 case BO_Assign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008277 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008278 if (getLangOpts().CPlusPlus &&
Richard Trieu4a287fb2011-09-07 01:49:20 +00008279 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8280 VK = LHS.get()->getValueKind();
8281 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008282 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008283 if (!ResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00008284 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008285 break;
John McCalle3027922010-08-25 11:45:40 +00008286 case BO_PtrMemD:
8287 case BO_PtrMemI:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008288 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008289 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00008290 break;
John McCalle3027922010-08-25 11:45:40 +00008291 case BO_Mul:
8292 case BO_Div:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008293 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00008294 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008295 break;
John McCalle3027922010-08-25 11:45:40 +00008296 case BO_Rem:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008297 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008298 break;
John McCalle3027922010-08-25 11:45:40 +00008299 case BO_Add:
Nico Weberccec40d2012-03-02 22:01:22 +00008300 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008301 break;
John McCalle3027922010-08-25 11:45:40 +00008302 case BO_Sub:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008303 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008304 break;
John McCalle3027922010-08-25 11:45:40 +00008305 case BO_Shl:
8306 case BO_Shr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008307 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008308 break;
John McCalle3027922010-08-25 11:45:40 +00008309 case BO_LE:
8310 case BO_LT:
8311 case BO_GE:
8312 case BO_GT:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008313 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008314 break;
John McCalle3027922010-08-25 11:45:40 +00008315 case BO_EQ:
8316 case BO_NE:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008317 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008318 break;
John McCalle3027922010-08-25 11:45:40 +00008319 case BO_And:
8320 case BO_Xor:
8321 case BO_Or:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008322 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008323 break;
John McCalle3027922010-08-25 11:45:40 +00008324 case BO_LAnd:
8325 case BO_LOr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008326 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008327 break;
John McCalle3027922010-08-25 11:45:40 +00008328 case BO_MulAssign:
8329 case BO_DivAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008330 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00008331 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008332 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008333 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8334 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008335 break;
John McCalle3027922010-08-25 11:45:40 +00008336 case BO_RemAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008337 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008338 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008339 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8340 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008341 break;
John McCalle3027922010-08-25 11:45:40 +00008342 case BO_AddAssign:
Nico Weberccec40d2012-03-02 22:01:22 +00008343 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu4a287fb2011-09-07 01:49:20 +00008344 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8345 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008346 break;
John McCalle3027922010-08-25 11:45:40 +00008347 case BO_SubAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008348 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8349 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8350 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008351 break;
John McCalle3027922010-08-25 11:45:40 +00008352 case BO_ShlAssign:
8353 case BO_ShrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008354 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008355 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008356 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8357 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008358 break;
John McCalle3027922010-08-25 11:45:40 +00008359 case BO_AndAssign:
8360 case BO_XorAssign:
8361 case BO_OrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008362 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008363 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008364 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8365 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008366 break;
John McCalle3027922010-08-25 11:45:40 +00008367 case BO_Comma:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008368 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikiebbafb8a2012-03-11 07:00:24 +00008369 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu4a287fb2011-09-07 01:49:20 +00008370 VK = RHS.get()->getValueKind();
8371 OK = RHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008372 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008373 break;
8374 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008375 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00008376 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008377
8378 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu4a287fb2011-09-07 01:49:20 +00008379 CheckArrayAccess(LHS.get());
8380 CheckArrayAccess(RHS.get());
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008381
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008382 if (CompResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00008383 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00008384 ResultTy, VK, OK, OpLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00008385 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieucfc491d2011-08-02 04:35:43 +00008386 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00008387 VK = VK_LValue;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008388 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008389 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008390 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00008391 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00008392 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008393}
8394
Sebastian Redl44615072009-10-27 12:10:02 +00008395/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8396/// operators are mixed in a way that suggests that the programmer forgot that
8397/// comparison operators have higher precedence. The most typical example of
8398/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00008399static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008400 SourceLocation OpLoc, Expr *LHSExpr,
8401 Expr *RHSExpr) {
Sebastian Redl44615072009-10-27 12:10:02 +00008402 typedef BinaryOperator BinOp;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008403 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8404 RHSopc = static_cast<BinOp::Opcode>(-1);
8405 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8406 LHSopc = BO->getOpcode();
8407 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8408 RHSopc = BO->getOpcode();
Sebastian Redl43028242009-10-26 15:24:15 +00008409
8410 // Subs are not binary operators.
Richard Trieu4a287fb2011-09-07 01:49:20 +00008411 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl43028242009-10-26 15:24:15 +00008412 return;
8413
8414 // Bitwise operations are sometimes used as eager logical ops.
8415 // Don't diagnose this.
Richard Trieu4a287fb2011-09-07 01:49:20 +00008416 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8417 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00008418 return;
8419
Richard Trieu4a287fb2011-09-07 01:49:20 +00008420 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8421 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00008422 if (!isLeftComp && !isRightComp) return;
8423
Richard Trieu4a287fb2011-09-07 01:49:20 +00008424 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8425 OpLoc)
8426 : SourceRange(OpLoc, RHSExpr->getLocEnd());
8427 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8428 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00008429 SourceRange ParensRange = isLeftComp ?
Richard Trieu4a287fb2011-09-07 01:49:20 +00008430 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8431 RHSExpr->getLocEnd())
8432 : SourceRange(LHSExpr->getLocStart(),
8433 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu73088052011-08-10 22:41:34 +00008434
8435 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8436 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8437 SuggestParentheses(Self, OpLoc,
8438 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Nico Webercdfb1ae2012-06-03 07:07:00 +00008439 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu73088052011-08-10 22:41:34 +00008440 SuggestParentheses(Self, OpLoc,
8441 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8442 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00008443}
8444
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008445/// \brief It accepts a '&' expr that is inside a '|' one.
8446/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8447/// in parentheses.
8448static void
8449EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8450 BinaryOperator *Bop) {
8451 assert(Bop->getOpcode() == BO_And);
8452 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8453 << Bop->getSourceRange() << OpLoc;
8454 SuggestParentheses(Self, Bop->getOperatorLoc(),
8455 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8456 Bop->getSourceRange());
8457}
8458
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008459/// \brief It accepts a '&&' expr that is inside a '||' one.
8460/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8461/// in parentheses.
8462static void
8463EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008464 BinaryOperator *Bop) {
8465 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008466 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8467 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008468 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008469 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008470 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008471}
8472
8473/// \brief Returns true if the given expression can be evaluated as a constant
8474/// 'true'.
8475static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8476 bool Res;
8477 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8478}
8479
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008480/// \brief Returns true if the given expression can be evaluated as a constant
8481/// 'false'.
8482static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8483 bool Res;
8484 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8485}
8486
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008487/// \brief Look for '&&' in the left hand of a '||' expr.
8488static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008489 Expr *LHSExpr, Expr *RHSExpr) {
8490 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008491 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008492 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008493 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008494 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008495 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8496 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8497 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8498 } else if (Bop->getOpcode() == BO_LOr) {
8499 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8500 // If it's "a || b && 1 || c" we didn't warn earlier for
8501 // "a || b && 1", but warn now.
8502 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8503 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8504 }
8505 }
8506 }
8507}
8508
8509/// \brief Look for '&&' in the right hand of a '||' expr.
8510static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008511 Expr *LHSExpr, Expr *RHSExpr) {
8512 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008513 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008514 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008515 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008516 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008517 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8518 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8519 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008520 }
8521 }
8522}
8523
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008524/// \brief Look for '&' in the left or right hand of a '|' expr.
8525static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8526 Expr *OrArg) {
8527 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8528 if (Bop->getOpcode() == BO_And)
8529 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8530 }
8531}
8532
Sebastian Redl43028242009-10-26 15:24:15 +00008533/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008534/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008535static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008536 SourceLocation OpLoc, Expr *LHSExpr,
8537 Expr *RHSExpr){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008538 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008539 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008540 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008541
8542 // Diagnose "arg1 & arg2 | arg3"
8543 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008544 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8545 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008546 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008547
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008548 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8549 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008550 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008551 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8552 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008553 }
Sebastian Redl43028242009-10-26 15:24:15 +00008554}
8555
Steve Naroff218bc2b2007-05-04 21:54:46 +00008556// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008557ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008558 tok::TokenKind Kind,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008559 Expr *LHSExpr, Expr *RHSExpr) {
John McCalle3027922010-08-25 11:45:40 +00008560 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008561 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8562 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008563
Sebastian Redl43028242009-10-26 15:24:15 +00008564 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008565 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +00008566
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008567 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor5287f092009-11-05 00:51:44 +00008568}
8569
John McCall526ab472011-10-25 17:37:35 +00008570/// Build an overloaded binary operator expression in the given scope.
8571static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8572 BinaryOperatorKind Opc,
8573 Expr *LHS, Expr *RHS) {
8574 // Find all of the overloaded operators visible from this
8575 // point. We perform both an operator-name lookup from the local
8576 // scope and an argument-dependent lookup based on the types of
8577 // the arguments.
8578 UnresolvedSet<16> Functions;
8579 OverloadedOperatorKind OverOp
8580 = BinaryOperator::getOverloadedOperator(Opc);
8581 if (Sc && OverOp != OO_None)
8582 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8583 RHS->getType(), Functions);
8584
8585 // Build the (potentially-overloaded, potentially-dependent)
8586 // binary operation.
8587 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8588}
8589
John McCalldadc5752010-08-24 06:29:42 +00008590ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008591 BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008592 Expr *LHSExpr, Expr *RHSExpr) {
John McCall9a43e122011-10-28 01:04:34 +00008593 // We want to end up calling one of checkPseudoObjectAssignment
8594 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8595 // both expressions are overloadable or either is type-dependent),
8596 // or CreateBuiltinBinOp (in any other case). We also want to get
8597 // any placeholder types out of the way.
8598
John McCall526ab472011-10-25 17:37:35 +00008599 // Handle pseudo-objects in the LHS.
8600 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8601 // Assignments with a pseudo-object l-value need special analysis.
8602 if (pty->getKind() == BuiltinType::PseudoObject &&
8603 BinaryOperator::isAssignmentOp(Opc))
8604 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8605
8606 // Don't resolve overloads if the other type is overloadable.
8607 if (pty->getKind() == BuiltinType::Overload) {
8608 // We can't actually test that if we still have a placeholder,
8609 // though. Fortunately, none of the exceptions we see in that
John McCall9a43e122011-10-28 01:04:34 +00008610 // code below are valid when the LHS is an overload set. Note
8611 // that an overload set can be dependently-typed, but it never
8612 // instantiates to having an overloadable type.
John McCall526ab472011-10-25 17:37:35 +00008613 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8614 if (resolvedRHS.isInvalid()) return ExprError();
8615 RHSExpr = resolvedRHS.take();
8616
John McCall9a43e122011-10-28 01:04:34 +00008617 if (RHSExpr->isTypeDependent() ||
8618 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008619 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8620 }
8621
8622 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8623 if (LHS.isInvalid()) return ExprError();
8624 LHSExpr = LHS.take();
8625 }
8626
8627 // Handle pseudo-objects in the RHS.
8628 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8629 // An overload in the RHS can potentially be resolved by the type
8630 // being assigned to.
John McCall9a43e122011-10-28 01:04:34 +00008631 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8632 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8633 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8634
Eli Friedman419b1ff2012-01-17 21:27:43 +00008635 if (LHSExpr->getType()->isOverloadableType())
8636 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8637
John McCall526ab472011-10-25 17:37:35 +00008638 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCall9a43e122011-10-28 01:04:34 +00008639 }
John McCall526ab472011-10-25 17:37:35 +00008640
8641 // Don't resolve overloads if the other type is overloadable.
8642 if (pty->getKind() == BuiltinType::Overload &&
8643 LHSExpr->getType()->isOverloadableType())
8644 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8645
8646 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8647 if (!resolvedRHS.isUsable()) return ExprError();
8648 RHSExpr = resolvedRHS.take();
8649 }
8650
David Blaikiebbafb8a2012-03-11 07:00:24 +00008651 if (getLangOpts().CPlusPlus) {
John McCall9a43e122011-10-28 01:04:34 +00008652 // If either expression is type-dependent, always build an
8653 // overloaded op.
8654 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8655 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008656
John McCall9a43e122011-10-28 01:04:34 +00008657 // Otherwise, build an overloaded op if either expression has an
8658 // overloadable type.
8659 if (LHSExpr->getType()->isOverloadableType() ||
8660 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008661 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb5d49352009-01-19 22:31:54 +00008662 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008663
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008664 // Build a built-in binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008665 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008666}
8667
John McCalldadc5752010-08-24 06:29:42 +00008668ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008669 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008670 Expr *InputExpr) {
8671 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008672 ExprValueKind VK = VK_RValue;
8673 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008674 QualType resultType;
8675 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008676 case UO_PreInc:
8677 case UO_PreDec:
8678 case UO_PostInc:
8679 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008680 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008681 Opc == UO_PreInc ||
8682 Opc == UO_PostInc,
8683 Opc == UO_PreInc ||
8684 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008685 break;
John McCalle3027922010-08-25 11:45:40 +00008686 case UO_AddrOf:
John McCall526ab472011-10-25 17:37:35 +00008687 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008688 break;
John McCall31996342011-04-07 08:22:57 +00008689 case UO_Deref: {
John Wiegley01296292011-04-08 18:41:53 +00008690 Input = DefaultFunctionArrayLvalueConversion(Input.take());
Eli Friedman34866c72012-08-31 00:14:07 +00008691 if (Input.isInvalid()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008692 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008693 break;
John McCall31996342011-04-07 08:22:57 +00008694 }
John McCalle3027922010-08-25 11:45:40 +00008695 case UO_Plus:
8696 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008697 Input = UsualUnaryConversions(Input.take());
8698 if (Input.isInvalid()) return ExprError();
8699 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008700 if (resultType->isDependentType())
8701 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008702 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8703 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008704 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008705 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregord08452f2008-11-19 15:42:04 +00008706 resultType->isEnumeralType())
8707 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008708 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008709 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008710 resultType->isPointerType())
8711 break;
8712
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008713 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008714 << resultType << Input.get()->getSourceRange());
8715
John McCalle3027922010-08-25 11:45:40 +00008716 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008717 Input = UsualUnaryConversions(Input.take());
8718 if (Input.isInvalid()) return ExprError();
8719 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008720 if (resultType->isDependentType())
8721 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008722 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8723 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8724 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008725 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008726 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008727 else if (resultType->hasIntegerRepresentation())
8728 break;
John McCall526ab472011-10-25 17:37:35 +00008729 else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008730 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008731 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008732 }
Steve Naroff35d85152007-05-07 00:24:15 +00008733 break;
John Wiegley01296292011-04-08 18:41:53 +00008734
John McCalle3027922010-08-25 11:45:40 +00008735 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008736 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008737 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8738 if (Input.isInvalid()) return ExprError();
8739 resultType = Input.get()->getType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00008740
8741 // Though we still have to promote half FP to float...
8742 if (resultType->isHalfType()) {
8743 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8744 resultType = Context.FloatTy;
8745 }
8746
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008747 if (resultType->isDependentType())
8748 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008749 if (resultType->isScalarType()) {
8750 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008751 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008752 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8753 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008754 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8755 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008756 }
Tanya Lattner3dd33b22012-01-19 01:16:16 +00008757 } else if (resultType->isExtVectorType()) {
Tanya Lattner20248222012-01-16 21:02:28 +00008758 // Vector logical not returns the signed variant of the operand type.
8759 resultType = GetSignedVectorType(resultType);
8760 break;
John McCall36226622010-10-12 02:09:17 +00008761 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008762 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008763 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008764 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008765
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008766 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008767 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008768 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008769 break;
John McCalle3027922010-08-25 11:45:40 +00008770 case UO_Real:
8771 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008772 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smith0b6b8e42012-02-18 20:53:32 +00008773 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8774 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley01296292011-04-08 18:41:53 +00008775 if (Input.isInvalid()) return ExprError();
Richard Smith0b6b8e42012-02-18 20:53:32 +00008776 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8777 if (Input.get()->getValueKind() != VK_RValue &&
8778 Input.get()->getObjectKind() == OK_Ordinary)
8779 VK = Input.get()->getValueKind();
David Blaikiebbafb8a2012-03-11 07:00:24 +00008780 } else if (!getLangOpts().CPlusPlus) {
Richard Smith0b6b8e42012-02-18 20:53:32 +00008781 // In C, a volatile scalar is read by __imag. In C++, it is not.
8782 Input = DefaultLvalueConversion(Input.take());
8783 }
Chris Lattner30b5dd02007-08-24 21:16:53 +00008784 break;
John McCalle3027922010-08-25 11:45:40 +00008785 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008786 resultType = Input.get()->getType();
8787 VK = Input.get()->getValueKind();
8788 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008789 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008790 }
John Wiegley01296292011-04-08 18:41:53 +00008791 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008792 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008793
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008794 // Check for array bounds violations in the operand of the UnaryOperator,
8795 // except for the '*' and '&' operators that have to be handled specially
8796 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8797 // that are explicitly defined as valid by the standard).
8798 if (Opc != UO_AddrOf && Opc != UO_Deref)
8799 CheckArrayAccess(Input.get());
8800
John Wiegley01296292011-04-08 18:41:53 +00008801 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008802 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008803}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008804
Douglas Gregor72341032011-12-14 21:23:13 +00008805/// \brief Determine whether the given expression is a qualified member
8806/// access expression, of a form that could be turned into a pointer to member
8807/// with the address-of operator.
8808static bool isQualifiedMemberAccess(Expr *E) {
8809 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8810 if (!DRE->getQualifier())
8811 return false;
8812
8813 ValueDecl *VD = DRE->getDecl();
8814 if (!VD->isCXXClassMember())
8815 return false;
8816
8817 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8818 return true;
8819 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8820 return Method->isInstance();
8821
8822 return false;
8823 }
8824
8825 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8826 if (!ULE->getQualifier())
8827 return false;
8828
8829 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8830 DEnd = ULE->decls_end();
8831 D != DEnd; ++D) {
8832 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8833 if (Method->isInstance())
8834 return true;
8835 } else {
8836 // Overload set does not contain methods.
8837 break;
8838 }
8839 }
8840
8841 return false;
8842 }
8843
8844 return false;
8845}
8846
John McCalldadc5752010-08-24 06:29:42 +00008847ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008848 UnaryOperatorKind Opc, Expr *Input) {
John McCall526ab472011-10-25 17:37:35 +00008849 // First things first: handle placeholders so that the
8850 // overloaded-operator check considers the right type.
8851 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8852 // Increment and decrement of pseudo-object references.
8853 if (pty->getKind() == BuiltinType::PseudoObject &&
8854 UnaryOperator::isIncrementDecrementOp(Opc))
8855 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8856
8857 // extension is always a builtin operator.
8858 if (Opc == UO_Extension)
8859 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8860
8861 // & gets special logic for several kinds of placeholder.
8862 // The builtin code knows what to do.
8863 if (Opc == UO_AddrOf &&
8864 (pty->getKind() == BuiltinType::Overload ||
8865 pty->getKind() == BuiltinType::UnknownAny ||
8866 pty->getKind() == BuiltinType::BoundMember))
8867 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8868
8869 // Anything else needs to be handled now.
8870 ExprResult Result = CheckPlaceholderExpr(Input);
8871 if (Result.isInvalid()) return ExprError();
8872 Input = Result.take();
8873 }
8874
David Blaikiebbafb8a2012-03-11 07:00:24 +00008875 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregor72341032011-12-14 21:23:13 +00008876 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8877 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008878 // Find all of the overloaded operators visible from this
8879 // point. We perform both an operator-name lookup from the local
8880 // scope and an argument-dependent lookup based on the types of
8881 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008882 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008883 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008884 if (S && OverOp != OO_None)
8885 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8886 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008887
John McCallb268a282010-08-23 23:25:46 +00008888 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008889 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008890
John McCallb268a282010-08-23 23:25:46 +00008891 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008892}
8893
Douglas Gregor5287f092009-11-05 00:51:44 +00008894// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008895ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008896 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008897 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008898}
8899
Steve Naroff66356bd2007-09-16 14:56:35 +00008900/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008901ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008902 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008903 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008904 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008905 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008906 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008907}
8908
John McCall31168b02011-06-15 23:02:42 +00008909/// Given the last statement in a statement-expression, check whether
8910/// the result is a producing expression (like a call to an
8911/// ns_returns_retained function) and, if so, rebuild it to hoist the
8912/// release out of the full-expression. Otherwise, return null.
8913/// Cannot fail.
Richard Trieuba63ce62011-09-09 01:45:06 +00008914static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCall31168b02011-06-15 23:02:42 +00008915 // Should always be wrapped with one of these.
Richard Trieuba63ce62011-09-09 01:45:06 +00008916 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCall31168b02011-06-15 23:02:42 +00008917 if (!cleanups) return 0;
8918
8919 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall2d637d22011-09-10 06:18:15 +00008920 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCall31168b02011-06-15 23:02:42 +00008921 return 0;
8922
8923 // Splice out the cast. This shouldn't modify any interesting
8924 // features of the statement.
8925 Expr *producer = cast->getSubExpr();
8926 assert(producer->getType() == cast->getType());
8927 assert(producer->getValueKind() == cast->getValueKind());
8928 cleanups->setSubExpr(producer);
8929 return cleanups;
8930}
8931
John McCall3abee492012-04-04 01:27:53 +00008932void Sema::ActOnStartStmtExpr() {
8933 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
8934}
8935
8936void Sema::ActOnStmtExprError() {
John McCalled7b2782012-04-06 18:20:53 +00008937 // Note that function is also called by TreeTransform when leaving a
8938 // StmtExpr scope without rebuilding anything.
8939
John McCall3abee492012-04-04 01:27:53 +00008940 DiscardCleanupsInEvaluationContext();
8941 PopExpressionEvaluationContext();
8942}
8943
John McCalldadc5752010-08-24 06:29:42 +00008944ExprResult
John McCallb268a282010-08-23 23:25:46 +00008945Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008946 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008947 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8948 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8949
John McCall3abee492012-04-04 01:27:53 +00008950 if (hasAnyUnrecoverableErrorsInThisFunction())
8951 DiscardCleanupsInEvaluationContext();
8952 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
8953 PopExpressionEvaluationContext();
8954
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008955 bool isFileScope
8956 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008957 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008958 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008959
Chris Lattner366727f2007-07-24 16:58:17 +00008960 // FIXME: there are a variety of strange constraints to enforce here, for
8961 // example, it is not possible to goto into a stmt expression apparently.
8962 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008963
Chris Lattner366727f2007-07-24 16:58:17 +00008964 // If there are sub stmts in the compound stmt, take the type of the last one
8965 // as the type of the stmtexpr.
8966 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008967 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008968 if (!Compound->body_empty()) {
8969 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008970 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008971 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008972 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8973 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008974 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008975 }
John McCall31168b02011-06-15 23:02:42 +00008976
John Wiegley01296292011-04-08 18:41:53 +00008977 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008978 // Do function/array conversion on the last expression, but not
8979 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008980 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8981 if (LastExpr.isInvalid())
8982 return ExprError();
8983 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008984
John Wiegley01296292011-04-08 18:41:53 +00008985 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008986 // In ARC, if the final expression ends in a consume, splice
8987 // the consume out and bind it later. In the alternate case
8988 // (when dealing with a retainable type), the result
8989 // initialization will create a produce. In both cases the
8990 // result will be +1, and we'll need to balance that out with
8991 // a bind.
8992 if (Expr *rebuiltLastStmt
8993 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8994 LastExpr = rebuiltLastStmt;
8995 } else {
8996 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008997 InitializedEntity::InitializeResult(LPLoc,
8998 Ty,
8999 false),
9000 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00009001 LastExpr);
9002 }
9003
John Wiegley01296292011-04-08 18:41:53 +00009004 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009005 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009006 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009007 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00009008 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009009 else
John Wiegley01296292011-04-08 18:41:53 +00009010 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009011 StmtExprMayBindToTemp = true;
9012 }
9013 }
9014 }
Chris Lattner944d3062008-07-26 19:51:01 +00009015 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009016
Eli Friedmanba961a92009-03-23 00:24:07 +00009017 // FIXME: Check that expression type is complete/non-abstract; statement
9018 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009019 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9020 if (StmtExprMayBindToTemp)
9021 return MaybeBindToTemporary(ResStmtExpr);
9022 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00009023}
Steve Naroff78864672007-08-01 22:05:33 +00009024
John McCalldadc5752010-08-24 06:29:42 +00009025ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009026 TypeSourceInfo *TInfo,
9027 OffsetOfComponent *CompPtr,
9028 unsigned NumComponents,
9029 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00009030 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009031 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00009032 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00009033
Chris Lattnerf17bd422007-08-30 17:45:32 +00009034 // We must have at least one component that refers to the type, and the first
9035 // one is known to be a field designator. Verify that the ArgTy represents
9036 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009037 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00009038 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9039 << ArgTy << TypeRange);
9040
9041 // Type must be complete per C99 7.17p3 because a declaring a variable
9042 // with an incomplete type would be ill-formed.
9043 if (!Dependent
9044 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009045 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor882211c2010-04-28 22:16:22 +00009046 return ExprError();
9047
Chris Lattner78502cf2007-08-31 21:49:13 +00009048 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9049 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00009050 // FIXME: This diagnostic isn't actually visible because the location is in
9051 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00009052 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00009053 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9054 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00009055
9056 bool DidWarnAboutNonPOD = false;
9057 QualType CurrentType = ArgTy;
9058 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009059 SmallVector<OffsetOfNode, 4> Comps;
9060 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00009061 for (unsigned i = 0; i != NumComponents; ++i) {
9062 const OffsetOfComponent &OC = CompPtr[i];
9063 if (OC.isBrackets) {
9064 // Offset of an array sub-field. TODO: Should we allow vector elements?
9065 if (!CurrentType->isDependentType()) {
9066 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9067 if(!AT)
9068 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9069 << CurrentType);
9070 CurrentType = AT->getElementType();
9071 } else
9072 CurrentType = Context.DependentTy;
9073
Richard Smith9fcc5c32011-10-17 23:29:39 +00009074 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9075 if (IdxRval.isInvalid())
9076 return ExprError();
9077 Expr *Idx = IdxRval.take();
9078
Douglas Gregor882211c2010-04-28 22:16:22 +00009079 // The expression must be an integral expression.
9080 // FIXME: An integral constant expression?
Douglas Gregor882211c2010-04-28 22:16:22 +00009081 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9082 !Idx->getType()->isIntegerType())
9083 return ExprError(Diag(Idx->getLocStart(),
9084 diag::err_typecheck_subscript_not_integer)
9085 << Idx->getSourceRange());
Richard Smitheda612882011-10-17 05:48:07 +00009086
Douglas Gregor882211c2010-04-28 22:16:22 +00009087 // Record this array index.
9088 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smith9fcc5c32011-10-17 23:29:39 +00009089 Exprs.push_back(Idx);
Douglas Gregor882211c2010-04-28 22:16:22 +00009090 continue;
9091 }
9092
9093 // Offset of a field.
9094 if (CurrentType->isDependentType()) {
9095 // We have the offset of a field, but we can't look into the dependent
9096 // type. Just record the identifier of the field.
9097 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9098 CurrentType = Context.DependentTy;
9099 continue;
9100 }
9101
9102 // We need to have a complete type to look into.
9103 if (RequireCompleteType(OC.LocStart, CurrentType,
9104 diag::err_offsetof_incomplete_type))
9105 return ExprError();
9106
9107 // Look for the designated field.
9108 const RecordType *RC = CurrentType->getAs<RecordType>();
9109 if (!RC)
9110 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9111 << CurrentType);
9112 RecordDecl *RD = RC->getDecl();
9113
9114 // C++ [lib.support.types]p5:
9115 // The macro offsetof accepts a restricted set of type arguments in this
9116 // International Standard. type shall be a POD structure or a POD union
9117 // (clause 9).
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009118 // C++11 [support.types]p4:
9119 // If type is not a standard-layout class (Clause 9), the results are
9120 // undefined.
Douglas Gregor882211c2010-04-28 22:16:22 +00009121 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009122 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9123 unsigned DiagID =
9124 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9125 : diag::warn_offsetof_non_pod_type;
9126
9127 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00009128 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009129 PDiag(DiagID)
Douglas Gregor882211c2010-04-28 22:16:22 +00009130 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9131 << CurrentType))
9132 DidWarnAboutNonPOD = true;
9133 }
9134
9135 // Look for the field.
9136 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9137 LookupQualifiedName(R, RD);
9138 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009139 IndirectFieldDecl *IndirectMemberDecl = 0;
9140 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00009141 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00009142 MemberDecl = IndirectMemberDecl->getAnonField();
9143 }
9144
Douglas Gregor882211c2010-04-28 22:16:22 +00009145 if (!MemberDecl)
9146 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9147 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9148 OC.LocEnd));
9149
Douglas Gregor10982ea2010-04-28 22:36:06 +00009150 // C99 7.17p3:
9151 // (If the specified member is a bit-field, the behavior is undefined.)
9152 //
9153 // We diagnose this as an error.
Richard Smithcaf33902011-10-10 18:28:20 +00009154 if (MemberDecl->isBitField()) {
Douglas Gregor10982ea2010-04-28 22:36:06 +00009155 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9156 << MemberDecl->getDeclName()
9157 << SourceRange(BuiltinLoc, RParenLoc);
9158 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9159 return ExprError();
9160 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009161
9162 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009163 if (IndirectMemberDecl)
9164 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009165
Douglas Gregord1702062010-04-29 00:18:15 +00009166 // If the member was found in a base class, introduce OffsetOfNodes for
9167 // the base class indirections.
9168 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9169 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009170 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00009171 CXXBasePath &Path = Paths.front();
9172 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9173 B != BEnd; ++B)
9174 Comps.push_back(OffsetOfNode(B->Base));
9175 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009176
Francois Pichet783dd6e2010-11-21 06:08:52 +00009177 if (IndirectMemberDecl) {
9178 for (IndirectFieldDecl::chain_iterator FI =
9179 IndirectMemberDecl->chain_begin(),
9180 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9181 assert(isa<FieldDecl>(*FI));
9182 Comps.push_back(OffsetOfNode(OC.LocStart,
9183 cast<FieldDecl>(*FI), OC.LocEnd));
9184 }
9185 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00009186 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00009187
Douglas Gregor882211c2010-04-28 22:16:22 +00009188 CurrentType = MemberDecl->getType().getNonReferenceType();
9189 }
9190
9191 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00009192 TInfo, Comps, Exprs, RParenLoc));
Douglas Gregor882211c2010-04-28 22:16:22 +00009193}
Mike Stump4e1f26a2009-02-19 03:04:26 +00009194
John McCalldadc5752010-08-24 06:29:42 +00009195ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00009196 SourceLocation BuiltinLoc,
9197 SourceLocation TypeLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009198 ParsedType ParsedArgTy,
John McCall36226622010-10-12 02:09:17 +00009199 OffsetOfComponent *CompPtr,
9200 unsigned NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00009201 SourceLocation RParenLoc) {
John McCall36226622010-10-12 02:09:17 +00009202
Douglas Gregor882211c2010-04-28 22:16:22 +00009203 TypeSourceInfo *ArgTInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00009204 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor882211c2010-04-28 22:16:22 +00009205 if (ArgTy.isNull())
9206 return ExprError();
9207
Eli Friedman06dcfd92010-08-05 10:15:45 +00009208 if (!ArgTInfo)
9209 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9210
9211 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00009212 RParenLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00009213}
9214
9215
John McCalldadc5752010-08-24 06:29:42 +00009216ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009217 Expr *CondExpr,
9218 Expr *LHSExpr, Expr *RHSExpr,
9219 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00009220 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9221
John McCall7decc9e2010-11-18 06:31:45 +00009222 ExprValueKind VK = VK_RValue;
9223 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009224 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00009225 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00009226 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009227 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00009228 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009229 } else {
9230 // The conditional expression is required to be a constant expression.
9231 llvm::APSInt condEval(32);
Douglas Gregore2b37442012-05-04 22:38:52 +00009232 ExprResult CondICE
9233 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9234 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009235 if (CondICE.isInvalid())
9236 return ExprError();
9237 CondExpr = CondICE.take();
Steve Naroff9efdabc2007-08-03 21:21:27 +00009238
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009239 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00009240 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9241
9242 resType = ActiveExpr->getType();
9243 ValueDependent = ActiveExpr->isValueDependent();
9244 VK = ActiveExpr->getValueKind();
9245 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009246 }
9247
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009248 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00009249 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00009250 resType->isDependentType(),
9251 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00009252}
9253
Steve Naroffc540d662008-09-03 18:15:37 +00009254//===----------------------------------------------------------------------===//
9255// Clang Extensions.
9256//===----------------------------------------------------------------------===//
9257
9258/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuba63ce62011-09-09 01:45:06 +00009259void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009260 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuba63ce62011-09-09 01:45:06 +00009261 PushBlockScope(CurScope, Block);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009262 CurContext->addDecl(Block);
Richard Trieuba63ce62011-09-09 01:45:06 +00009263 if (CurScope)
9264 PushDeclContext(CurScope, Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009265 else
9266 CurContext = Block;
John McCallf1a3c2a2011-11-11 03:19:12 +00009267
Eli Friedman34b49062012-01-26 03:00:14 +00009268 getCurBlock()->HasImplicitReturnType = true;
9269
John McCallf1a3c2a2011-11-11 03:19:12 +00009270 // Enter a new evaluation context to insulate the block from any
9271 // cleanups from the enclosing full-expression.
9272 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009273}
9274
Douglas Gregor7efd007c2012-06-15 16:59:29 +00009275void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9276 Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00009277 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00009278 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009279 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009280
John McCall8cb7bdf2010-06-04 23:28:52 +00009281 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00009282 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00009283
Douglas Gregor7efd007c2012-06-15 16:59:29 +00009284 // FIXME: We should allow unexpanded parameter packs here, but that would,
9285 // in turn, make the block expression contain unexpanded parameter packs.
9286 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9287 // Drop the parameters.
9288 FunctionProtoType::ExtProtoInfo EPI;
9289 EPI.HasTrailingReturn = false;
9290 EPI.TypeQuals |= DeclSpec::TQ_const;
9291 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9292 EPI);
9293 Sig = Context.getTrivialTypeSourceInfo(T);
9294 }
9295
John McCall3882ace2011-01-05 12:14:39 +00009296 // GetTypeForDeclarator always produces a function type for a block
9297 // literal signature. Furthermore, it is always a FunctionProtoType
9298 // unless the function was written with a typedef.
9299 assert(T->isFunctionType() &&
9300 "GetTypeForDeclarator made a non-function block signature");
9301
9302 // Look for an explicit signature in that function type.
9303 FunctionProtoTypeLoc ExplicitSignature;
9304
9305 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9306 if (isa<FunctionProtoTypeLoc>(tmp)) {
9307 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9308
9309 // Check whether that explicit signature was synthesized by
9310 // GetTypeForDeclarator. If so, don't save that as part of the
9311 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00009312 if (ExplicitSignature.getLocalRangeBegin() ==
9313 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00009314 // This would be much cheaper if we stored TypeLocs instead of
9315 // TypeSourceInfos.
9316 TypeLoc Result = ExplicitSignature.getResultLoc();
9317 unsigned Size = Result.getFullDataSize();
9318 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9319 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9320
9321 ExplicitSignature = FunctionProtoTypeLoc();
9322 }
John McCalla3ccba02010-06-04 11:21:44 +00009323 }
Mike Stump11289f42009-09-09 15:08:12 +00009324
John McCall3882ace2011-01-05 12:14:39 +00009325 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9326 CurBlock->FunctionType = T;
9327
9328 const FunctionType *Fn = T->getAs<FunctionType>();
9329 QualType RetTy = Fn->getResultType();
9330 bool isVariadic =
9331 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9332
John McCall8e346702010-06-04 19:02:56 +00009333 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00009334
John McCalla3ccba02010-06-04 11:21:44 +00009335 // Don't allow returning a objc interface by value.
9336 if (RetTy->isObjCObjectType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009337 Diag(ParamInfo.getLocStart(),
John McCalla3ccba02010-06-04 11:21:44 +00009338 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9339 return;
9340 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009341
John McCalla3ccba02010-06-04 11:21:44 +00009342 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00009343 // return type. TODO: what should we do with declarators like:
9344 // ^ * { ... }
9345 // If the answer is "apply template argument deduction"....
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009346 if (RetTy != Context.DependentTy) {
John McCalla3ccba02010-06-04 11:21:44 +00009347 CurBlock->ReturnType = RetTy;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009348 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman34b49062012-01-26 03:00:14 +00009349 CurBlock->HasImplicitReturnType = false;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009350 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009351
John McCalla3ccba02010-06-04 11:21:44 +00009352 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009353 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00009354 if (ExplicitSignature) {
9355 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9356 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009357 if (Param->getIdentifier() == 0 &&
9358 !Param->isImplicit() &&
9359 !Param->isInvalidDecl() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00009360 !getLangOpts().CPlusPlus)
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009361 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00009362 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009363 }
John McCalla3ccba02010-06-04 11:21:44 +00009364
9365 // Fake up parameter variables if we have a typedef, like
9366 // ^ fntype { ... }
9367 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9368 for (FunctionProtoType::arg_type_iterator
9369 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9370 ParmVarDecl *Param =
9371 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009372 ParamInfo.getLocStart(),
John McCalla3ccba02010-06-04 11:21:44 +00009373 *I);
John McCall8e346702010-06-04 19:02:56 +00009374 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00009375 }
Steve Naroffc540d662008-09-03 18:15:37 +00009376 }
John McCalla3ccba02010-06-04 11:21:44 +00009377
John McCall8e346702010-06-04 19:02:56 +00009378 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00009379 if (!Params.empty()) {
David Blaikie9c70e042011-09-21 18:16:56 +00009380 CurBlock->TheDecl->setParams(Params);
Douglas Gregorb524d902010-11-01 18:37:59 +00009381 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9382 CurBlock->TheDecl->param_end(),
9383 /*CheckParameterNames=*/false);
9384 }
9385
John McCalla3ccba02010-06-04 11:21:44 +00009386 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00009387 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00009388
John McCalla3ccba02010-06-04 11:21:44 +00009389 // Put the parameter variables in scope. We can bail out immediately
9390 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00009391 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00009392 return;
9393
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009394 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00009395 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9396 (*AI)->setOwningFunction(CurBlock->TheDecl);
9397
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009398 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009399 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009400 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00009401
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009402 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009403 }
John McCallf7b2fb52010-01-22 00:28:27 +00009404 }
Steve Naroffc540d662008-09-03 18:15:37 +00009405}
9406
9407/// ActOnBlockError - If there is an error parsing a block, this callback
9408/// is invoked to pop the information about the block from the action impl.
9409void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCallf1a3c2a2011-11-11 03:19:12 +00009410 // Leave the expression-evaluation context.
9411 DiscardCleanupsInEvaluationContext();
9412 PopExpressionEvaluationContext();
9413
Steve Naroffc540d662008-09-03 18:15:37 +00009414 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00009415 PopDeclContext();
Eli Friedman71c80552012-01-05 03:35:19 +00009416 PopFunctionScopeInfo();
Steve Naroffc540d662008-09-03 18:15:37 +00009417}
9418
9419/// ActOnBlockStmtExpr - This is called when the body of a block statement
9420/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00009421ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00009422 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00009423 // If blocks are disabled, emit an error.
9424 if (!LangOpts.Blocks)
9425 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00009426
John McCallf1a3c2a2011-11-11 03:19:12 +00009427 // Leave the expression-evaluation context.
John McCall85110b42012-03-08 22:00:17 +00009428 if (hasAnyUnrecoverableErrorsInThisFunction())
9429 DiscardCleanupsInEvaluationContext();
John McCallf1a3c2a2011-11-11 03:19:12 +00009430 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9431 PopExpressionEvaluationContext();
9432
Douglas Gregor9a28e842010-03-01 23:15:13 +00009433 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Jordan Rosed39e5f12012-07-02 21:19:23 +00009434
9435 if (BSI->HasImplicitReturnType)
9436 deduceClosureReturnType(*BSI);
9437
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009438 PopDeclContext();
9439
Steve Naroffc540d662008-09-03 18:15:37 +00009440 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00009441 if (!BSI->ReturnType.isNull())
9442 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009443
Mike Stump3bf1ab42009-07-28 22:04:01 +00009444 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00009445 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00009446
John McCallc63de662011-02-02 13:00:07 +00009447 // Set the captured variables on the block.
Eli Friedman20139d32012-01-11 02:36:31 +00009448 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9449 SmallVector<BlockDecl::Capture, 4> Captures;
9450 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9451 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9452 if (Cap.isThisCapture())
9453 continue;
Eli Friedman24af8502012-02-03 22:47:37 +00009454 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedman20139d32012-01-11 02:36:31 +00009455 Cap.isNested(), Cap.getCopyExpr());
9456 Captures.push_back(NewCap);
9457 }
9458 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9459 BSI->CXXThisCaptureIndex != 0);
John McCallc63de662011-02-02 13:00:07 +00009460
John McCall8e346702010-06-04 19:02:56 +00009461 // If the user wrote a function type in some form, try to use that.
9462 if (!BSI->FunctionType.isNull()) {
9463 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9464
9465 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9466 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9467
9468 // Turn protoless block types into nullary block types.
9469 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009470 FunctionProtoType::ExtProtoInfo EPI;
9471 EPI.ExtInfo = Ext;
9472 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009473
9474 // Otherwise, if we don't need to change anything about the function type,
9475 // preserve its sugar structure.
9476 } else if (FTy->getResultType() == RetTy &&
9477 (!NoReturn || FTy->getNoReturnAttr())) {
9478 BlockTy = BSI->FunctionType;
9479
9480 // Otherwise, make the minimal modifications to the function type.
9481 } else {
9482 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00009483 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9484 EPI.TypeQuals = 0; // FIXME: silently?
9485 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00009486 BlockTy = Context.getFunctionType(RetTy,
9487 FPT->arg_type_begin(),
9488 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00009489 EPI);
John McCall8e346702010-06-04 19:02:56 +00009490 }
9491
9492 // If we don't have a function type, just build one from nothing.
9493 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00009494 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00009495 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00009496 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009497 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009498
John McCall8e346702010-06-04 19:02:56 +00009499 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9500 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00009501 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009502
Chris Lattner45542ea2009-04-19 05:28:12 +00009503 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00009504 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor5d944db2012-08-17 05:12:08 +00009505 !hasAnyUnrecoverableErrorsInThisFunction() &&
9506 !PP.isCodeCompletionEnabled())
John McCallb268a282010-08-23 23:25:46 +00009507 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00009508
Chris Lattner60f84492011-02-17 23:58:47 +00009509 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009510
Jordan Rosed39e5f12012-07-02 21:19:23 +00009511 // Try to apply the named return value optimization. We have to check again
9512 // if we can do this, though, because blocks keep return statements around
9513 // to deduce an implicit return type.
9514 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9515 !BSI->TheDecl->isDependentContext())
9516 computeNRVO(Body, getCurBlock());
Douglas Gregor49695f02011-09-06 20:46:03 +00009517
Benjamin Kramera4fb8362011-07-12 14:11:05 +00009518 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9519 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedman71c80552012-01-05 03:35:19 +00009520 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramera4fb8362011-07-12 14:11:05 +00009521
John McCall28fc7092011-11-10 05:35:25 +00009522 // If the block isn't obviously global, i.e. it captures anything at
John McCalld2393872012-04-13 01:08:17 +00009523 // all, then we need to do a few things in the surrounding context:
John McCall28fc7092011-11-10 05:35:25 +00009524 if (Result->getBlockDecl()->hasCaptures()) {
John McCalld2393872012-04-13 01:08:17 +00009525 // First, this expression has a new cleanup object.
John McCall28fc7092011-11-10 05:35:25 +00009526 ExprCleanupObjects.push_back(Result->getBlockDecl());
9527 ExprNeedsCleanups = true;
John McCalld2393872012-04-13 01:08:17 +00009528
9529 // It also gets a branch-protected scope if any of the captured
9530 // variables needs destruction.
9531 for (BlockDecl::capture_const_iterator
9532 ci = Result->getBlockDecl()->capture_begin(),
9533 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9534 const VarDecl *var = ci->getVariable();
9535 if (var->getType().isDestructedType() != QualType::DK_none) {
9536 getCurFunction()->setHasBranchProtectedScope();
9537 break;
9538 }
9539 }
John McCall28fc7092011-11-10 05:35:25 +00009540 }
Fariborz Jahanian197c68c2012-03-06 18:41:35 +00009541
Douglas Gregor9a28e842010-03-01 23:15:13 +00009542 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00009543}
9544
John McCalldadc5752010-08-24 06:29:42 +00009545ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009546 Expr *E, ParsedType Ty,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009547 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00009548 TypeSourceInfo *TInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00009549 GetTypeFromParser(Ty, &TInfo);
9550 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00009551}
9552
John McCalldadc5752010-08-24 06:29:42 +00009553ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00009554 Expr *E, TypeSourceInfo *TInfo,
9555 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00009556 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00009557
Eli Friedman121ba0c2008-08-09 23:32:40 +00009558 // Get the va_list type
9559 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00009560 if (VaListType->isArrayType()) {
9561 // Deal with implicit array decay; for example, on x86-64,
9562 // va_list is an array, but it's supposed to decay to
9563 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00009564 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00009565 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00009566 ExprResult Result = UsualUnaryConversions(E);
9567 if (Result.isInvalid())
9568 return ExprError();
9569 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00009570 } else {
9571 // Otherwise, the va_list argument must be an l-value because
9572 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00009573 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00009574 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00009575 return ExprError();
9576 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00009577
Douglas Gregorad3150c2009-05-19 23:10:31 +00009578 if (!E->isTypeDependent() &&
9579 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009580 return ExprError(Diag(E->getLocStart(),
9581 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00009582 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00009583 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009584
David Majnemerc75d1a12011-06-14 05:17:32 +00009585 if (!TInfo->getType()->isDependentType()) {
9586 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009587 diag::err_second_parameter_to_va_arg_incomplete,
9588 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +00009589 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00009590
David Majnemerc75d1a12011-06-14 05:17:32 +00009591 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregorae298422012-05-04 17:09:59 +00009592 TInfo->getType(),
9593 diag::err_second_parameter_to_va_arg_abstract,
9594 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +00009595 return ExprError();
9596
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009597 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00009598 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009599 TInfo->getType()->isObjCLifetimeType()
9600 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9601 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00009602 << TInfo->getType()
9603 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009604 }
Eli Friedman6290ae42011-07-11 21:45:59 +00009605
9606 // Check for va_arg where arguments of the given type will be promoted
9607 // (i.e. this va_arg is guaranteed to have undefined behavior).
9608 QualType PromoteType;
9609 if (TInfo->getType()->isPromotableIntegerType()) {
9610 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9611 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9612 PromoteType = QualType();
9613 }
9614 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9615 PromoteType = Context.DoubleTy;
9616 if (!PromoteType.isNull())
9617 Diag(TInfo->getTypeLoc().getBeginLoc(),
9618 diag::warn_second_parameter_to_va_arg_never_compatible)
9619 << TInfo->getType()
9620 << PromoteType
9621 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00009622 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009623
Abramo Bagnara27db2392010-08-10 10:06:15 +00009624 QualType T = TInfo->getType().getNonLValueExprType(Context);
9625 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009626}
9627
John McCalldadc5752010-08-24 06:29:42 +00009628ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009629 // The type of __null will be int or long, depending on the size of
9630 // pointers on the target.
9631 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009632 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9633 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009634 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009635 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009636 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009637 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009638 Ty = Context.LongLongTy;
9639 else {
David Blaikie83d382b2011-09-23 05:06:16 +00009640 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009641 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009642
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009643 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009644}
9645
Alexis Huntc46382e2010-04-28 23:02:27 +00009646static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009647 Expr *SrcExpr, FixItHint &Hint) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009648 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonace5d072009-11-10 04:46:30 +00009649 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009650
Anders Carlssonace5d072009-11-10 04:46:30 +00009651 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9652 if (!PT)
9653 return;
9654
9655 // Check if the destination is of type 'id'.
9656 if (!PT->isObjCIdType()) {
9657 // Check if the destination is the 'NSString' interface.
9658 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9659 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9660 return;
9661 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009662
John McCallfe96e0b2011-11-06 09:01:30 +00009663 // Ignore any parens, implicit casts (should only be
9664 // array-to-pointer decays), and not-so-opaque values. The last is
9665 // important for making this trigger for property assignments.
9666 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9667 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9668 if (OV->getSourceExpr())
9669 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9670
9671 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregorfb65e592011-07-27 05:40:30 +00009672 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00009673 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009674
Douglas Gregora771f462010-03-31 17:46:05 +00009675 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009676}
9677
Chris Lattner9bad62c2008-01-04 18:04:52 +00009678bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9679 SourceLocation Loc,
9680 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009681 Expr *SrcExpr, AssignmentAction Action,
9682 bool *Complained) {
9683 if (Complained)
9684 *Complained = false;
9685
Chris Lattner9bad62c2008-01-04 18:04:52 +00009686 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00009687 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009688 bool isInvalid = false;
Eli Friedman381f4312012-02-29 20:59:56 +00009689 unsigned DiagKind = 0;
Douglas Gregora771f462010-03-31 17:46:05 +00009690 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00009691 ConversionFixItGenerator ConvHints;
9692 bool MayHaveConvFixit = false;
Richard Trieucaff2472011-11-23 22:32:32 +00009693 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009694
Chris Lattner9bad62c2008-01-04 18:04:52 +00009695 switch (ConvTy) {
Fariborz Jahanian268fec12012-07-17 18:00:08 +00009696 case Compatible:
9697 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
9698 return false;
9699
Chris Lattner940cfeb2008-01-04 18:22:42 +00009700 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009701 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00009702 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9703 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009704 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009705 case IntToPointer:
9706 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00009707 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9708 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009709 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009710 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009711 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009712 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00009713 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9714 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00009715 if (Hint.isNull() && !CheckInferredResultType) {
9716 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9717 }
9718 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009719 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009720 case IncompatiblePointerSign:
9721 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9722 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009723 case FunctionVoidPointer:
9724 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9725 break;
John McCall4fff8f62011-02-01 00:10:29 +00009726 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009727 // Perform array-to-pointer decay if necessary.
9728 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9729
John McCall4fff8f62011-02-01 00:10:29 +00009730 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9731 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9732 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9733 DiagKind = diag::err_typecheck_incompatible_address_space;
9734 break;
John McCall31168b02011-06-15 23:02:42 +00009735
9736
9737 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009738 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00009739 break;
John McCall4fff8f62011-02-01 00:10:29 +00009740 }
9741
9742 llvm_unreachable("unknown error case for discarding qualifiers!");
9743 // fallthrough
9744 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009745 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009746 // If the qualifiers lost were because we were applying the
9747 // (deprecated) C++ conversion from a string literal to a char*
9748 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9749 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009750 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009751 // bit of refactoring (so that the second argument is an
9752 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009753 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009754 // C++ semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009755 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009756 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9757 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009758 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9759 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009760 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009761 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009762 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009763 case IntToBlockPointer:
9764 DiagKind = diag::err_int_to_block_pointer;
9765 break;
9766 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009767 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009768 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009769 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009770 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009771 // it can give a more specific diagnostic.
9772 DiagKind = diag::warn_incompatible_qualified_id;
9773 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009774 case IncompatibleVectors:
9775 DiagKind = diag::warn_incompatible_vectors;
9776 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00009777 case IncompatibleObjCWeakRef:
9778 DiagKind = diag::err_arc_weak_unavailable_assign;
9779 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009780 case Incompatible:
9781 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00009782 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9783 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009784 isInvalid = true;
Richard Trieucaff2472011-11-23 22:32:32 +00009785 MayHaveFunctionDiff = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009786 break;
9787 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009788
Douglas Gregorc68e1402010-04-09 00:35:39 +00009789 QualType FirstType, SecondType;
9790 switch (Action) {
9791 case AA_Assigning:
9792 case AA_Initializing:
9793 // The destination type comes first.
9794 FirstType = DstType;
9795 SecondType = SrcType;
9796 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009797
Douglas Gregorc68e1402010-04-09 00:35:39 +00009798 case AA_Returning:
9799 case AA_Passing:
9800 case AA_Converting:
9801 case AA_Sending:
9802 case AA_Casting:
9803 // The source type comes first.
9804 FirstType = SrcType;
9805 SecondType = DstType;
9806 break;
9807 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009808
Anna Zaks3b402712011-07-28 19:51:27 +00009809 PartialDiagnostic FDiag = PDiag(DiagKind);
9810 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9811
9812 // If we can fix the conversion, suggest the FixIts.
9813 assert(ConvHints.isNull() || Hint.isNull());
9814 if (!ConvHints.isNull()) {
Benjamin Kramer490afa62012-01-14 21:05:10 +00009815 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9816 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks3b402712011-07-28 19:51:27 +00009817 FDiag << *HI;
9818 } else {
9819 FDiag << Hint;
9820 }
9821 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9822
Richard Trieucaff2472011-11-23 22:32:32 +00009823 if (MayHaveFunctionDiff)
9824 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9825
Anna Zaks3b402712011-07-28 19:51:27 +00009826 Diag(Loc, FDiag);
9827
Richard Trieucaff2472011-11-23 22:32:32 +00009828 if (SecondType == Context.OverloadTy)
9829 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9830 FirstType);
9831
Douglas Gregor33823722011-06-11 01:09:30 +00009832 if (CheckInferredResultType)
9833 EmitRelatedResultTypeNote(SrcExpr);
9834
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009835 if (Complained)
9836 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009837 return isInvalid;
9838}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009839
Richard Smithf4c51d92012-02-04 09:53:13 +00009840ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9841 llvm::APSInt *Result) {
Douglas Gregore2b37442012-05-04 22:38:52 +00009842 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9843 public:
9844 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9845 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9846 }
9847 } Diagnoser;
9848
9849 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9850}
9851
9852ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9853 llvm::APSInt *Result,
9854 unsigned DiagID,
9855 bool AllowFold) {
9856 class IDDiagnoser : public VerifyICEDiagnoser {
9857 unsigned DiagID;
9858
9859 public:
9860 IDDiagnoser(unsigned DiagID)
9861 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9862
9863 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9864 S.Diag(Loc, DiagID) << SR;
9865 }
9866 } Diagnoser(DiagID);
9867
9868 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9869}
9870
9871void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9872 SourceRange SR) {
9873 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smithf4c51d92012-02-04 09:53:13 +00009874}
9875
Benjamin Kramer33adaae2012-04-18 14:22:41 +00009876ExprResult
9877Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregore2b37442012-05-04 22:38:52 +00009878 VerifyICEDiagnoser &Diagnoser,
9879 bool AllowFold) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009880 SourceLocation DiagLoc = E->getLocStart();
Richard Smithf4c51d92012-02-04 09:53:13 +00009881
David Blaikiebbafb8a2012-03-11 07:00:24 +00009882 if (getLangOpts().CPlusPlus0x) {
Richard Smithf4c51d92012-02-04 09:53:13 +00009883 // C++11 [expr.const]p5:
9884 // If an expression of literal class type is used in a context where an
9885 // integral constant expression is required, then that class type shall
9886 // have a single non-explicit conversion function to an integral or
9887 // unscoped enumeration type
9888 ExprResult Converted;
Douglas Gregore2b37442012-05-04 22:38:52 +00009889 if (!Diagnoser.Suppress) {
9890 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9891 public:
9892 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9893
9894 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9895 QualType T) {
9896 return S.Diag(Loc, diag::err_ice_not_integral) << T;
9897 }
9898
9899 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9900 SourceLocation Loc,
9901 QualType T) {
9902 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
9903 }
9904
9905 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9906 SourceLocation Loc,
9907 QualType T,
9908 QualType ConvTy) {
9909 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
9910 }
9911
9912 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9913 CXXConversionDecl *Conv,
9914 QualType ConvTy) {
9915 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9916 << ConvTy->isEnumeralType() << ConvTy;
9917 }
9918
9919 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9920 QualType T) {
9921 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
9922 }
9923
9924 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9925 CXXConversionDecl *Conv,
9926 QualType ConvTy) {
9927 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9928 << ConvTy->isEnumeralType() << ConvTy;
9929 }
9930
9931 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9932 SourceLocation Loc,
9933 QualType T,
9934 QualType ConvTy) {
9935 return DiagnosticBuilder::getEmpty();
9936 }
9937 } ConvertDiagnoser;
9938
9939 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9940 ConvertDiagnoser,
9941 /*AllowScopedEnumerations*/ false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009942 } else {
9943 // The caller wants to silently enquire whether this is an ICE. Don't
9944 // produce any diagnostics if it isn't.
Douglas Gregore2b37442012-05-04 22:38:52 +00009945 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
9946 public:
9947 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
9948
9949 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9950 QualType T) {
9951 return DiagnosticBuilder::getEmpty();
9952 }
9953
9954 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9955 SourceLocation Loc,
9956 QualType T) {
9957 return DiagnosticBuilder::getEmpty();
9958 }
9959
9960 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9961 SourceLocation Loc,
9962 QualType T,
9963 QualType ConvTy) {
9964 return DiagnosticBuilder::getEmpty();
9965 }
9966
9967 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9968 CXXConversionDecl *Conv,
9969 QualType ConvTy) {
9970 return DiagnosticBuilder::getEmpty();
9971 }
9972
9973 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9974 QualType T) {
9975 return DiagnosticBuilder::getEmpty();
9976 }
9977
9978 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9979 CXXConversionDecl *Conv,
9980 QualType ConvTy) {
9981 return DiagnosticBuilder::getEmpty();
9982 }
9983
9984 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9985 SourceLocation Loc,
9986 QualType T,
9987 QualType ConvTy) {
9988 return DiagnosticBuilder::getEmpty();
9989 }
9990 } ConvertDiagnoser;
9991
9992 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9993 ConvertDiagnoser, false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009994 }
9995 if (Converted.isInvalid())
9996 return Converted;
9997 E = Converted.take();
9998 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
9999 return ExprError();
10000 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10001 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregore2b37442012-05-04 22:38:52 +000010002 if (!Diagnoser.Suppress)
10003 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithf4c51d92012-02-04 09:53:13 +000010004 return ExprError();
10005 }
10006
Richard Smith902ca212011-12-14 23:32:26 +000010007 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10008 // in the non-ICE case.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010009 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
Richard Smithf4c51d92012-02-04 09:53:13 +000010010 if (Result)
10011 *Result = E->EvaluateKnownConstInt(Context);
10012 return Owned(E);
Eli Friedmanbb967cc2009-04-25 22:26:58 +000010013 }
10014
Anders Carlssone54e8a12008-11-30 19:50:32 +000010015 Expr::EvalResult EvalResult;
Richard Smith92b1ce02011-12-12 09:28:41 +000010016 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
10017 EvalResult.Diag = &Notes;
Anders Carlssone54e8a12008-11-30 19:50:32 +000010018
Richard Smith902ca212011-12-14 23:32:26 +000010019 // Try to evaluate the expression, and produce diagnostics explaining why it's
10020 // not a constant expression as a side-effect.
10021 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10022 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10023
10024 // In C++11, we can rely on diagnostics being produced for any expression
10025 // which is not a constant expression. If no diagnostics were produced, then
10026 // this is a constant expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010027 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
Richard Smith902ca212011-12-14 23:32:26 +000010028 if (Result)
10029 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +000010030 return Owned(E);
10031 }
10032
10033 // If our only note is the usual "invalid subexpression" note, just point
10034 // the caret at its location rather than producing an essentially
10035 // redundant note.
10036 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10037 diag::note_invalid_subexpr_in_const_expr) {
10038 DiagLoc = Notes[0].first;
10039 Notes.clear();
Richard Smith902ca212011-12-14 23:32:26 +000010040 }
10041
10042 if (!Folded || !AllowFold) {
Douglas Gregore2b37442012-05-04 22:38:52 +000010043 if (!Diagnoser.Suppress) {
10044 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith92b1ce02011-12-12 09:28:41 +000010045 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10046 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone54e8a12008-11-30 19:50:32 +000010047 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000010048
Richard Smithf4c51d92012-02-04 09:53:13 +000010049 return ExprError();
Anders Carlssone54e8a12008-11-30 19:50:32 +000010050 }
10051
Douglas Gregore2b37442012-05-04 22:38:52 +000010052 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith2ec40612012-01-15 03:51:30 +000010053 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10054 Diag(Notes[I].first, Notes[I].second);
Mike Stump4e1f26a2009-02-19 03:04:26 +000010055
Anders Carlssone54e8a12008-11-30 19:50:32 +000010056 if (Result)
10057 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +000010058 return Owned(E);
Anders Carlssone54e8a12008-11-30 19:50:32 +000010059}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010060
Eli Friedman456f0182012-01-20 01:26:23 +000010061namespace {
10062 // Handle the case where we conclude a expression which we speculatively
10063 // considered to be unevaluated is actually evaluated.
10064 class TransformToPE : public TreeTransform<TransformToPE> {
10065 typedef TreeTransform<TransformToPE> BaseTransform;
10066
10067 public:
10068 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10069
10070 // Make sure we redo semantic analysis
10071 bool AlwaysRebuild() { return true; }
10072
Eli Friedman5f0ca242012-02-06 23:29:57 +000010073 // Make sure we handle LabelStmts correctly.
10074 // FIXME: This does the right thing, but maybe we need a more general
10075 // fix to TreeTransform?
10076 StmtResult TransformLabelStmt(LabelStmt *S) {
10077 S->getDecl()->setStmt(0);
10078 return BaseTransform::TransformLabelStmt(S);
10079 }
10080
Eli Friedman456f0182012-01-20 01:26:23 +000010081 // We need to special-case DeclRefExprs referring to FieldDecls which
10082 // are not part of a member pointer formation; normal TreeTransforming
10083 // doesn't catch this case because of the way we represent them in the AST.
10084 // FIXME: This is a bit ugly; is it really the best way to handle this
10085 // case?
10086 //
10087 // Error on DeclRefExprs referring to FieldDecls.
10088 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10089 if (isa<FieldDecl>(E->getDecl()) &&
David Blaikie131fcb42012-08-06 22:47:24 +000010090 !SemaRef.isUnevaluatedContext())
Eli Friedman456f0182012-01-20 01:26:23 +000010091 return SemaRef.Diag(E->getLocation(),
10092 diag::err_invalid_non_static_member_use)
10093 << E->getDecl() << E->getSourceRange();
10094
10095 return BaseTransform::TransformDeclRefExpr(E);
10096 }
10097
10098 // Exception: filter out member pointer formation
10099 ExprResult TransformUnaryOperator(UnaryOperator *E) {
10100 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10101 return E;
10102
10103 return BaseTransform::TransformUnaryOperator(E);
10104 }
10105
Douglas Gregor89625492012-02-09 08:14:43 +000010106 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10107 // Lambdas never need to be transformed.
10108 return E;
10109 }
Eli Friedman456f0182012-01-20 01:26:23 +000010110 };
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000010111}
10112
Eli Friedman456f0182012-01-20 01:26:23 +000010113ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
Eli Friedmane4f22df2012-02-29 04:03:55 +000010114 assert(ExprEvalContexts.back().Context == Unevaluated &&
10115 "Should only transform unevaluated expressions");
Eli Friedman456f0182012-01-20 01:26:23 +000010116 ExprEvalContexts.back().Context =
10117 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10118 if (ExprEvalContexts.back().Context == Unevaluated)
10119 return E;
10120 return TransformToPE(*this).TransformExpr(E);
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000010121}
10122
Douglas Gregorff790f12009-11-26 00:44:06 +000010123void
Douglas Gregor7fcbd902012-02-21 00:37:24 +000010124Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smithfd555f62012-02-22 02:04:18 +000010125 Decl *LambdaContextDecl,
10126 bool IsDecltype) {
Douglas Gregorff790f12009-11-26 00:44:06 +000010127 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +000010128 ExpressionEvaluationContextRecord(NewContext,
John McCall28fc7092011-11-10 05:35:25 +000010129 ExprCleanupObjects.size(),
Douglas Gregor7fcbd902012-02-21 00:37:24 +000010130 ExprNeedsCleanups,
Richard Smithfd555f62012-02-22 02:04:18 +000010131 LambdaContextDecl,
10132 IsDecltype));
John McCall31168b02011-06-15 23:02:42 +000010133 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010134 if (!MaybeODRUseExprs.empty())
10135 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010136}
10137
Richard Trieucfc491d2011-08-02 04:35:43 +000010138void Sema::PopExpressionEvaluationContext() {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010139 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010140
Douglas Gregor89625492012-02-09 08:14:43 +000010141 if (!Rec.Lambdas.empty()) {
10142 if (Rec.Context == Unevaluated) {
10143 // C++11 [expr.prim.lambda]p2:
10144 // A lambda-expression shall not appear in an unevaluated operand
10145 // (Clause 5).
10146 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10147 Diag(Rec.Lambdas[I]->getLocStart(),
10148 diag::err_lambda_unevaluated_operand);
10149 } else {
10150 // Mark the capture expressions odr-used. This was deferred
10151 // during lambda expression creation.
10152 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10153 LambdaExpr *Lambda = Rec.Lambdas[I];
10154 for (LambdaExpr::capture_init_iterator
10155 C = Lambda->capture_init_begin(),
10156 CEnd = Lambda->capture_init_end();
10157 C != CEnd; ++C) {
10158 MarkDeclarationsReferencedInExpr(*C);
10159 }
10160 }
10161 }
10162 }
10163
Douglas Gregorff790f12009-11-26 00:44:06 +000010164 // When are coming out of an unevaluated context, clear out any
10165 // temporaries that we may have created as part of the evaluation of
10166 // the expression in that context: they aren't relevant because they
10167 // will never be constructed.
Richard Smith764d2fe2011-12-20 02:08:33 +000010168 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall28fc7092011-11-10 05:35:25 +000010169 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10170 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +000010171 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010172 CleanupVarDeclMarking();
10173 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCall31168b02011-06-15 23:02:42 +000010174 // Otherwise, merge the contexts together.
10175 } else {
10176 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010177 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10178 Rec.SavedMaybeODRUseExprs.end());
John McCall31168b02011-06-15 23:02:42 +000010179 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010180
10181 // Pop the current expression evaluation context off the stack.
10182 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010183}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010184
John McCall31168b02011-06-15 23:02:42 +000010185void Sema::DiscardCleanupsInEvaluationContext() {
John McCall28fc7092011-11-10 05:35:25 +000010186 ExprCleanupObjects.erase(
10187 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10188 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +000010189 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010190 MaybeODRUseExprs.clear();
John McCall31168b02011-06-15 23:02:42 +000010191}
10192
Eli Friedmane0afc982012-01-21 01:01:51 +000010193ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10194 if (!E->getType()->isVariablyModifiedType())
10195 return E;
10196 return TranformToPotentiallyEvaluated(E);
10197}
10198
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +000010199static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010200 // Do not mark anything as "used" within a dependent context; wait for
10201 // an instantiation.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010202 if (SemaRef.CurContext->isDependentContext())
10203 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010204
Eli Friedmanfa0df832012-02-02 03:46:19 +000010205 switch (SemaRef.ExprEvalContexts.back().Context) {
10206 case Sema::Unevaluated:
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010207 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman02b58512012-01-21 04:44:06 +000010208 // (Depending on how you read the standard, we actually do need to do
10209 // something here for null pointer constants, but the standard's
10210 // definition of a null pointer constant is completely crazy.)
Eli Friedmanfa0df832012-02-02 03:46:19 +000010211 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010212
Eli Friedmanfa0df832012-02-02 03:46:19 +000010213 case Sema::ConstantEvaluated:
10214 case Sema::PotentiallyEvaluated:
Eli Friedman02b58512012-01-21 04:44:06 +000010215 // We are in a potentially evaluated expression (or a constant-expression
10216 // in C++03); we need to do implicit template instantiation, implicitly
10217 // define class members, and mark most declarations as used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010218 return true;
Mike Stump11289f42009-09-09 15:08:12 +000010219
Eli Friedmanfa0df832012-02-02 03:46:19 +000010220 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010221 // Referenced declarations will only be used if the construct in the
10222 // containing expression is used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010223 return false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010224 }
Matt Beaumont-Gay248bc722012-02-02 18:35:35 +000010225 llvm_unreachable("Invalid context");
Eli Friedmanfa0df832012-02-02 03:46:19 +000010226}
10227
10228/// \brief Mark a function referenced, and check whether it is odr-used
10229/// (C++ [basic.def.odr]p2, C99 6.9p3)
10230void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10231 assert(Func && "No function?");
10232
10233 Func->setReferenced();
10234
Richard Smith4a941e22012-02-14 22:25:15 +000010235 // Don't mark this function as used multiple times, unless it's a constexpr
10236 // function which we need to instantiate.
10237 if (Func->isUsed(false) &&
10238 !(Func->isConstexpr() && !Func->getBody() &&
10239 Func->isImplicitlyInstantiable()))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010240 return;
10241
10242 if (!IsPotentiallyEvaluatedContext(*this))
10243 return;
Mike Stump11289f42009-09-09 15:08:12 +000010244
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010245 // Note that this declaration has been used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010246 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010247 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010248 if (Constructor->isDefaultConstructor()) {
10249 if (Constructor->isTrivial())
10250 return;
10251 if (!Constructor->isUsed(false))
10252 DefineImplicitDefaultConstructor(Loc, Constructor);
10253 } else if (Constructor->isCopyConstructor()) {
10254 if (!Constructor->isUsed(false))
10255 DefineImplicitCopyConstructor(Loc, Constructor);
10256 } else if (Constructor->isMoveConstructor()) {
10257 if (!Constructor->isUsed(false))
10258 DefineImplicitMoveConstructor(Loc, Constructor);
10259 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010260 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010261
Douglas Gregor88d292c2010-05-13 16:44:06 +000010262 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010263 } else if (CXXDestructorDecl *Destructor =
10264 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010265 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10266 !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010267 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010268 if (Destructor->isVirtual())
10269 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010270 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010271 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10272 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010273 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010274 if (!MethodDecl->isUsed(false)) {
10275 if (MethodDecl->isCopyAssignmentOperator())
10276 DefineImplicitCopyAssignment(Loc, MethodDecl);
10277 else
10278 DefineImplicitMoveAssignment(Loc, MethodDecl);
10279 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010280 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10281 MethodDecl->getParent()->isLambda()) {
10282 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10283 if (Conversion->isLambdaToBlockPointerConversion())
10284 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10285 else
10286 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010287 } else if (MethodDecl->isVirtual())
10288 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010289 }
John McCall83779672011-02-19 02:53:41 +000010290
Eli Friedmanfa0df832012-02-02 03:46:19 +000010291 // Recursive functions should be marked when used from another function.
10292 // FIXME: Is this really right?
10293 if (CurContext == Func) return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010294
Richard Smithd3b5c9082012-07-27 04:22:15 +000010295 // Resolve the exception specification for any function which is
Richard Smithf623c962012-04-17 00:58:00 +000010296 // used: CodeGen will need it.
Richard Smithd3729422012-04-19 00:08:28 +000010297 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010298 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10299 ResolveExceptionSpec(Loc, FPT);
Richard Smithf623c962012-04-17 00:58:00 +000010300
Eli Friedmanfa0df832012-02-02 03:46:19 +000010301 // Implicit instantiation of function templates and member functions of
10302 // class templates.
10303 if (Func->isImplicitlyInstantiable()) {
10304 bool AlreadyInstantiated = false;
Richard Smith4a941e22012-02-14 22:25:15 +000010305 SourceLocation PointOfInstantiation = Loc;
Eli Friedmanfa0df832012-02-02 03:46:19 +000010306 if (FunctionTemplateSpecializationInfo *SpecInfo
10307 = Func->getTemplateSpecializationInfo()) {
10308 if (SpecInfo->getPointOfInstantiation().isInvalid())
10309 SpecInfo->setPointOfInstantiation(Loc);
10310 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000010311 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010312 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000010313 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10314 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010315 } else if (MemberSpecializationInfo *MSInfo
10316 = Func->getMemberSpecializationInfo()) {
10317 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregor06db9f52009-10-12 20:18:28 +000010318 MSInfo->setPointOfInstantiation(Loc);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010319 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000010320 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010321 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000010322 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10323 }
Douglas Gregor06db9f52009-10-12 20:18:28 +000010324 }
Mike Stump11289f42009-09-09 15:08:12 +000010325
Richard Smith4a941e22012-02-14 22:25:15 +000010326 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010327 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10328 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith4a941e22012-02-14 22:25:15 +000010329 PendingLocalImplicitInstantiations.push_back(
10330 std::make_pair(Func, PointOfInstantiation));
10331 else if (Func->isConstexpr())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010332 // Do not defer instantiations of constexpr functions, to avoid the
10333 // expression evaluator needing to call back into Sema if it sees a
10334 // call to such a function.
Richard Smith4a941e22012-02-14 22:25:15 +000010335 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000010336 else {
Richard Smith4a941e22012-02-14 22:25:15 +000010337 PendingInstantiations.push_back(std::make_pair(Func,
10338 PointOfInstantiation));
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000010339 // Notify the consumer that a function was implicitly instantiated.
10340 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10341 }
John McCall83779672011-02-19 02:53:41 +000010342 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010343 } else {
10344 // Walk redefinitions, as some of them may be instantiable.
10345 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10346 e(Func->redecls_end()); i != e; ++i) {
10347 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10348 MarkFunctionReferenced(Loc, *i);
10349 }
Sam Weinigbae69142009-09-11 03:29:30 +000010350 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010351
10352 // Keep track of used but undefined functions.
10353 if (!Func->isPure() && !Func->hasBody() &&
10354 Func->getLinkage() != ExternalLinkage) {
10355 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10356 if (old.isInvalid()) old = Loc;
10357 }
10358
10359 Func->setUsed(true);
10360}
10361
Eli Friedman9bb33f52012-02-03 02:04:35 +000010362static void
10363diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10364 VarDecl *var, DeclContext *DC) {
Eli Friedmandd053f62012-02-07 00:15:00 +000010365 DeclContext *VarDC = var->getDeclContext();
10366
Eli Friedman9bb33f52012-02-03 02:04:35 +000010367 // If the parameter still belongs to the translation unit, then
10368 // we're actually just using one parameter in the declaration of
10369 // the next.
10370 if (isa<ParmVarDecl>(var) &&
Eli Friedmandd053f62012-02-07 00:15:00 +000010371 isa<TranslationUnitDecl>(VarDC))
Eli Friedman9bb33f52012-02-03 02:04:35 +000010372 return;
10373
Eli Friedmandd053f62012-02-07 00:15:00 +000010374 // For C code, don't diagnose about capture if we're not actually in code
10375 // right now; it's impossible to write a non-constant expression outside of
10376 // function context, so we'll get other (more useful) diagnostics later.
10377 //
10378 // For C++, things get a bit more nasty... it would be nice to suppress this
10379 // diagnostic for certain cases like using a local variable in an array bound
10380 // for a member of a local class, but the correct predicate is not obvious.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010381 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman9bb33f52012-02-03 02:04:35 +000010382 return;
10383
Eli Friedmandd053f62012-02-07 00:15:00 +000010384 if (isa<CXXMethodDecl>(VarDC) &&
10385 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10386 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10387 << var->getIdentifier();
10388 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10389 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10390 << var->getIdentifier() << fn->getDeclName();
10391 } else if (isa<BlockDecl>(VarDC)) {
10392 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10393 << var->getIdentifier();
10394 } else {
10395 // FIXME: Is there any other context where a local variable can be
10396 // declared?
10397 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10398 << var->getIdentifier();
10399 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010400
Eli Friedman9bb33f52012-02-03 02:04:35 +000010401 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10402 << var->getIdentifier();
Eli Friedmandd053f62012-02-07 00:15:00 +000010403
10404 // FIXME: Add additional diagnostic info about class etc. which prevents
10405 // capture.
Eli Friedman9bb33f52012-02-03 02:04:35 +000010406}
10407
Douglas Gregor81495f32012-02-12 18:42:33 +000010408/// \brief Capture the given variable in the given lambda expression.
10409static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010410 VarDecl *Var, QualType FieldType,
10411 QualType DeclRefType,
Douglas Gregora8182f92012-05-16 17:01:33 +000010412 SourceLocation Loc,
10413 bool RefersToEnclosingLocal) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010414 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregor81495f32012-02-12 18:42:33 +000010415
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010416 // Build the non-static data member.
10417 FieldDecl *Field
10418 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10419 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Richard Smith2b013182012-06-10 03:12:00 +000010420 0, false, ICIS_NoInit);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010421 Field->setImplicit(true);
10422 Field->setAccess(AS_private);
Douglas Gregor3d23f7882012-02-09 02:12:34 +000010423 Lambda->addDecl(Field);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010424
10425 // C++11 [expr.prim.lambda]p21:
10426 // When the lambda-expression is evaluated, the entities that
10427 // are captured by copy are used to direct-initialize each
10428 // corresponding non-static data member of the resulting closure
10429 // object. (For array members, the array elements are
10430 // direct-initialized in increasing subscript order.) These
10431 // initializations are performed in the (unspecified) order in
10432 // which the non-static data members are declared.
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010433
Douglas Gregor89625492012-02-09 08:14:43 +000010434 // Introduce a new evaluation context for the initialization, so
10435 // that temporaries introduced as part of the capture are retained
10436 // to be re-"exported" from the lambda expression itself.
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010437 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10438
Douglas Gregorf02455e2012-02-10 09:26:04 +000010439 // C++ [expr.prim.labda]p12:
10440 // An entity captured by a lambda-expression is odr-used (3.2) in
10441 // the scope containing the lambda-expression.
Douglas Gregora8182f92012-05-16 17:01:33 +000010442 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10443 DeclRefType, VK_LValue, Loc);
Eli Friedman23b1be92012-03-01 21:32:56 +000010444 Var->setReferenced(true);
Douglas Gregorf02455e2012-02-10 09:26:04 +000010445 Var->setUsed(true);
Douglas Gregor199cec72012-02-09 02:45:47 +000010446
10447 // When the field has array type, create index variables for each
10448 // dimension of the array. We use these index variables to subscript
10449 // the source array, and other clients (e.g., CodeGen) will perform
10450 // the necessary iteration with these index variables.
10451 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor199cec72012-02-09 02:45:47 +000010452 QualType BaseType = FieldType;
10453 QualType SizeType = S.Context.getSizeType();
Douglas Gregor54fcea62012-02-13 16:35:30 +000010454 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor199cec72012-02-09 02:45:47 +000010455 while (const ConstantArrayType *Array
10456 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor199cec72012-02-09 02:45:47 +000010457 // Create the iteration variable for this array index.
10458 IdentifierInfo *IterationVarName = 0;
10459 {
10460 SmallString<8> Str;
10461 llvm::raw_svector_ostream OS(Str);
10462 OS << "__i" << IndexVariables.size();
10463 IterationVarName = &S.Context.Idents.get(OS.str());
10464 }
10465 VarDecl *IterationVar
10466 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10467 IterationVarName, SizeType,
10468 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10469 SC_None, SC_None);
10470 IndexVariables.push_back(IterationVar);
Douglas Gregor54fcea62012-02-13 16:35:30 +000010471 LSI->ArrayIndexVars.push_back(IterationVar);
10472
Douglas Gregor199cec72012-02-09 02:45:47 +000010473 // Create a reference to the iteration variable.
10474 ExprResult IterationVarRef
10475 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10476 assert(!IterationVarRef.isInvalid() &&
10477 "Reference to invented variable cannot fail!");
10478 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10479 assert(!IterationVarRef.isInvalid() &&
10480 "Conversion of invented variable cannot fail!");
10481
10482 // Subscript the array with this iteration variable.
10483 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10484 Ref, Loc, IterationVarRef.take(), Loc);
10485 if (Subscript.isInvalid()) {
10486 S.CleanupVarDeclMarking();
10487 S.DiscardCleanupsInEvaluationContext();
10488 S.PopExpressionEvaluationContext();
10489 return ExprError();
10490 }
10491
10492 Ref = Subscript.take();
10493 BaseType = Array->getElementType();
10494 }
10495
10496 // Construct the entity that we will be initializing. For an array, this
10497 // will be first element in the array, which may require several levels
10498 // of array-subscript entities.
10499 SmallVector<InitializedEntity, 4> Entities;
10500 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor19666fb2012-02-15 16:57:26 +000010501 Entities.push_back(
10502 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor199cec72012-02-09 02:45:47 +000010503 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10504 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10505 0,
10506 Entities.back()));
10507
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010508 InitializationKind InitKind
10509 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor199cec72012-02-09 02:45:47 +000010510 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010511 ExprResult Result(true);
Douglas Gregor199cec72012-02-09 02:45:47 +000010512 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010513 Result = Init.Perform(S, Entities.back(), InitKind, Ref);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010514
10515 // If this initialization requires any cleanups (e.g., due to a
10516 // default argument to a copy constructor), note that for the
10517 // lambda.
10518 if (S.ExprNeedsCleanups)
10519 LSI->ExprNeedsCleanups = true;
10520
10521 // Exit the expression evaluation context used for the capture.
10522 S.CleanupVarDeclMarking();
10523 S.DiscardCleanupsInEvaluationContext();
10524 S.PopExpressionEvaluationContext();
10525 return Result;
Douglas Gregor199cec72012-02-09 02:45:47 +000010526}
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010527
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010528bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10529 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10530 bool BuildAndDiagnose,
10531 QualType &CaptureType,
10532 QualType &DeclRefType) {
10533 bool Nested = false;
Douglas Gregor81495f32012-02-12 18:42:33 +000010534
Eli Friedman24af8502012-02-03 22:47:37 +000010535 DeclContext *DC = CurContext;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010536 if (Var->getDeclContext() == DC) return true;
10537 if (!Var->hasLocalStorage()) return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010538
Douglas Gregor81495f32012-02-12 18:42:33 +000010539 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010540
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010541 // Walk up the stack to determine whether we can capture the variable,
10542 // performing the "simple" checks that don't depend on type. We stop when
10543 // we've either hit the declared scope of the variable or find an existing
10544 // capture of that variable.
10545 CaptureType = Var->getType();
10546 DeclRefType = CaptureType.getNonReferenceType();
10547 bool Explicit = (Kind != TryCapture_Implicit);
10548 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010549 do {
Eli Friedman24af8502012-02-03 22:47:37 +000010550 // Only block literals and lambda expressions can capture; other
Eli Friedman9bb33f52012-02-03 02:04:35 +000010551 // scopes don't work.
Eli Friedman24af8502012-02-03 22:47:37 +000010552 DeclContext *ParentDC;
10553 if (isa<BlockDecl>(DC))
10554 ParentDC = DC->getParent();
10555 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregor81495f32012-02-12 18:42:33 +000010556 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedman24af8502012-02-03 22:47:37 +000010557 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10558 ParentDC = DC->getParent()->getParent();
Douglas Gregor81495f32012-02-12 18:42:33 +000010559 else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010560 if (BuildAndDiagnose)
Douglas Gregor81495f32012-02-12 18:42:33 +000010561 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010562 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000010563 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010564
Eli Friedman24af8502012-02-03 22:47:37 +000010565 CapturingScopeInfo *CSI =
Douglas Gregor81495f32012-02-12 18:42:33 +000010566 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010567
Eli Friedman24af8502012-02-03 22:47:37 +000010568 // Check whether we've already captured it.
Douglas Gregor81495f32012-02-12 18:42:33 +000010569 if (CSI->CaptureMap.count(Var)) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010570 // If we found a capture, any subcaptures are nested.
Eli Friedman9bb33f52012-02-03 02:04:35 +000010571 Nested = true;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010572
10573 // Retrieve the capture type for this variable.
10574 CaptureType = CSI->getCapture(Var).getCaptureType();
10575
10576 // Compute the type of an expression that refers to this variable.
10577 DeclRefType = CaptureType.getNonReferenceType();
10578
10579 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10580 if (Cap.isCopyCapture() &&
10581 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10582 DeclRefType.addConst();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010583 break;
10584 }
10585
Douglas Gregor81495f32012-02-12 18:42:33 +000010586 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010587 bool IsLambda = !IsBlock;
Eli Friedman24af8502012-02-03 22:47:37 +000010588
10589 // Lambdas are not allowed to capture unnamed variables
10590 // (e.g. anonymous unions).
10591 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10592 // assuming that's the intent.
Douglas Gregor81495f32012-02-12 18:42:33 +000010593 if (IsLambda && !Var->getDeclName()) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010594 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010595 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10596 Diag(Var->getLocation(), diag::note_declared_at);
10597 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010598 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000010599 }
10600
10601 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010602 if (Var->getType()->isVariablyModifiedType()) {
10603 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010604 if (IsBlock)
10605 Diag(Loc, diag::err_ref_vm_type);
10606 else
10607 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10608 Diag(Var->getLocation(), diag::note_previous_decl)
10609 << Var->getDeclName();
10610 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010611 return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010612 }
10613
Eli Friedman24af8502012-02-03 22:47:37 +000010614 // Lambdas are not allowed to capture __block variables; they don't
10615 // support the expected semantics.
Douglas Gregor81495f32012-02-12 18:42:33 +000010616 if (IsLambda && HasBlocksAttr) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010617 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010618 Diag(Loc, diag::err_lambda_capture_block)
10619 << Var->getDeclName();
10620 Diag(Var->getLocation(), diag::note_previous_decl)
10621 << Var->getDeclName();
10622 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010623 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000010624 }
10625
Douglas Gregor81495f32012-02-12 18:42:33 +000010626 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10627 // No capture-default
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010628 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010629 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10630 Diag(Var->getLocation(), diag::note_previous_decl)
10631 << Var->getDeclName();
10632 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10633 diag::note_lambda_decl);
10634 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010635 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000010636 }
10637
10638 FunctionScopesIndex--;
10639 DC = ParentDC;
10640 Explicit = false;
10641 } while (!Var->getDeclContext()->Equals(DC));
10642
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010643 // Walk back down the scope stack, computing the type of the capture at
10644 // each step, checking type-specific requirements, and adding captures if
10645 // requested.
10646 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10647 ++I) {
10648 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor812d8f62012-02-18 05:51:20 +000010649
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010650 // Compute the type of the capture and of a reference to the capture within
10651 // this scope.
10652 if (isa<BlockScopeInfo>(CSI)) {
10653 Expr *CopyExpr = 0;
10654 bool ByRef = false;
10655
10656 // Blocks are not allowed to capture arrays.
10657 if (CaptureType->isArrayType()) {
10658 if (BuildAndDiagnose) {
10659 Diag(Loc, diag::err_ref_array_type);
10660 Diag(Var->getLocation(), diag::note_previous_decl)
10661 << Var->getDeclName();
10662 }
10663 return true;
10664 }
10665
John McCall67cd5e02012-03-30 05:23:48 +000010666 // Forbid the block-capture of autoreleasing variables.
10667 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10668 if (BuildAndDiagnose) {
10669 Diag(Loc, diag::err_arc_autoreleasing_capture)
10670 << /*block*/ 0;
10671 Diag(Var->getLocation(), diag::note_previous_decl)
10672 << Var->getDeclName();
10673 }
10674 return true;
10675 }
10676
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010677 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10678 // Block capture by reference does not change the capture or
10679 // declaration reference types.
10680 ByRef = true;
10681 } else {
10682 // Block capture by copy introduces 'const'.
10683 CaptureType = CaptureType.getNonReferenceType().withConst();
10684 DeclRefType = CaptureType;
10685
David Blaikiebbafb8a2012-03-11 07:00:24 +000010686 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010687 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10688 // The capture logic needs the destructor, so make sure we mark it.
10689 // Usually this is unnecessary because most local variables have
10690 // their destructors marked at declaration time, but parameters are
10691 // an exception because it's technically only the call site that
10692 // actually requires the destructor.
10693 if (isa<ParmVarDecl>(Var))
10694 FinalizeVarWithDestructor(Var, Record);
10695
10696 // According to the blocks spec, the capture of a variable from
10697 // the stack requires a const copy constructor. This is not true
10698 // of the copy/move done to move a __block variable to the heap.
John McCall113bee02012-03-10 09:33:50 +000010699 Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010700 DeclRefType.withConst(),
10701 VK_LValue, Loc);
10702 ExprResult Result
10703 = PerformCopyInitialization(
10704 InitializedEntity::InitializeBlock(Var->getLocation(),
10705 CaptureType, false),
10706 Loc, Owned(DeclRef));
10707
10708 // Build a full-expression copy expression if initialization
10709 // succeeded and used a non-trivial constructor. Recover from
10710 // errors by pretending that the copy isn't necessary.
10711 if (!Result.isInvalid() &&
10712 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10713 ->isTrivial()) {
10714 Result = MaybeCreateExprWithCleanups(Result);
10715 CopyExpr = Result.take();
10716 }
10717 }
10718 }
10719 }
10720
10721 // Actually capture the variable.
10722 if (BuildAndDiagnose)
10723 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10724 SourceLocation(), CaptureType, CopyExpr);
10725 Nested = true;
10726 continue;
10727 }
Douglas Gregor812d8f62012-02-18 05:51:20 +000010728
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010729 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10730
10731 // Determine whether we are capturing by reference or by value.
10732 bool ByRef = false;
10733 if (I == N - 1 && Kind != TryCapture_Implicit) {
10734 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedman24af8502012-02-03 22:47:37 +000010735 } else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010736 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedman24af8502012-02-03 22:47:37 +000010737 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010738
10739 // Compute the type of the field that will capture this variable.
10740 if (ByRef) {
10741 // C++11 [expr.prim.lambda]p15:
10742 // An entity is captured by reference if it is implicitly or
10743 // explicitly captured but not captured by copy. It is
10744 // unspecified whether additional unnamed non-static data
10745 // members are declared in the closure type for entities
10746 // captured by reference.
10747 //
10748 // FIXME: It is not clear whether we want to build an lvalue reference
10749 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10750 // to do the former, while EDG does the latter. Core issue 1249 will
10751 // clarify, but for now we follow GCC because it's a more permissive and
10752 // easily defensible position.
10753 CaptureType = Context.getLValueReferenceType(DeclRefType);
10754 } else {
10755 // C++11 [expr.prim.lambda]p14:
10756 // For each entity captured by copy, an unnamed non-static
10757 // data member is declared in the closure type. The
10758 // declaration order of these members is unspecified. The type
10759 // of such a data member is the type of the corresponding
10760 // captured entity if the entity is not a reference to an
10761 // object, or the referenced type otherwise. [Note: If the
10762 // captured entity is a reference to a function, the
10763 // corresponding data member is also a reference to a
10764 // function. - end note ]
10765 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10766 if (!RefType->getPointeeType()->isFunctionType())
10767 CaptureType = RefType->getPointeeType();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010768 }
John McCall67cd5e02012-03-30 05:23:48 +000010769
10770 // Forbid the lambda copy-capture of autoreleasing variables.
10771 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10772 if (BuildAndDiagnose) {
10773 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10774 Diag(Var->getLocation(), diag::note_previous_decl)
10775 << Var->getDeclName();
10776 }
10777 return true;
10778 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010779 }
10780
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010781 // Capture this variable in the lambda.
10782 Expr *CopyExpr = 0;
10783 if (BuildAndDiagnose) {
10784 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
Douglas Gregora8182f92012-05-16 17:01:33 +000010785 DeclRefType, Loc,
10786 I == N-1);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010787 if (!Result.isInvalid())
10788 CopyExpr = Result.take();
10789 }
10790
10791 // Compute the type of a reference to this captured variable.
10792 if (ByRef)
10793 DeclRefType = CaptureType.getNonReferenceType();
10794 else {
10795 // C++ [expr.prim.lambda]p5:
10796 // The closure type for a lambda-expression has a public inline
10797 // function call operator [...]. This function call operator is
10798 // declared const (9.3.1) if and only if the lambda-expression’s
10799 // parameter-declaration-clause is not followed by mutable.
10800 DeclRefType = CaptureType.getNonReferenceType();
10801 if (!LSI->Mutable && !CaptureType->isReferenceType())
10802 DeclRefType.addConst();
10803 }
10804
10805 // Add the capture.
10806 if (BuildAndDiagnose)
10807 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10808 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010809 Nested = true;
10810 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010811
10812 return false;
10813}
10814
10815bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10816 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10817 QualType CaptureType;
10818 QualType DeclRefType;
10819 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10820 /*BuildAndDiagnose=*/true, CaptureType,
10821 DeclRefType);
10822}
10823
10824QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10825 QualType CaptureType;
10826 QualType DeclRefType;
10827
10828 // Determine whether we can capture this variable.
10829 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10830 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10831 return QualType();
10832
10833 return DeclRefType;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010834}
10835
Eli Friedman3bda6b12012-02-02 23:15:15 +000010836static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10837 SourceLocation Loc) {
10838 // Keep track of used but undefined variables.
Eli Friedman130bbd02012-02-04 00:54:05 +000010839 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar9d355812012-03-09 01:51:51 +000010840 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman130bbd02012-02-04 00:54:05 +000010841 Var->getLinkage() != ExternalLinkage &&
10842 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010843 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10844 if (old.isInvalid()) old = Loc;
10845 }
10846
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010847 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010848
Eli Friedman3bda6b12012-02-02 23:15:15 +000010849 Var->setUsed(true);
10850}
10851
10852void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10853 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10854 // an object that satisfies the requirements for appearing in a
10855 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10856 // is immediately applied." This function handles the lvalue-to-rvalue
10857 // conversion part.
10858 MaybeODRUseExprs.erase(E->IgnoreParens());
10859}
10860
Eli Friedmanc6237c62012-02-29 03:16:56 +000010861ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10862 if (!Res.isUsable())
10863 return Res;
10864
10865 // If a constant-expression is a reference to a variable where we delay
10866 // deciding whether it is an odr-use, just assume we will apply the
10867 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
10868 // (a non-type template argument), we have special handling anyway.
10869 UpdateMarkingForLValueToRValue(Res.get());
10870 return Res;
10871}
10872
Eli Friedman3bda6b12012-02-02 23:15:15 +000010873void Sema::CleanupVarDeclMarking() {
10874 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10875 e = MaybeODRUseExprs.end();
10876 i != e; ++i) {
10877 VarDecl *Var;
10878 SourceLocation Loc;
John McCall113bee02012-03-10 09:33:50 +000010879 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010880 Var = cast<VarDecl>(DRE->getDecl());
10881 Loc = DRE->getLocation();
10882 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10883 Var = cast<VarDecl>(ME->getMemberDecl());
10884 Loc = ME->getMemberLoc();
10885 } else {
10886 llvm_unreachable("Unexpcted expression");
10887 }
10888
10889 MarkVarDeclODRUsed(*this, Var, Loc);
10890 }
10891
10892 MaybeODRUseExprs.clear();
10893}
10894
10895// Mark a VarDecl referenced, and perform the necessary handling to compute
10896// odr-uses.
10897static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10898 VarDecl *Var, Expr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010899 Var->setReferenced();
10900
Eli Friedman3bda6b12012-02-02 23:15:15 +000010901 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010902 return;
10903
10904 // Implicit instantiation of static data members of class templates.
Richard Smithd3cf2382012-02-15 02:42:50 +000010905 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010906 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10907 assert(MSInfo && "Missing member specialization information?");
Richard Smithd3cf2382012-02-15 02:42:50 +000010908 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10909 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000010910 (!AlreadyInstantiated ||
10911 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smithd3cf2382012-02-15 02:42:50 +000010912 if (!AlreadyInstantiated) {
10913 // This is a modification of an existing AST node. Notify listeners.
10914 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10915 L->StaticDataMemberInstantiated(Var);
10916 MSInfo->setPointOfInstantiation(Loc);
10917 }
10918 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar9d355812012-03-09 01:51:51 +000010919 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010920 // Do not defer instantiations of variables which could be used in a
10921 // constant expression.
Richard Smithd3cf2382012-02-15 02:42:50 +000010922 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010923 else
Richard Smithd3cf2382012-02-15 02:42:50 +000010924 SemaRef.PendingInstantiations.push_back(
10925 std::make_pair(Var, PointOfInstantiation));
Eli Friedmanfa0df832012-02-02 03:46:19 +000010926 }
10927 }
10928
Eli Friedman3bda6b12012-02-02 23:15:15 +000010929 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10930 // an object that satisfies the requirements for appearing in a
10931 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10932 // is immediately applied." We check the first part here, and
10933 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
10934 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith35ecb362012-03-02 04:14:40 +000010935 // C++03 depends on whether we get the C++03 version correct. This does not
10936 // apply to references, since they are not objects.
Eli Friedman3bda6b12012-02-02 23:15:15 +000010937 const VarDecl *DefVD;
Richard Smith35ecb362012-03-02 04:14:40 +000010938 if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000010939 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Eli Friedman3bda6b12012-02-02 23:15:15 +000010940 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
10941 SemaRef.MaybeODRUseExprs.insert(E);
10942 else
10943 MarkVarDeclODRUsed(SemaRef, Var, Loc);
10944}
Eli Friedmanfa0df832012-02-02 03:46:19 +000010945
Eli Friedman3bda6b12012-02-02 23:15:15 +000010946/// \brief Mark a variable referenced, and check whether it is odr-used
10947/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
10948/// used directly for normal expressions referring to VarDecl.
10949void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
10950 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010951}
10952
10953static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
10954 Decl *D, Expr *E) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010955 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
10956 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
10957 return;
10958 }
10959
Eli Friedmanfa0df832012-02-02 03:46:19 +000010960 SemaRef.MarkAnyDeclReferenced(Loc, D);
Rafael Espindola49e860b2012-06-26 17:45:31 +000010961
10962 // If this is a call to a method via a cast, also mark the method in the
10963 // derived class used in case codegen can devirtualize the call.
10964 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10965 if (!ME)
10966 return;
10967 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
10968 if (!MD)
10969 return;
10970 const Expr *Base = ME->getBase();
Rafael Espindolab7f5a9c2012-06-27 18:18:05 +000010971 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Rafael Espindola49e860b2012-06-26 17:45:31 +000010972 if (!MostDerivedClassDecl)
10973 return;
10974 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
Rafael Espindolaa245edc2012-06-27 17:44:39 +000010975 if (!DM)
10976 return;
Rafael Espindola49e860b2012-06-26 17:45:31 +000010977 SemaRef.MarkAnyDeclReferenced(Loc, DM);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010978}
Eli Friedmanfa0df832012-02-02 03:46:19 +000010979
Eli Friedmanfa0df832012-02-02 03:46:19 +000010980/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
10981void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
10982 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
10983}
10984
10985/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
10986void Sema::MarkMemberReferenced(MemberExpr *E) {
10987 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
10988}
10989
Douglas Gregorf02455e2012-02-10 09:26:04 +000010990/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedmanfa0df832012-02-02 03:46:19 +000010991/// marks the declaration referenced, and performs odr-use checking for functions
10992/// and variables. This method should not be used when building an normal
10993/// expression which refers to a variable.
10994void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
10995 if (VarDecl *VD = dyn_cast<VarDecl>(D))
10996 MarkVariableReferenced(Loc, VD);
10997 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
10998 MarkFunctionReferenced(Loc, FD);
10999 else
11000 D->setReferenced();
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000011001}
Anders Carlsson7f84ed92009-10-09 23:51:55 +000011002
Douglas Gregor5597ab42010-05-07 23:12:07 +000011003namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +000011004 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +000011005 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +000011006 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +000011007 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
11008 Sema &S;
11009 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +000011010
Douglas Gregor5597ab42010-05-07 23:12:07 +000011011 public:
11012 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +000011013
Douglas Gregor5597ab42010-05-07 23:12:07 +000011014 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +000011015
11016 bool TraverseTemplateArgument(const TemplateArgument &Arg);
11017 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +000011018 };
11019}
11020
Chandler Carruthaf80f662010-06-09 08:17:30 +000011021bool MarkReferencedDecls::TraverseTemplateArgument(
11022 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000011023 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +000011024 if (Decl *D = Arg.getAsDecl())
11025 S.MarkAnyDeclReferenced(Loc, D);
Douglas Gregor5597ab42010-05-07 23:12:07 +000011026 }
Chandler Carruthaf80f662010-06-09 08:17:30 +000011027
11028 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +000011029}
11030
Chandler Carruthaf80f662010-06-09 08:17:30 +000011031bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000011032 if (ClassTemplateSpecializationDecl *Spec
11033 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11034 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +000011035 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +000011036 }
11037
Chandler Carruthc65667c2010-06-10 10:31:57 +000011038 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +000011039}
11040
11041void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11042 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +000011043 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +000011044}
11045
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011046namespace {
11047 /// \brief Helper class that marks all of the declarations referenced by
11048 /// potentially-evaluated subexpressions as "referenced".
11049 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11050 Sema &S;
Douglas Gregor680e9e02012-02-21 19:11:17 +000011051 bool SkipLocalVariables;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011052
11053 public:
11054 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11055
Douglas Gregor680e9e02012-02-21 19:11:17 +000011056 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11057 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011058
11059 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregor680e9e02012-02-21 19:11:17 +000011060 // If we were asked not to visit local variables, don't.
11061 if (SkipLocalVariables) {
11062 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11063 if (VD->hasLocalStorage())
11064 return;
11065 }
11066
Eli Friedmanfa0df832012-02-02 03:46:19 +000011067 S.MarkDeclRefReferenced(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011068 }
11069
11070 void VisitMemberExpr(MemberExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011071 S.MarkMemberReferenced(E);
Douglas Gregor32b3de52010-09-11 23:32:50 +000011072 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011073 }
11074
John McCall28fc7092011-11-10 05:35:25 +000011075 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011076 S.MarkFunctionReferenced(E->getLocStart(),
John McCall28fc7092011-11-10 05:35:25 +000011077 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11078 Visit(E->getSubExpr());
11079 }
11080
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011081 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011082 if (E->getOperatorNew())
Eli Friedmanfa0df832012-02-02 03:46:19 +000011083 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011084 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000011085 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +000011086 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011087 }
Sebastian Redl6047f072012-02-16 12:22:20 +000011088
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011089 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11090 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000011091 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000011092 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11093 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11094 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedmanfa0df832012-02-02 03:46:19 +000011095 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000011096 S.LookupDestructor(Record));
11097 }
11098
Douglas Gregor32b3de52010-09-11 23:32:50 +000011099 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011100 }
11101
11102 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011103 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +000011104 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011105 }
11106
Douglas Gregorf0873f42010-10-19 17:17:35 +000011107 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11108 Visit(E->getExpr());
11109 }
Eli Friedman3bda6b12012-02-02 23:15:15 +000011110
11111 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11112 Inherited::VisitImplicitCastExpr(E);
11113
11114 if (E->getCastKind() == CK_LValueToRValue)
11115 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11116 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011117 };
11118}
11119
11120/// \brief Mark any declarations that appear within this expression or any
11121/// potentially-evaluated subexpressions as "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +000011122///
11123/// \param SkipLocalVariables If true, don't mark local variables as
11124/// 'referenced'.
11125void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11126 bool SkipLocalVariables) {
11127 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011128}
11129
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011130/// \brief Emit a diagnostic that describes an effect on the run-time behavior
11131/// of the program being compiled.
11132///
11133/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011134/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011135/// possibility that the code will actually be executable. Code in sizeof()
11136/// expressions, code used only during overload resolution, etc., are not
11137/// potentially evaluated. This routine will suppress such diagnostics or,
11138/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011139/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011140/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011141///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011142/// This routine should be used for all diagnostics that describe the run-time
11143/// behavior of a program, such as passing a non-POD value through an ellipsis.
11144/// Failure to do so will likely result in spurious diagnostics or failures
11145/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuba63ce62011-09-09 01:45:06 +000011146bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011147 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +000011148 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011149 case Unevaluated:
11150 // The argument will never be evaluated, so don't complain.
11151 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011152
Richard Smith764d2fe2011-12-20 02:08:33 +000011153 case ConstantEvaluated:
11154 // Relevant diagnostics should be produced by constant evaluation.
11155 break;
11156
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011157 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011158 case PotentiallyEvaluatedIfUsed:
Richard Trieuba63ce62011-09-09 01:45:06 +000011159 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +000011160 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuba63ce62011-09-09 01:45:06 +000011161 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek3427fac2011-02-23 01:52:04 +000011162 }
11163 else
11164 Diag(Loc, PD);
11165
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011166 return true;
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011167 }
11168
11169 return false;
11170}
11171
Anders Carlsson7f84ed92009-10-09 23:51:55 +000011172bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11173 CallExpr *CE, FunctionDecl *FD) {
11174 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11175 return false;
11176
Richard Smithfd555f62012-02-22 02:04:18 +000011177 // If we're inside a decltype's expression, don't check for a valid return
11178 // type or construct temporaries until we know whether this is the last call.
11179 if (ExprEvalContexts.back().IsDecltype) {
11180 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11181 return false;
11182 }
11183
Douglas Gregora6c5abb2012-05-04 16:48:41 +000011184 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011185 FunctionDecl *FD;
11186 CallExpr *CE;
11187
11188 public:
11189 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11190 : FD(FD), CE(CE) { }
11191
11192 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11193 if (!FD) {
11194 S.Diag(Loc, diag::err_call_incomplete_return)
11195 << T << CE->getSourceRange();
11196 return;
11197 }
11198
11199 S.Diag(Loc, diag::err_call_function_incomplete_return)
11200 << CE->getSourceRange() << FD->getDeclName() << T;
11201 S.Diag(FD->getLocation(),
11202 diag::note_function_with_incomplete_return_type_declared_here)
11203 << FD->getDeclName();
11204 }
11205 } Diagnoser(FD, CE);
11206
11207 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson7f84ed92009-10-09 23:51:55 +000011208 return true;
11209
11210 return false;
11211}
11212
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011213// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000011214// will prevent this condition from triggering, which is what we want.
11215void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11216 SourceLocation Loc;
11217
John McCall0506e4a2009-11-11 02:41:58 +000011218 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011219 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000011220
Chandler Carruthf87d6c02011-08-16 22:30:10 +000011221 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011222 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000011223 return;
11224
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011225 IsOrAssign = Op->getOpcode() == BO_OrAssign;
11226
John McCallb0e419e2009-11-12 00:06:05 +000011227 // Greylist some idioms by putting them into a warning subcategory.
11228 if (ObjCMessageExpr *ME
11229 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11230 Selector Sel = ME->getSelector();
11231
John McCallb0e419e2009-11-12 00:06:05 +000011232 // self = [<foo> init...]
Douglas Gregor486b74e2011-09-27 16:10:05 +000011233 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +000011234 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11235
11236 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000011237 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000011238 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11239 }
John McCall0506e4a2009-11-11 02:41:58 +000011240
John McCalld5707ab2009-10-12 21:59:07 +000011241 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +000011242 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011243 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000011244 return;
11245
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011246 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000011247 Loc = Op->getOperatorLoc();
Fariborz Jahanianf07bcc52012-08-29 17:17:11 +000011248 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
11249 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
11250 else {
John McCalld5707ab2009-10-12 21:59:07 +000011251 // Not an assignment.
11252 return;
11253 }
11254
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000011255 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011256
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011257 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000011258 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11259 Diag(Loc, diag::note_condition_assign_silence)
11260 << FixItHint::CreateInsertion(Open, "(")
11261 << FixItHint::CreateInsertion(Close, ")");
11262
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011263 if (IsOrAssign)
11264 Diag(Loc, diag::note_condition_or_assign_to_comparison)
11265 << FixItHint::CreateReplacement(Loc, "!=");
11266 else
11267 Diag(Loc, diag::note_condition_assign_to_comparison)
11268 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +000011269}
11270
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011271/// \brief Redundant parentheses over an equality comparison can indicate
11272/// that the user intended an assignment used as condition.
Richard Trieuba63ce62011-09-09 01:45:06 +000011273void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011274 // Don't warn if the parens came from a macro.
Richard Trieuba63ce62011-09-09 01:45:06 +000011275 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011276 if (parenLoc.isInvalid() || parenLoc.isMacroID())
11277 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000011278 // Don't warn for dependent expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +000011279 if (ParenE->isTypeDependent())
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000011280 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011281
Richard Trieuba63ce62011-09-09 01:45:06 +000011282 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011283
11284 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000011285 if (opE->getOpcode() == BO_EQ &&
11286 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11287 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011288 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000011289
Ted Kremenekae022092011-02-02 02:20:30 +000011290 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011291 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +000011292 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011293 << FixItHint::CreateRemoval(ParenERange.getBegin())
11294 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000011295 Diag(Loc, diag::note_equality_comparison_to_assign)
11296 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011297 }
11298}
11299
John Wiegley01296292011-04-08 18:41:53 +000011300ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +000011301 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011302 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11303 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000011304
John McCall0009fcc2011-04-26 20:42:42 +000011305 ExprResult result = CheckPlaceholderExpr(E);
11306 if (result.isInvalid()) return ExprError();
11307 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000011308
John McCall0009fcc2011-04-26 20:42:42 +000011309 if (!E->isTypeDependent()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000011310 if (getLangOpts().CPlusPlus)
John McCall34376a62010-12-04 03:47:34 +000011311 return CheckCXXBooleanCondition(E); // C++ 6.4p4
11312
John Wiegley01296292011-04-08 18:41:53 +000011313 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11314 if (ERes.isInvalid())
11315 return ExprError();
11316 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +000011317
11318 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000011319 if (!T->isScalarType()) { // C99 6.8.4.1p1
11320 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11321 << T << E->getSourceRange();
11322 return ExprError();
11323 }
John McCalld5707ab2009-10-12 21:59:07 +000011324 }
11325
John Wiegley01296292011-04-08 18:41:53 +000011326 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +000011327}
Douglas Gregore60e41a2010-05-06 17:25:47 +000011328
John McCalldadc5752010-08-24 06:29:42 +000011329ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +000011330 Expr *SubExpr) {
11331 if (!SubExpr)
Douglas Gregore60e41a2010-05-06 17:25:47 +000011332 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011333
Richard Trieuba63ce62011-09-09 01:45:06 +000011334 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +000011335}
John McCall36e7fe32010-10-12 00:20:44 +000011336
John McCall31996342011-04-07 08:22:57 +000011337namespace {
John McCall2979fe02011-04-12 00:42:48 +000011338 /// A visitor for rebuilding a call to an __unknown_any expression
11339 /// to have an appropriate type.
11340 struct RebuildUnknownAnyFunction
11341 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11342
11343 Sema &S;
11344
11345 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11346
11347 ExprResult VisitStmt(Stmt *S) {
11348 llvm_unreachable("unexpected statement!");
John McCall2979fe02011-04-12 00:42:48 +000011349 }
11350
Richard Trieu10162ab2011-09-09 03:59:41 +000011351 ExprResult VisitExpr(Expr *E) {
11352 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11353 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011354 return ExprError();
11355 }
11356
11357 /// Rebuild an expression which simply semantically wraps another
11358 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000011359 template <class T> ExprResult rebuildSugarExpr(T *E) {
11360 ExprResult SubResult = Visit(E->getSubExpr());
11361 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000011362
Richard Trieu10162ab2011-09-09 03:59:41 +000011363 Expr *SubExpr = SubResult.take();
11364 E->setSubExpr(SubExpr);
11365 E->setType(SubExpr->getType());
11366 E->setValueKind(SubExpr->getValueKind());
11367 assert(E->getObjectKind() == OK_Ordinary);
11368 return E;
John McCall2979fe02011-04-12 00:42:48 +000011369 }
11370
Richard Trieu10162ab2011-09-09 03:59:41 +000011371 ExprResult VisitParenExpr(ParenExpr *E) {
11372 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011373 }
11374
Richard Trieu10162ab2011-09-09 03:59:41 +000011375 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11376 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011377 }
11378
Richard Trieu10162ab2011-09-09 03:59:41 +000011379 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11380 ExprResult SubResult = Visit(E->getSubExpr());
11381 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000011382
Richard Trieu10162ab2011-09-09 03:59:41 +000011383 Expr *SubExpr = SubResult.take();
11384 E->setSubExpr(SubExpr);
11385 E->setType(S.Context.getPointerType(SubExpr->getType()));
11386 assert(E->getValueKind() == VK_RValue);
11387 assert(E->getObjectKind() == OK_Ordinary);
11388 return E;
John McCall2979fe02011-04-12 00:42:48 +000011389 }
11390
Richard Trieu10162ab2011-09-09 03:59:41 +000011391 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11392 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011393
Richard Trieu10162ab2011-09-09 03:59:41 +000011394 E->setType(VD->getType());
John McCall2979fe02011-04-12 00:42:48 +000011395
Richard Trieu10162ab2011-09-09 03:59:41 +000011396 assert(E->getValueKind() == VK_RValue);
David Blaikiebbafb8a2012-03-11 07:00:24 +000011397 if (S.getLangOpts().CPlusPlus &&
Richard Trieu10162ab2011-09-09 03:59:41 +000011398 !(isa<CXXMethodDecl>(VD) &&
11399 cast<CXXMethodDecl>(VD)->isInstance()))
11400 E->setValueKind(VK_LValue);
John McCall2979fe02011-04-12 00:42:48 +000011401
Richard Trieu10162ab2011-09-09 03:59:41 +000011402 return E;
John McCall2979fe02011-04-12 00:42:48 +000011403 }
11404
Richard Trieu10162ab2011-09-09 03:59:41 +000011405 ExprResult VisitMemberExpr(MemberExpr *E) {
11406 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000011407 }
11408
Richard Trieu10162ab2011-09-09 03:59:41 +000011409 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11410 return resolveDecl(E, E->getDecl());
John McCall2979fe02011-04-12 00:42:48 +000011411 }
11412 };
11413}
11414
11415/// Given a function expression of unknown-any type, try to rebuild it
11416/// to have a function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011417static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11418 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11419 if (Result.isInvalid()) return ExprError();
11420 return S.DefaultFunctionArrayConversion(Result.take());
John McCall2979fe02011-04-12 00:42:48 +000011421}
11422
11423namespace {
John McCall2d2e8702011-04-11 07:02:50 +000011424 /// A visitor for rebuilding an expression of type __unknown_anytype
11425 /// into one which resolves the type directly on the referring
11426 /// expression. Strict preservation of the original source
11427 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +000011428 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +000011429 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +000011430
11431 Sema &S;
11432
11433 /// The current destination type.
11434 QualType DestType;
11435
Richard Trieu10162ab2011-09-09 03:59:41 +000011436 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11437 : S(S), DestType(CastType) {}
John McCall31996342011-04-07 08:22:57 +000011438
John McCall39439732011-04-09 22:50:59 +000011439 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +000011440 llvm_unreachable("unexpected statement!");
John McCall31996342011-04-07 08:22:57 +000011441 }
11442
Richard Trieu10162ab2011-09-09 03:59:41 +000011443 ExprResult VisitExpr(Expr *E) {
11444 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11445 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011446 return ExprError();
John McCall31996342011-04-07 08:22:57 +000011447 }
11448
Richard Trieu10162ab2011-09-09 03:59:41 +000011449 ExprResult VisitCallExpr(CallExpr *E);
11450 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall2d2e8702011-04-11 07:02:50 +000011451
John McCall39439732011-04-09 22:50:59 +000011452 /// Rebuild an expression which simply semantically wraps another
11453 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000011454 template <class T> ExprResult rebuildSugarExpr(T *E) {
11455 ExprResult SubResult = Visit(E->getSubExpr());
11456 if (SubResult.isInvalid()) return ExprError();
11457 Expr *SubExpr = SubResult.take();
11458 E->setSubExpr(SubExpr);
11459 E->setType(SubExpr->getType());
11460 E->setValueKind(SubExpr->getValueKind());
11461 assert(E->getObjectKind() == OK_Ordinary);
11462 return E;
John McCall39439732011-04-09 22:50:59 +000011463 }
John McCall31996342011-04-07 08:22:57 +000011464
Richard Trieu10162ab2011-09-09 03:59:41 +000011465 ExprResult VisitParenExpr(ParenExpr *E) {
11466 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000011467 }
11468
Richard Trieu10162ab2011-09-09 03:59:41 +000011469 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11470 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000011471 }
11472
Richard Trieu10162ab2011-09-09 03:59:41 +000011473 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11474 const PointerType *Ptr = DestType->getAs<PointerType>();
11475 if (!Ptr) {
11476 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11477 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011478 return ExprError();
11479 }
Richard Trieu10162ab2011-09-09 03:59:41 +000011480 assert(E->getValueKind() == VK_RValue);
11481 assert(E->getObjectKind() == OK_Ordinary);
11482 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +000011483
11484 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011485 DestType = Ptr->getPointeeType();
11486 ExprResult SubResult = Visit(E->getSubExpr());
11487 if (SubResult.isInvalid()) return ExprError();
11488 E->setSubExpr(SubResult.take());
11489 return E;
John McCall2979fe02011-04-12 00:42:48 +000011490 }
11491
Richard Trieu10162ab2011-09-09 03:59:41 +000011492 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCall39439732011-04-09 22:50:59 +000011493
Richard Trieu10162ab2011-09-09 03:59:41 +000011494 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCall39439732011-04-09 22:50:59 +000011495
Richard Trieu10162ab2011-09-09 03:59:41 +000011496 ExprResult VisitMemberExpr(MemberExpr *E) {
11497 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000011498 }
John McCall39439732011-04-09 22:50:59 +000011499
Richard Trieu10162ab2011-09-09 03:59:41 +000011500 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11501 return resolveDecl(E, E->getDecl());
John McCall31996342011-04-07 08:22:57 +000011502 }
11503 };
11504}
11505
John McCall2d2e8702011-04-11 07:02:50 +000011506/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu10162ab2011-09-09 03:59:41 +000011507ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11508 Expr *CalleeExpr = E->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000011509
11510 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +000011511 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +000011512 FK_FunctionPointer,
11513 FK_BlockPointer
11514 };
11515
Richard Trieu10162ab2011-09-09 03:59:41 +000011516 FnKind Kind;
11517 QualType CalleeType = CalleeExpr->getType();
11518 if (CalleeType == S.Context.BoundMemberTy) {
11519 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11520 Kind = FK_MemberFunction;
11521 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11522 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11523 CalleeType = Ptr->getPointeeType();
11524 Kind = FK_FunctionPointer;
John McCall2d2e8702011-04-11 07:02:50 +000011525 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000011526 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11527 Kind = FK_BlockPointer;
John McCall2d2e8702011-04-11 07:02:50 +000011528 }
Richard Trieu10162ab2011-09-09 03:59:41 +000011529 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall2d2e8702011-04-11 07:02:50 +000011530
11531 // Verify that this is a legal result type of a function.
11532 if (DestType->isArrayType() || DestType->isFunctionType()) {
11533 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu10162ab2011-09-09 03:59:41 +000011534 if (Kind == FK_BlockPointer)
John McCall2d2e8702011-04-11 07:02:50 +000011535 diagID = diag::err_block_returning_array_function;
11536
Richard Trieu10162ab2011-09-09 03:59:41 +000011537 S.Diag(E->getExprLoc(), diagID)
John McCall2d2e8702011-04-11 07:02:50 +000011538 << DestType->isFunctionType() << DestType;
11539 return ExprError();
11540 }
11541
11542 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu10162ab2011-09-09 03:59:41 +000011543 E->setType(DestType.getNonLValueExprType(S.Context));
11544 E->setValueKind(Expr::getValueKindForType(DestType));
11545 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000011546
11547 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu10162ab2011-09-09 03:59:41 +000011548 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall2d2e8702011-04-11 07:02:50 +000011549 DestType = S.Context.getFunctionType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000011550 Proto->arg_type_begin(),
11551 Proto->getNumArgs(),
11552 Proto->getExtProtoInfo());
John McCall2d2e8702011-04-11 07:02:50 +000011553 else
11554 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000011555 FnType->getExtInfo());
John McCall2d2e8702011-04-11 07:02:50 +000011556
11557 // Rebuild the appropriate pointer-to-function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011558 switch (Kind) {
John McCall4adb38c2011-04-27 00:36:17 +000011559 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +000011560 // Nothing to do.
11561 break;
11562
11563 case FK_FunctionPointer:
11564 DestType = S.Context.getPointerType(DestType);
11565 break;
11566
11567 case FK_BlockPointer:
11568 DestType = S.Context.getBlockPointerType(DestType);
11569 break;
11570 }
11571
11572 // Finally, we can recurse.
Richard Trieu10162ab2011-09-09 03:59:41 +000011573 ExprResult CalleeResult = Visit(CalleeExpr);
11574 if (!CalleeResult.isUsable()) return ExprError();
11575 E->setCallee(CalleeResult.take());
John McCall2d2e8702011-04-11 07:02:50 +000011576
11577 // Bind a temporary if necessary.
Richard Trieu10162ab2011-09-09 03:59:41 +000011578 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000011579}
11580
Richard Trieu10162ab2011-09-09 03:59:41 +000011581ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000011582 // Verify that this is a legal result type of a call.
11583 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu10162ab2011-09-09 03:59:41 +000011584 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall2979fe02011-04-12 00:42:48 +000011585 << DestType->isFunctionType() << DestType;
11586 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011587 }
11588
John McCall3f4138c2011-07-13 17:56:40 +000011589 // Rewrite the method result type if available.
Richard Trieu10162ab2011-09-09 03:59:41 +000011590 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11591 assert(Method->getResultType() == S.Context.UnknownAnyTy);
11592 Method->setResultType(DestType);
John McCall3f4138c2011-07-13 17:56:40 +000011593 }
John McCall2979fe02011-04-12 00:42:48 +000011594
John McCall2d2e8702011-04-11 07:02:50 +000011595 // Change the type of the message.
Richard Trieu10162ab2011-09-09 03:59:41 +000011596 E->setType(DestType.getNonReferenceType());
11597 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000011598
Richard Trieu10162ab2011-09-09 03:59:41 +000011599 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000011600}
11601
Richard Trieu10162ab2011-09-09 03:59:41 +000011602ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000011603 // The only case we should ever see here is a function-to-pointer decay.
Sean Callanan2db103c2012-03-06 23:12:57 +000011604 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanan12495112012-03-06 21:34:12 +000011605 assert(E->getValueKind() == VK_RValue);
11606 assert(E->getObjectKind() == OK_Ordinary);
11607
11608 E->setType(DestType);
11609
11610 // Rebuild the sub-expression as the pointee (function) type.
11611 DestType = DestType->castAs<PointerType>()->getPointeeType();
11612
11613 ExprResult Result = Visit(E->getSubExpr());
11614 if (!Result.isUsable()) return ExprError();
11615
11616 E->setSubExpr(Result.take());
11617 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000011618 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanan12495112012-03-06 21:34:12 +000011619 assert(E->getValueKind() == VK_RValue);
11620 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000011621
Sean Callanan12495112012-03-06 21:34:12 +000011622 assert(isa<BlockPointerType>(E->getType()));
John McCall2979fe02011-04-12 00:42:48 +000011623
Sean Callanan12495112012-03-06 21:34:12 +000011624 E->setType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000011625
Sean Callanan12495112012-03-06 21:34:12 +000011626 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11627 DestType = S.Context.getLValueReferenceType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000011628
Sean Callanan12495112012-03-06 21:34:12 +000011629 ExprResult Result = Visit(E->getSubExpr());
11630 if (!Result.isUsable()) return ExprError();
11631
11632 E->setSubExpr(Result.take());
11633 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000011634 } else {
Sean Callanan12495112012-03-06 21:34:12 +000011635 llvm_unreachable("Unhandled cast type!");
11636 }
John McCall2d2e8702011-04-11 07:02:50 +000011637}
11638
Richard Trieu10162ab2011-09-09 03:59:41 +000011639ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11640 ExprValueKind ValueKind = VK_LValue;
11641 QualType Type = DestType;
John McCall2d2e8702011-04-11 07:02:50 +000011642
11643 // We know how to make this work for certain kinds of decls:
11644
11645 // - functions
Richard Trieu10162ab2011-09-09 03:59:41 +000011646 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11647 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11648 DestType = Ptr->getPointeeType();
11649 ExprResult Result = resolveDecl(E, VD);
11650 if (Result.isInvalid()) return ExprError();
11651 return S.ImpCastExprToType(Result.take(), Type,
John McCall9a877fe2011-08-10 04:12:23 +000011652 CK_FunctionToPointerDecay, VK_RValue);
11653 }
11654
Richard Trieu10162ab2011-09-09 03:59:41 +000011655 if (!Type->isFunctionType()) {
11656 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11657 << VD << E->getSourceRange();
John McCall9a877fe2011-08-10 04:12:23 +000011658 return ExprError();
11659 }
John McCall2d2e8702011-04-11 07:02:50 +000011660
Richard Trieu10162ab2011-09-09 03:59:41 +000011661 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11662 if (MD->isInstance()) {
11663 ValueKind = VK_RValue;
11664 Type = S.Context.BoundMemberTy;
John McCall4adb38c2011-04-27 00:36:17 +000011665 }
11666
John McCall2d2e8702011-04-11 07:02:50 +000011667 // Function references aren't l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011668 if (!S.getLangOpts().CPlusPlus)
Richard Trieu10162ab2011-09-09 03:59:41 +000011669 ValueKind = VK_RValue;
John McCall2d2e8702011-04-11 07:02:50 +000011670
11671 // - variables
Richard Trieu10162ab2011-09-09 03:59:41 +000011672 } else if (isa<VarDecl>(VD)) {
11673 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11674 Type = RefTy->getPointeeType();
11675 } else if (Type->isFunctionType()) {
11676 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11677 << VD << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011678 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011679 }
11680
11681 // - nothing else
11682 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000011683 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11684 << VD << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011685 return ExprError();
11686 }
11687
Richard Trieu10162ab2011-09-09 03:59:41 +000011688 VD->setType(DestType);
11689 E->setType(Type);
11690 E->setValueKind(ValueKind);
11691 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +000011692}
11693
John McCall31996342011-04-07 08:22:57 +000011694/// Check a cast of an unknown-any type. We intentionally only
11695/// trigger this for C-style casts.
Richard Trieuba63ce62011-09-09 01:45:06 +000011696ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11697 Expr *CastExpr, CastKind &CastKind,
11698 ExprValueKind &VK, CXXCastPath &Path) {
John McCall31996342011-04-07 08:22:57 +000011699 // Rewrite the casted expression from scratch.
Richard Trieuba63ce62011-09-09 01:45:06 +000011700 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCall39439732011-04-09 22:50:59 +000011701 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000011702
Richard Trieuba63ce62011-09-09 01:45:06 +000011703 CastExpr = result.take();
11704 VK = CastExpr->getValueKind();
11705 CastKind = CK_NoOp;
John McCall39439732011-04-09 22:50:59 +000011706
Richard Trieuba63ce62011-09-09 01:45:06 +000011707 return CastExpr;
John McCall31996342011-04-07 08:22:57 +000011708}
11709
Douglas Gregord8fb1e32011-12-01 01:37:36 +000011710ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11711 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11712}
11713
Richard Trieuba63ce62011-09-09 01:45:06 +000011714static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11715 Expr *orig = E;
John McCall2d2e8702011-04-11 07:02:50 +000011716 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000011717 while (true) {
Richard Trieuba63ce62011-09-09 01:45:06 +000011718 E = E->IgnoreParenImpCasts();
11719 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11720 E = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000011721 diagID = diag::err_uncasted_call_of_unknown_any;
11722 } else {
John McCall31996342011-04-07 08:22:57 +000011723 break;
John McCall2d2e8702011-04-11 07:02:50 +000011724 }
John McCall31996342011-04-07 08:22:57 +000011725 }
11726
John McCall2d2e8702011-04-11 07:02:50 +000011727 SourceLocation loc;
11728 NamedDecl *d;
Richard Trieuba63ce62011-09-09 01:45:06 +000011729 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011730 loc = ref->getLocation();
11731 d = ref->getDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011732 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011733 loc = mem->getMemberLoc();
11734 d = mem->getMemberDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011735 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011736 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidisa6011e22011-10-03 06:36:51 +000011737 loc = msg->getSelectorStartLoc();
John McCall2d2e8702011-04-11 07:02:50 +000011738 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000011739 if (!d) {
11740 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11741 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11742 << orig->getSourceRange();
11743 return ExprError();
11744 }
John McCall2d2e8702011-04-11 07:02:50 +000011745 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +000011746 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11747 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011748 return ExprError();
11749 }
11750
11751 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000011752
11753 // Never recoverable.
11754 return ExprError();
11755}
11756
John McCall36e7fe32010-10-12 00:20:44 +000011757/// Check for operands with placeholder types and complain if found.
11758/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000011759ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall4124c492011-10-17 18:40:02 +000011760 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11761 if (!placeholderType) return Owned(E);
11762
11763 switch (placeholderType->getKind()) {
John McCall36e7fe32010-10-12 00:20:44 +000011764
John McCall31996342011-04-07 08:22:57 +000011765 // Overloaded expressions.
John McCall4124c492011-10-17 18:40:02 +000011766 case BuiltinType::Overload: {
John McCall50a2c2c2011-10-11 23:14:30 +000011767 // Try to resolve a single function template specialization.
11768 // This is obligatory.
11769 ExprResult result = Owned(E);
11770 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11771 return result;
11772
11773 // If that failed, try to recover with a call.
11774 } else {
11775 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11776 /*complain*/ true);
11777 return result;
11778 }
11779 }
John McCall31996342011-04-07 08:22:57 +000011780
John McCall0009fcc2011-04-26 20:42:42 +000011781 // Bound member functions.
John McCall4124c492011-10-17 18:40:02 +000011782 case BuiltinType::BoundMember: {
John McCall50a2c2c2011-10-11 23:14:30 +000011783 ExprResult result = Owned(E);
11784 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11785 /*complain*/ true);
11786 return result;
John McCall4124c492011-10-17 18:40:02 +000011787 }
11788
11789 // ARC unbridged casts.
11790 case BuiltinType::ARCUnbridgedCast: {
11791 Expr *realCast = stripARCUnbridgedCast(E);
11792 diagnoseARCUnbridgedCast(realCast);
11793 return Owned(realCast);
11794 }
John McCall0009fcc2011-04-26 20:42:42 +000011795
John McCall31996342011-04-07 08:22:57 +000011796 // Expressions of unknown type.
John McCall4124c492011-10-17 18:40:02 +000011797 case BuiltinType::UnknownAny:
John McCall31996342011-04-07 08:22:57 +000011798 return diagnoseUnknownAnyExpr(*this, E);
11799
John McCall526ab472011-10-25 17:37:35 +000011800 // Pseudo-objects.
11801 case BuiltinType::PseudoObject:
11802 return checkPseudoObjectRValue(E);
11803
Eli Friedman34866c72012-08-31 00:14:07 +000011804 case BuiltinType::BuiltinFn:
11805 Diag(E->getLocStart(), diag::err_builtin_fn_use);
11806 return ExprError();
11807
John McCalle314e272011-10-18 21:02:43 +000011808 // Everything else should be impossible.
11809#define BUILTIN_TYPE(Id, SingletonId) \
11810 case BuiltinType::Id:
11811#define PLACEHOLDER_TYPE(Id, SingletonId)
11812#include "clang/AST/BuiltinTypes.def"
John McCall4124c492011-10-17 18:40:02 +000011813 break;
11814 }
11815
11816 llvm_unreachable("invalid placeholder type!");
John McCall36e7fe32010-10-12 00:20:44 +000011817}
Richard Trieu2c850c02011-04-21 21:44:26 +000011818
Richard Trieuba63ce62011-09-09 01:45:06 +000011819bool Sema::CheckCaseExpression(Expr *E) {
11820 if (E->isTypeDependent())
Richard Trieu2c850c02011-04-21 21:44:26 +000011821 return true;
Richard Trieuba63ce62011-09-09 01:45:06 +000011822 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11823 return E->getType()->isIntegralOrEnumerationType();
Richard Trieu2c850c02011-04-21 21:44:26 +000011824 return false;
11825}
Ted Kremeneke65b0862012-03-06 20:05:56 +000011826
11827/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11828ExprResult
11829Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11830 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11831 "Unknown Objective-C Boolean value!");
Fariborz Jahanianf2578572012-08-30 18:49:41 +000011832 QualType BoolT = Context.ObjCBuiltinBoolTy;
11833 if (!Context.getBOOLDecl()) {
11834 LookupResult Result(*this, &Context.Idents.get("BOOL"), SourceLocation(),
11835 Sema::LookupOrdinaryName);
11836 if (LookupName(Result, getCurScope())) {
11837 NamedDecl *ND = Result.getFoundDecl();
11838 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
11839 Context.setBOOLDecl(TD);
11840 }
11841 }
11842 if (Context.getBOOLDecl())
11843 BoolT = Context.getBOOLType();
Ted Kremeneke65b0862012-03-06 20:05:56 +000011844 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanianf2578572012-08-30 18:49:41 +000011845 BoolT, OpLoc));
Ted Kremeneke65b0862012-03-06 20:05:56 +000011846}