blob: 0570dd38c79f41cfbb221a7e1d6186bef61db347 [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000015#include "clang/Sema/DelayedDiagnostic.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000018#include "clang/Sema/ScopeInfo.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000019#include "clang/Sema/AnalysisBasedWarnings.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000020#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000021#include "clang/AST/ASTConsumer.h"
Sebastian Redl2ac2c722011-04-29 08:19:30 +000022#include "clang/AST/ASTMutationListener.h"
Douglas Gregord1702062010-04-29 00:18:15 +000023#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000025#include "clang/AST/DeclTemplate.h"
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000026#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000027#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000028#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000029#include "clang/AST/ExprObjC.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000030#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000031#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000032#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000033#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000034#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000035#include "clang/Lex/LiteralSupport.h"
36#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000037#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/Designator.h"
39#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000040#include "clang/Sema/ScopeInfo.h"
John McCall8b0666c2010-08-20 18:27:03 +000041#include "clang/Sema/ParsedTemplate.h"
Anna Zaks3b402712011-07-28 19:51:27 +000042#include "clang/Sema/SemaFixItUtils.h"
John McCallde6836a2010-08-24 07:21:54 +000043#include "clang/Sema/Template.h"
Eli Friedman456f0182012-01-20 01:26:23 +000044#include "TreeTransform.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000045using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000046using namespace sema;
Chris Lattner5b183d82006-11-10 05:03:26 +000047
Sebastian Redlb49c46c2011-09-24 17:48:00 +000048/// \brief Determine whether the use of this declaration is valid, without
49/// emitting diagnostics.
50bool Sema::CanUseDecl(NamedDecl *D) {
51 // See if this is an auto-typed variable whose initializer we are parsing.
52 if (ParsingInitForAutoVars.count(D))
53 return false;
54
55 // See if this is a deleted function.
56 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
57 if (FD->isDeleted())
58 return false;
59 }
Sebastian Redl5999aec2011-10-16 18:19:16 +000060
61 // See if this function is unavailable.
62 if (D->getAvailability() == AR_Unavailable &&
63 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
64 return false;
65
Sebastian Redlb49c46c2011-09-24 17:48:00 +000066 return true;
67}
David Chisnall9f57c292009-08-17 16:35:33 +000068
Fariborz Jahanian66c93f42012-09-06 16:43:18 +000069static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
70 // Warn if this is used but marked unused.
71 if (D->hasAttr<UnusedAttr>()) {
Fariborz Jahanian979780f2012-09-06 18:38:58 +000072 const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
Fariborz Jahanian66c93f42012-09-06 16:43:18 +000073 if (!DC->hasAttr<UnusedAttr>())
74 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
75 }
76}
77
Ted Kremenek6eb25622012-02-10 02:45:47 +000078static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000079 NamedDecl *D, SourceLocation Loc,
80 const ObjCInterfaceDecl *UnknownObjCClass) {
81 // See if this declaration is unavailable or deprecated.
82 std::string Message;
83 AvailabilityResult Result = D->getAvailability(&Message);
Fariborz Jahanian25d09c22011-11-28 19:45:58 +000084 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
85 if (Result == AR_Available) {
86 const DeclContext *DC = ECD->getDeclContext();
87 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
88 Result = TheEnumDecl->getAvailability(&Message);
89 }
Fariborz Jahanian974c9482012-09-21 20:46:37 +000090 const ObjCPropertyDecl *ObjCPDecl = 0;
91 if (Result == AR_Deprecated || Result == AR_Unavailable)
92 if (ObjCPropertyDecl *ND = S.PropertyIfSetterOrGetter(D)) {
93 AvailabilityResult PDeclResult = ND->getAvailability(0);
94 if (PDeclResult == Result)
95 ObjCPDecl = ND;
96 }
Fariborz Jahanian25d09c22011-11-28 19:45:58 +000097
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000098 switch (Result) {
99 case AR_Available:
100 case AR_NotYetIntroduced:
101 break;
102
103 case AR_Deprecated:
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000104 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl);
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000105 break;
106
107 case AR_Unavailable:
Ted Kremenek6eb25622012-02-10 02:45:47 +0000108 if (S.getCurContextAvailability() != AR_Unavailable) {
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000109 if (Message.empty()) {
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000110 if (!UnknownObjCClass) {
Ted Kremenek6eb25622012-02-10 02:45:47 +0000111 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000112 if (ObjCPDecl)
113 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
114 << ObjCPDecl->getDeclName() << 1;
115 }
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000116 else
Ted Kremenek6eb25622012-02-10 02:45:47 +0000117 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000118 << D->getDeclName();
119 }
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000120 else
Ted Kremenek6eb25622012-02-10 02:45:47 +0000121 S.Diag(Loc, diag::err_unavailable_message)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000122 << D->getDeclName() << Message;
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000123 S.Diag(D->getLocation(), diag::note_unavailable_here)
124 << isa<FunctionDecl>(D) << false;
125 if (ObjCPDecl)
126 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
127 << ObjCPDecl->getDeclName() << 1;
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000128 }
129 break;
130 }
131 return Result;
132}
133
Richard Smith852265f2012-03-30 20:53:28 +0000134/// \brief Emit a note explaining that this function is deleted or unavailable.
135void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
136 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
137
Richard Smith6f1e2c62012-04-02 20:59:25 +0000138 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
139 // If the method was explicitly defaulted, point at that declaration.
140 if (!Method->isImplicit())
141 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
142
143 // Try to diagnose why this special member function was implicitly
144 // deleted. This might fail, if that reason no longer applies.
Richard Smith852265f2012-03-30 20:53:28 +0000145 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +0000146 if (CSM != CXXInvalid)
147 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
148
149 return;
Richard Smith852265f2012-03-30 20:53:28 +0000150 }
151
152 Diag(Decl->getLocation(), diag::note_unavailable_here)
153 << 1 << Decl->isDeleted();
154}
155
Jordan Rose28cd12f2012-06-18 22:09:19 +0000156/// \brief Determine whether a FunctionDecl was ever declared with an
157/// explicit storage class.
158static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
159 for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
160 E = D->redecls_end();
161 I != E; ++I) {
162 if (I->getStorageClassAsWritten() != SC_None)
163 return true;
164 }
165 return false;
166}
167
168/// \brief Check whether we're in an extern inline function and referring to a
Jordan Rosede9e9762012-06-20 18:50:06 +0000169/// variable or function with internal linkage (C11 6.7.4p3).
Jordan Rose28cd12f2012-06-18 22:09:19 +0000170///
Jordan Rose28cd12f2012-06-18 22:09:19 +0000171/// This is only a warning because we used to silently accept this code, but
Jordan Rosede9e9762012-06-20 18:50:06 +0000172/// in many cases it will not behave correctly. This is not enabled in C++ mode
173/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
174/// and so while there may still be user mistakes, most of the time we can't
175/// prove that there are errors.
Jordan Rose28cd12f2012-06-18 22:09:19 +0000176static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
177 const NamedDecl *D,
178 SourceLocation Loc) {
Jordan Rosede9e9762012-06-20 18:50:06 +0000179 // This is disabled under C++; there are too many ways for this to fire in
180 // contexts where the warning is a false positive, or where it is technically
181 // correct but benign.
182 if (S.getLangOpts().CPlusPlus)
183 return;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000184
185 // Check if this is an inlined function or method.
186 FunctionDecl *Current = S.getCurFunctionDecl();
187 if (!Current)
188 return;
189 if (!Current->isInlined())
190 return;
191 if (Current->getLinkage() != ExternalLinkage)
192 return;
193
194 // Check if the decl has internal linkage.
Jordan Rosede9e9762012-06-20 18:50:06 +0000195 if (D->getLinkage() != InternalLinkage)
Jordan Rose28cd12f2012-06-18 22:09:19 +0000196 return;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000197
Jordan Rose815fe262012-06-21 05:54:50 +0000198 // Downgrade from ExtWarn to Extension if
199 // (1) the supposedly external inline function is in the main file,
200 // and probably won't be included anywhere else.
201 // (2) the thing we're referencing is a pure function.
202 // (3) the thing we're referencing is another inline function.
203 // This last can give us false negatives, but it's better than warning on
204 // wrappers for simple C library functions.
205 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
206 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
207 if (!DowngradeWarning && UsedFn)
208 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
209
210 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
211 : diag::warn_internal_in_extern_inline)
212 << /*IsVar=*/!UsedFn << D;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000213
214 // Suggest "static" on the inline function, if possible.
Jordan Rosede9e9762012-06-20 18:50:06 +0000215 if (!hasAnyExplicitStorageClass(Current)) {
Jordan Rose28cd12f2012-06-18 22:09:19 +0000216 const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
217 SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
218 S.Diag(DeclBegin, diag::note_convert_inline_to_static)
219 << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
220 }
221
222 S.Diag(D->getCanonicalDecl()->getLocation(),
223 diag::note_internal_decl_declared_here)
224 << D;
225}
226
Douglas Gregor171c45a2009-02-18 21:56:37 +0000227/// \brief Determine whether the use of this declaration is valid, and
228/// emit any corresponding diagnostics.
229///
230/// This routine diagnoses various problems with referencing
231/// declarations that can occur when using a declaration. For example,
232/// it might warn if a deprecated or unavailable declaration is being
233/// used, or produce an error (and return true) if a C++0x deleted
234/// function is being used.
235///
236/// \returns true if there was an error (this declaration cannot be
237/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +0000238///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +0000239bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000240 const ObjCInterfaceDecl *UnknownObjCClass) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000241 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000242 // If there were any diagnostics suppressed by template argument deduction,
243 // emit them now.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000244 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000245 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
246 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000247 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000248 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
249 Diag(Suppressed[I].first, Suppressed[I].second);
250
251 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000252 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000253 // entry from the table, because we want to avoid ever emitting these
254 // diagnostics again.
255 Suppressed.clear();
256 }
257 }
258
Richard Smith30482bc2011-02-20 03:19:35 +0000259 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +0000260 if (ParsingInitForAutoVars.count(D)) {
261 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
262 << D->getDeclName();
263 return true;
Richard Smith30482bc2011-02-20 03:19:35 +0000264 }
265
Douglas Gregor171c45a2009-02-18 21:56:37 +0000266 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +0000267 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +0000268 if (FD->isDeleted()) {
269 Diag(Loc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +0000270 NoteDeletedFunction(FD);
Douglas Gregor171c45a2009-02-18 21:56:37 +0000271 return true;
272 }
Douglas Gregorde681d42009-02-24 04:26:15 +0000273 }
Ted Kremenek6eb25622012-02-10 02:45:47 +0000274 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000275
Fariborz Jahanian66c93f42012-09-06 16:43:18 +0000276 DiagnoseUnusedOfDecl(*this, D, Loc);
Jordan Rose2684c682012-06-15 18:19:48 +0000277
Jordan Rose28cd12f2012-06-18 22:09:19 +0000278 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
Jordan Rose2684c682012-06-15 18:19:48 +0000279
Douglas Gregor171c45a2009-02-18 21:56:37 +0000280 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000281}
282
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000283/// \brief Retrieve the message suffix that should be added to a
284/// diagnostic complaining about the given function being deleted or
285/// unavailable.
286std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
287 // FIXME: C++0x implicitly-deleted special member functions could be
288 // detected here so that we could improve diagnostics to say, e.g.,
289 // "base class 'A' had a deleted copy constructor".
290 if (FD->isDeleted())
291 return std::string();
292
293 std::string Message;
294 if (FD->getAvailability(&Message))
295 return ": " + Message;
296
297 return std::string();
298}
299
John McCallb46f2872011-09-09 07:56:05 +0000300/// DiagnoseSentinelCalls - This routine checks whether a call or
301/// message-send is to a declaration with the sentinel attribute, and
302/// if so, it checks that the requirements of the sentinel are
303/// satisfied.
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000304void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCallb46f2872011-09-09 07:56:05 +0000305 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000306 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000307 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000308 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000309
John McCallb46f2872011-09-09 07:56:05 +0000310 // The number of formal parameters of the declaration.
311 unsigned numFormalParams;
Mike Stump11289f42009-09-09 15:08:12 +0000312
John McCallb46f2872011-09-09 07:56:05 +0000313 // The kind of declaration. This is also an index into a %select in
314 // the diagnostic.
315 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
316
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000317 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000318 numFormalParams = MD->param_size();
319 calleeType = CT_Method;
Mike Stump12b8ce12009-08-04 21:02:39 +0000320 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000321 numFormalParams = FD->param_size();
322 calleeType = CT_Function;
323 } else if (isa<VarDecl>(D)) {
324 QualType type = cast<ValueDecl>(D)->getType();
325 const FunctionType *fn = 0;
326 if (const PointerType *ptr = type->getAs<PointerType>()) {
327 fn = ptr->getPointeeType()->getAs<FunctionType>();
328 if (!fn) return;
329 calleeType = CT_Function;
330 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
331 fn = ptr->getPointeeType()->castAs<FunctionType>();
332 calleeType = CT_Block;
333 } else {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000334 return;
John McCallb46f2872011-09-09 07:56:05 +0000335 }
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000336
John McCallb46f2872011-09-09 07:56:05 +0000337 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
338 numFormalParams = proto->getNumArgs();
339 } else {
340 numFormalParams = 0;
341 }
342 } else {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000343 return;
344 }
John McCallb46f2872011-09-09 07:56:05 +0000345
346 // "nullPos" is the number of formal parameters at the end which
347 // effectively count as part of the variadic arguments. This is
348 // useful if you would prefer to not have *any* formal parameters,
349 // but the language forces you to have at least one.
350 unsigned nullPos = attr->getNullPos();
351 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
352 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
353
354 // The number of arguments which should follow the sentinel.
355 unsigned numArgsAfterSentinel = attr->getSentinel();
356
357 // If there aren't enough arguments for all the formal parameters,
358 // the sentinel, and the args after the sentinel, complain.
359 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000360 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCallb46f2872011-09-09 07:56:05 +0000361 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000362 return;
363 }
John McCallb46f2872011-09-09 07:56:05 +0000364
365 // Otherwise, find the sentinel expression.
366 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall7ddbcf42010-05-06 23:53:00 +0000367 if (!sentinelExpr) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000368 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +0000369 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000370
John McCallb46f2872011-09-09 07:56:05 +0000371 // Pick a reasonable string to insert. Optimistically use 'nil' or
372 // 'NULL' if those are actually defined in the context. Only use
373 // 'nil' for ObjC methods, where it's much more likely that the
374 // variadic arguments form a list of object pointers.
375 SourceLocation MissingNilLoc
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000376 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
377 std::string NullValue;
John McCallb46f2872011-09-09 07:56:05 +0000378 if (calleeType == CT_Method &&
379 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000380 NullValue = "nil";
381 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
382 NullValue = "NULL";
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000383 else
John McCallb46f2872011-09-09 07:56:05 +0000384 NullValue = "(void*) 0";
Eli Friedman9ab36372011-09-27 23:46:37 +0000385
386 if (MissingNilLoc.isInvalid())
387 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
388 else
389 Diag(MissingNilLoc, diag::warn_missing_sentinel)
390 << calleeType
391 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCallb46f2872011-09-09 07:56:05 +0000392 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000393}
394
Richard Trieuba63ce62011-09-09 01:45:06 +0000395SourceRange Sema::getExprRange(Expr *E) const {
396 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor87f95b02009-02-26 21:00:50 +0000397}
398
Chris Lattner513165e2008-07-25 21:10:04 +0000399//===----------------------------------------------------------------------===//
400// Standard Promotions and Conversions
401//===----------------------------------------------------------------------===//
402
Chris Lattner513165e2008-07-25 21:10:04 +0000403/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000404ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000405 // Handle any placeholder expressions which made it here.
406 if (E->getType()->isPlaceholderType()) {
407 ExprResult result = CheckPlaceholderExpr(E);
408 if (result.isInvalid()) return ExprError();
409 E = result.take();
410 }
411
Chris Lattner513165e2008-07-25 21:10:04 +0000412 QualType Ty = E->getType();
413 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
414
Chris Lattner513165e2008-07-25 21:10:04 +0000415 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000416 E = ImpCastExprToType(E, Context.getPointerType(Ty),
417 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000418 else if (Ty->isArrayType()) {
419 // In C90 mode, arrays only promote to pointers if the array expression is
420 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
421 // type 'array of type' is converted to an expression that has type 'pointer
422 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
423 // that has type 'array of type' ...". The relevant change is "an lvalue"
424 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000425 //
426 // C++ 4.2p1:
427 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
428 // T" can be converted to an rvalue of type "pointer to T".
429 //
David Blaikiebbafb8a2012-03-11 07:00:24 +0000430 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000431 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
432 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000433 }
John Wiegley01296292011-04-08 18:41:53 +0000434 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000435}
436
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000437static void CheckForNullPointerDereference(Sema &S, Expr *E) {
438 // Check to see if we are dereferencing a null pointer. If so,
439 // and if not volatile-qualified, this is undefined behavior that the
440 // optimizer will delete, so warn about it. People sometimes try to use this
441 // to get a deterministic trap and are surprised by clang's behavior. This
442 // only handles the pattern "*null", which is a very syntactic check.
443 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
444 if (UO->getOpcode() == UO_Deref &&
445 UO->getSubExpr()->IgnoreParenCasts()->
446 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
447 !UO->getType().isVolatileQualified()) {
448 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
449 S.PDiag(diag::warn_indirection_through_null)
450 << UO->getSubExpr()->getSourceRange());
451 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
452 S.PDiag(diag::note_indirection_through_null));
453 }
454}
455
John Wiegley01296292011-04-08 18:41:53 +0000456ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000457 // Handle any placeholder expressions which made it here.
458 if (E->getType()->isPlaceholderType()) {
459 ExprResult result = CheckPlaceholderExpr(E);
460 if (result.isInvalid()) return ExprError();
461 E = result.take();
462 }
463
John McCallf3735e02010-12-01 04:43:34 +0000464 // C++ [conv.lval]p1:
465 // A glvalue of a non-function, non-array type T can be
466 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000467 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +0000468
John McCall27584242010-12-06 20:48:59 +0000469 QualType T = E->getType();
470 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000471
John McCall27584242010-12-06 20:48:59 +0000472 // We don't want to throw lvalue-to-rvalue casts on top of
473 // expressions of certain types in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000474 if (getLangOpts().CPlusPlus &&
John McCall27584242010-12-06 20:48:59 +0000475 (E->getType() == Context.OverloadTy ||
476 T->isDependentType() ||
477 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000478 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000479
480 // The C standard is actually really unclear on this point, and
481 // DR106 tells us what the result should be but not why. It's
482 // generally best to say that void types just doesn't undergo
483 // lvalue-to-rvalue at all. Note that expressions of unqualified
484 // 'void' type are never l-values, but qualified void can be.
485 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000486 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000487
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000488 CheckForNullPointerDereference(*this, E);
489
John McCall27584242010-12-06 20:48:59 +0000490 // C++ [conv.lval]p1:
491 // [...] If T is a non-class type, the type of the prvalue is the
492 // cv-unqualified version of T. Otherwise, the type of the
493 // rvalue is T.
494 //
495 // C99 6.3.2.1p2:
496 // If the lvalue has qualified type, the value has the unqualified
497 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000498 // type of the lvalue.
John McCall27584242010-12-06 20:48:59 +0000499 if (T.hasQualifiers())
500 T = T.getUnqualifiedType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000501
Eli Friedman3bda6b12012-02-02 23:15:15 +0000502 UpdateMarkingForLValueToRValue(E);
503
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000504 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
505 E, 0, VK_RValue));
506
Douglas Gregorc79862f2012-04-12 17:51:55 +0000507 // C11 6.3.2.1p2:
508 // ... if the lvalue has atomic type, the value has the non-atomic version
509 // of the type of the lvalue ...
510 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
511 T = Atomic->getValueType().getUnqualifiedType();
512 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
513 Res.get(), 0, VK_RValue));
514 }
515
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000516 return Res;
John McCall27584242010-12-06 20:48:59 +0000517}
518
John Wiegley01296292011-04-08 18:41:53 +0000519ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
520 ExprResult Res = DefaultFunctionArrayConversion(E);
521 if (Res.isInvalid())
522 return ExprError();
523 Res = DefaultLvalueConversion(Res.take());
524 if (Res.isInvalid())
525 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000526 return Res;
Douglas Gregorb92a1562010-02-03 00:27:59 +0000527}
528
529
Chris Lattner513165e2008-07-25 21:10:04 +0000530/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000531/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000532/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000533/// apply if the array is an argument to the sizeof or address (&) operators.
534/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000535ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000536 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000537 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
538 if (Res.isInvalid())
539 return Owned(E);
540 E = Res.take();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000541
John McCallf3735e02010-12-01 04:43:34 +0000542 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000543 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000544
545 // Half FP is a bit different: it's a storage-only type, meaning that any
546 // "use" of it should be promoted to float.
547 if (Ty->isHalfType())
548 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
549
John McCallf3735e02010-12-01 04:43:34 +0000550 // Try to perform integral promotions if the object has a theoretically
551 // promotable type.
552 if (Ty->isIntegralOrUnscopedEnumerationType()) {
553 // C99 6.3.1.1p2:
554 //
555 // The following may be used in an expression wherever an int or
556 // unsigned int may be used:
557 // - an object or expression with an integer type whose integer
558 // conversion rank is less than or equal to the rank of int
559 // and unsigned int.
560 // - A bit-field of type _Bool, int, signed int, or unsigned int.
561 //
562 // If an int can represent all values of the original type, the
563 // value is converted to an int; otherwise, it is converted to an
564 // unsigned int. These are called the integer promotions. All
565 // other types are unchanged by the integer promotions.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000566
John McCallf3735e02010-12-01 04:43:34 +0000567 QualType PTy = Context.isPromotableBitField(E);
568 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000569 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
570 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000571 }
572 if (Ty->isPromotableIntegerType()) {
573 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000574 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
575 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000576 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000577 }
John Wiegley01296292011-04-08 18:41:53 +0000578 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000579}
580
Chris Lattner2ce500f2008-07-25 22:25:12 +0000581/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000582/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000583/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000584ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
585 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000586 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000587
John Wiegley01296292011-04-08 18:41:53 +0000588 ExprResult Res = UsualUnaryConversions(E);
589 if (Res.isInvalid())
590 return Owned(E);
591 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000592
Chris Lattner2ce500f2008-07-25 22:25:12 +0000593 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000594 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000595 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
596
John McCall4bb057d2011-08-27 22:06:17 +0000597 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall0562caa2011-08-29 23:55:37 +0000598 // promotion, even on class types, but note:
599 // C++11 [conv.lval]p2:
600 // When an lvalue-to-rvalue conversion occurs in an unevaluated
601 // operand or a subexpression thereof the value contained in the
602 // referenced object is not accessed. Otherwise, if the glvalue
603 // has a class type, the conversion copy-initializes a temporary
604 // of type T from the glvalue and the result of the conversion
605 // is a prvalue for the temporary.
Eli Friedman05e28012012-01-17 02:13:45 +0000606 // FIXME: add some way to gate this entire thing for correctness in
607 // potentially potentially evaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +0000608 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
Eli Friedman05e28012012-01-17 02:13:45 +0000609 ExprResult Temp = PerformCopyInitialization(
610 InitializedEntity::InitializeTemporary(E->getType()),
611 E->getExprLoc(),
612 Owned(E));
613 if (Temp.isInvalid())
614 return ExprError();
615 E = Temp.get();
John McCall29ad95b2011-08-27 01:09:30 +0000616 }
617
John Wiegley01296292011-04-08 18:41:53 +0000618 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000619}
620
Richard Smith55ce3522012-06-25 20:30:08 +0000621/// Determine the degree of POD-ness for an expression.
622/// Incomplete types are considered POD, since this check can be performed
623/// when we're in an unevaluated context.
624Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
Jordan Rose3e0ec582012-07-19 18:10:23 +0000625 if (Ty->isIncompleteType()) {
626 if (Ty->isObjCObjectType())
627 return VAK_Invalid;
Richard Smith55ce3522012-06-25 20:30:08 +0000628 return VAK_Valid;
Jordan Rose3e0ec582012-07-19 18:10:23 +0000629 }
630
631 if (Ty.isCXX98PODType(Context))
632 return VAK_Valid;
633
Richard Smith55ce3522012-06-25 20:30:08 +0000634 // C++0x [expr.call]p7:
635 // Passing a potentially-evaluated argument of class type (Clause 9)
636 // having a non-trivial copy constructor, a non-trivial move constructor,
637 // or a non-trivial destructor, with no corresponding parameter,
638 // is conditionally-supported with implementation-defined semantics.
Richard Smith55ce3522012-06-25 20:30:08 +0000639 if (getLangOpts().CPlusPlus0x && !Ty->isDependentType())
640 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
641 if (Record->hasTrivialCopyConstructor() &&
642 Record->hasTrivialMoveConstructor() &&
643 Record->hasTrivialDestructor())
644 return VAK_ValidInCXX11;
645
646 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
647 return VAK_Valid;
648 return VAK_Invalid;
649}
650
651bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
652 // Don't allow one to pass an Objective-C interface to a vararg.
653 const QualType & Ty = E->getType();
654
655 // Complain about passing non-POD types through varargs.
656 switch (isValidVarArgType(Ty)) {
657 case VAK_Valid:
658 break;
659 case VAK_ValidInCXX11:
660 DiagRuntimeBehavior(E->getLocStart(), 0,
661 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
662 << E->getType() << CT);
663 break;
Jordan Rose3e0ec582012-07-19 18:10:23 +0000664 case VAK_Invalid: {
665 if (Ty->isObjCObjectType())
666 return DiagRuntimeBehavior(E->getLocStart(), 0,
667 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
668 << Ty << CT);
669
Richard Smith55ce3522012-06-25 20:30:08 +0000670 return DiagRuntimeBehavior(E->getLocStart(), 0,
671 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
672 << getLangOpts().CPlusPlus0x << Ty << CT);
673 }
Jordan Rose3e0ec582012-07-19 18:10:23 +0000674 }
Richard Smith55ce3522012-06-25 20:30:08 +0000675 // c++ rules are enforced elsewhere.
676 return false;
677}
678
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000679/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
Jordan Rose3e0ec582012-07-19 18:10:23 +0000680/// will create a trap if the resulting type is not a POD type.
John Wiegley01296292011-04-08 18:41:53 +0000681ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000682 FunctionDecl *FDecl) {
Richard Smith7659b122012-06-27 20:29:39 +0000683 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
John McCall4124c492011-10-17 18:40:02 +0000684 // Strip the unbridged-cast placeholder expression off, if applicable.
685 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
686 (CT == VariadicMethod ||
687 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
688 E = stripARCUnbridgedCast(E);
689
690 // Otherwise, do normal placeholder checking.
691 } else {
692 ExprResult ExprRes = CheckPlaceholderExpr(E);
693 if (ExprRes.isInvalid())
694 return ExprError();
695 E = ExprRes.take();
696 }
697 }
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000698
John McCall4124c492011-10-17 18:40:02 +0000699 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000700 if (ExprRes.isInvalid())
701 return ExprError();
702 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000703
Richard Smith55ce3522012-06-25 20:30:08 +0000704 // Diagnostics regarding non-POD argument types are
705 // emitted along with format string checking in Sema::CheckFunctionCall().
Richard Smith56471fd2012-06-27 20:23:58 +0000706 if (isValidVarArgType(E->getType()) == VAK_Invalid) {
Richard Smith55ce3522012-06-25 20:30:08 +0000707 // Turn this into a trap.
708 CXXScopeSpec SS;
709 SourceLocation TemplateKWLoc;
710 UnqualifiedId Name;
711 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
712 E->getLocStart());
713 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
714 Name, true, false);
715 if (TrapFn.isInvalid())
716 return ExprError();
John McCall31168b02011-06-15 23:02:42 +0000717
Richard Smith55ce3522012-06-25 20:30:08 +0000718 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
719 E->getLocStart(), MultiExprArg(),
720 E->getLocEnd());
721 if (Call.isInvalid())
722 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000723
Richard Smith55ce3522012-06-25 20:30:08 +0000724 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
725 Call.get(), E);
726 if (Comma.isInvalid())
727 return ExprError();
728 return Comma.get();
Douglas Gregor253cadf2011-05-21 16:27:21 +0000729 }
Richard Smith55ce3522012-06-25 20:30:08 +0000730
David Blaikiebbafb8a2012-03-11 07:00:24 +0000731 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000732 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahanianbf482812012-03-02 17:05:03 +0000733 diag::err_call_incomplete_argument))
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000734 return ExprError();
Richard Smith55ce3522012-06-25 20:30:08 +0000735
John Wiegley01296292011-04-08 18:41:53 +0000736 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000737}
738
Richard Trieu7aa58f12011-09-02 20:58:51 +0000739/// \brief Converts an integer to complex float type. Helper function of
740/// UsualArithmeticConversions()
741///
742/// \return false if the integer expression is an integer type and is
743/// successfully converted to the complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000744static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
745 ExprResult &ComplexExpr,
746 QualType IntTy,
747 QualType ComplexTy,
748 bool SkipCast) {
749 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
750 if (SkipCast) return false;
751 if (IntTy->isIntegerType()) {
752 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
753 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
754 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000755 CK_FloatingRealToComplex);
756 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +0000757 assert(IntTy->isComplexIntegerType());
758 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000759 CK_IntegralComplexToFloatingComplex);
760 }
761 return false;
762}
763
764/// \brief Takes two complex float types and converts them to the same type.
765/// Helper function of UsualArithmeticConversions()
766static QualType
Richard Trieu5065cdd2011-09-06 18:25:09 +0000767handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
768 ExprResult &RHS, QualType LHSType,
769 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000770 bool IsCompAssign) {
Richard Trieu5065cdd2011-09-06 18:25:09 +0000771 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000772
773 if (order < 0) {
774 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000775 if (!IsCompAssign)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000776 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
777 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000778 }
779 if (order > 0)
780 // _Complex float -> _Complex double
Richard Trieu5065cdd2011-09-06 18:25:09 +0000781 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
782 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000783}
784
785/// \brief Converts otherExpr to complex float and promotes complexExpr if
786/// necessary. Helper function of UsualArithmeticConversions()
787static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuba63ce62011-09-09 01:45:06 +0000788 ExprResult &ComplexExpr,
789 ExprResult &OtherExpr,
790 QualType ComplexTy,
791 QualType OtherTy,
792 bool ConvertComplexExpr,
793 bool ConvertOtherExpr) {
794 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000795
796 // If just the complexExpr is complex, the otherExpr needs to be converted,
797 // and the complexExpr might need to be promoted.
798 if (order > 0) { // complexExpr is wider
799 // float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000800 if (ConvertOtherExpr) {
801 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
802 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
803 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000804 CK_FloatingRealToComplex);
805 }
Richard Trieuba63ce62011-09-09 01:45:06 +0000806 return ComplexTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000807 }
808
809 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000810 QualType result = (order == 0 ? ComplexTy :
811 S.Context.getComplexType(OtherTy));
Richard Trieu7aa58f12011-09-02 20:58:51 +0000812
813 // double -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000814 if (ConvertOtherExpr)
815 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000816 CK_FloatingRealToComplex);
817
818 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000819 if (ConvertComplexExpr && order < 0)
820 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000821 CK_FloatingComplexCast);
822
823 return result;
824}
825
826/// \brief Handle arithmetic conversion with complex types. Helper function of
827/// UsualArithmeticConversions()
Richard Trieu5065cdd2011-09-06 18:25:09 +0000828static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
829 ExprResult &RHS, QualType LHSType,
830 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000831 bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000832 // if we have an integer operand, the result is the complex type.
Richard Trieu5065cdd2011-09-06 18:25:09 +0000833 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000834 /*skipCast*/false))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000835 return LHSType;
836 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000837 /*skipCast*/IsCompAssign))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000838 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000839
840 // This handles complex/complex, complex/float, or float/complex.
841 // When both operands are complex, the shorter operand is converted to the
842 // type of the longer, and that is the type of the result. This corresponds
843 // to what is done when combining two real floating-point operands.
844 // The fun begins when size promotion occur across type domains.
845 // From H&S 6.3.4: When one operand is complex and the other is a real
846 // floating-point type, the less precise type is converted, within it's
847 // real or complex domain, to the precision of the other type. For example,
848 // when combining a "long double" with a "double _Complex", the
849 // "double _Complex" is promoted to "long double _Complex".
850
Richard Trieu5065cdd2011-09-06 18:25:09 +0000851 bool LHSComplexFloat = LHSType->isComplexType();
852 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000853
854 // If both are complex, just cast to the more precise type.
855 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000856 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
857 LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000858 IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000859
860 // If only one operand is complex, promote it if necessary and convert the
861 // other operand to complex.
862 if (LHSComplexFloat)
863 return handleOtherComplexFloatConversion(
Richard Trieuba63ce62011-09-09 01:45:06 +0000864 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000865 /*convertOtherExpr*/ true);
866
867 assert(RHSComplexFloat);
868 return handleOtherComplexFloatConversion(
Richard Trieu5065cdd2011-09-06 18:25:09 +0000869 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000870 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000871}
872
873/// \brief Hande arithmetic conversion from integer to float. Helper function
874/// of UsualArithmeticConversions()
Richard Trieuba63ce62011-09-09 01:45:06 +0000875static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
876 ExprResult &IntExpr,
877 QualType FloatTy, QualType IntTy,
878 bool ConvertFloat, bool ConvertInt) {
879 if (IntTy->isIntegerType()) {
880 if (ConvertInt)
Richard Trieu7aa58f12011-09-02 20:58:51 +0000881 // Convert intExpr to the lhs floating point type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000882 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000883 CK_IntegralToFloating);
Richard Trieuba63ce62011-09-09 01:45:06 +0000884 return FloatTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000885 }
886
887 // Convert both sides to the appropriate complex float.
Richard Trieuba63ce62011-09-09 01:45:06 +0000888 assert(IntTy->isComplexIntegerType());
889 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000890
891 // _Complex int -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000892 if (ConvertInt)
893 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000894 CK_IntegralComplexToFloatingComplex);
895
896 // float -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000897 if (ConvertFloat)
898 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000899 CK_FloatingRealToComplex);
900
901 return result;
902}
903
904/// \brief Handle arithmethic conversion with floating point types. Helper
905/// function of UsualArithmeticConversions()
Richard Trieucfe3f212011-09-06 18:38:41 +0000906static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
907 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000908 QualType RHSType, bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000909 bool LHSFloat = LHSType->isRealFloatingType();
910 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000911
912 // If we have two real floating types, convert the smaller operand
913 // to the bigger result.
914 if (LHSFloat && RHSFloat) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000915 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000916 if (order > 0) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000917 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
918 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000919 }
920
921 assert(order < 0 && "illegal float comparison");
Richard Trieuba63ce62011-09-09 01:45:06 +0000922 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000923 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
924 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000925 }
926
927 if (LHSFloat)
Richard Trieucfe3f212011-09-06 18:38:41 +0000928 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000929 /*convertFloat=*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000930 /*convertInt=*/ true);
931 assert(RHSFloat);
Richard Trieucfe3f212011-09-06 18:38:41 +0000932 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000933 /*convertInt=*/ true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000934 /*convertFloat=*/!IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000935}
936
937/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000938/// of UsualArithmeticConversions()
Richard Trieu7aa58f12011-09-02 20:58:51 +0000939// FIXME: if the operands are (int, _Complex long), we currently
940// don't promote the complex. Also, signedness?
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000941static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
942 ExprResult &RHS, QualType LHSType,
943 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000944 bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000945 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
946 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000947
Richard Trieucfe3f212011-09-06 18:38:41 +0000948 if (LHSComplexInt && RHSComplexInt) {
949 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
950 RHSComplexInt->getElementType());
Richard Trieu7aa58f12011-09-02 20:58:51 +0000951 assert(order && "inequal types with equal element ordering");
952 if (order > 0) {
953 // _Complex int -> _Complex long
Richard Trieucfe3f212011-09-06 18:38:41 +0000954 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
955 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000956 }
957
Richard Trieuba63ce62011-09-09 01:45:06 +0000958 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000959 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
960 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000961 }
962
Richard Trieucfe3f212011-09-06 18:38:41 +0000963 if (LHSComplexInt) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000964 // int -> _Complex int
Eli Friedman47133be2011-11-12 03:56:23 +0000965 // FIXME: This needs to take integer ranks into account
966 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
967 CK_IntegralCast);
Richard Trieucfe3f212011-09-06 18:38:41 +0000968 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
969 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000970 }
971
Richard Trieucfe3f212011-09-06 18:38:41 +0000972 assert(RHSComplexInt);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000973 // int -> _Complex int
Eli Friedman47133be2011-11-12 03:56:23 +0000974 // FIXME: This needs to take integer ranks into account
975 if (!IsCompAssign) {
976 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
977 CK_IntegralCast);
Richard Trieucfe3f212011-09-06 18:38:41 +0000978 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
Eli Friedman47133be2011-11-12 03:56:23 +0000979 }
Richard Trieucfe3f212011-09-06 18:38:41 +0000980 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000981}
982
983/// \brief Handle integer arithmetic conversions. Helper function of
984/// UsualArithmeticConversions()
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000985static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
986 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000987 QualType RHSType, bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000988 // The rules for this case are in C99 6.3.1.8
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000989 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
990 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
991 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
992 if (LHSSigned == RHSSigned) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000993 // Same signedness; use the higher-ranked type
994 if (order >= 0) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000995 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
996 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000997 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000998 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
999 return RHSType;
1000 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +00001001 // The unsigned type has greater than or equal rank to the
1002 // signed type, so use the unsigned type
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001003 if (RHSSigned) {
1004 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1005 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +00001006 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001007 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1008 return RHSType;
1009 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +00001010 // The two types are different widths; if we are here, that
1011 // means the signed type is larger than the unsigned type, so
1012 // use the signed type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001013 if (LHSSigned) {
1014 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1015 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +00001016 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001017 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1018 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +00001019 } else {
1020 // The signed type is higher-ranked than the unsigned type,
1021 // but isn't actually any bigger (like unsigned int and long
1022 // on most 32-bit systems). Use the unsigned type corresponding
1023 // to the signed type.
1024 QualType result =
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001025 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1026 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuba63ce62011-09-09 01:45:06 +00001027 if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001028 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu7aa58f12011-09-02 20:58:51 +00001029 return result;
1030 }
1031}
1032
Chris Lattner513165e2008-07-25 21:10:04 +00001033/// UsualArithmeticConversions - Performs various conversions that are common to
1034/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +00001035/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +00001036/// responsible for emitting appropriate error diagnostics.
1037/// FIXME: verify the conversion rules for "complex int" are consistent with
1038/// GCC.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001039QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00001040 bool IsCompAssign) {
1041 if (!IsCompAssign) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001042 LHS = UsualUnaryConversions(LHS.take());
1043 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001044 return QualType();
1045 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00001046
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001047 RHS = UsualUnaryConversions(RHS.take());
1048 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001049 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001050
Mike Stump11289f42009-09-09 15:08:12 +00001051 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +00001052 // For example, "const float" and "float" are equivalent.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001053 QualType LHSType =
1054 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1055 QualType RHSType =
1056 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001057
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001058 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1059 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1060 LHSType = AtomicLHS->getValueType();
1061
Douglas Gregora11693b2008-11-12 17:17:38 +00001062 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001063 if (LHSType == RHSType)
1064 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +00001065
1066 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1067 // The caller can deal with this (e.g. pointer + int).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001068 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001069 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001070
John McCalld005ac92010-11-13 08:17:45 +00001071 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001072 QualType LHSUnpromotedType = LHSType;
1073 if (LHSType->isPromotableIntegerType())
1074 LHSType = Context.getPromotedIntegerType(LHSType);
1075 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +00001076 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001077 LHSType = LHSBitfieldPromoteTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00001078 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001079 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +00001080
John McCalld005ac92010-11-13 08:17:45 +00001081 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001082 if (LHSType == RHSType)
1083 return LHSType;
John McCalld005ac92010-11-13 08:17:45 +00001084
1085 // At this point, we have two different arithmetic types.
1086
1087 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001088 if (LHSType->isComplexType() || RHSType->isComplexType())
1089 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001090 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001091
1092 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001093 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1094 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001095 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001096
1097 // Handle GCC complex int extension.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001098 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer499c68b2011-09-06 19:57:14 +00001099 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001100 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001101
1102 // Finally, we have two differing integer types.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001103 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001104 IsCompAssign);
Douglas Gregora11693b2008-11-12 17:17:38 +00001105}
1106
Chris Lattner513165e2008-07-25 21:10:04 +00001107//===----------------------------------------------------------------------===//
1108// Semantic Analysis for various Expression Types
1109//===----------------------------------------------------------------------===//
1110
1111
Peter Collingbourne91147592011-04-15 00:35:48 +00001112ExprResult
1113Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1114 SourceLocation DefaultLoc,
1115 SourceLocation RParenLoc,
1116 Expr *ControllingExpr,
Richard Trieuba63ce62011-09-09 01:45:06 +00001117 MultiTypeArg ArgTypes,
1118 MultiExprArg ArgExprs) {
1119 unsigned NumAssocs = ArgTypes.size();
1120 assert(NumAssocs == ArgExprs.size());
Peter Collingbourne91147592011-04-15 00:35:48 +00001121
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001122 ParsedType *ParsedTypes = ArgTypes.data();
1123 Expr **Exprs = ArgExprs.data();
Peter Collingbourne91147592011-04-15 00:35:48 +00001124
1125 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1126 for (unsigned i = 0; i < NumAssocs; ++i) {
1127 if (ParsedTypes[i])
1128 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1129 else
1130 Types[i] = 0;
1131 }
1132
1133 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1134 ControllingExpr, Types, Exprs,
1135 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +00001136 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +00001137 return ER;
1138}
1139
1140ExprResult
1141Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1142 SourceLocation DefaultLoc,
1143 SourceLocation RParenLoc,
1144 Expr *ControllingExpr,
1145 TypeSourceInfo **Types,
1146 Expr **Exprs,
1147 unsigned NumAssocs) {
1148 bool TypeErrorFound = false,
1149 IsResultDependent = ControllingExpr->isTypeDependent(),
1150 ContainsUnexpandedParameterPack
1151 = ControllingExpr->containsUnexpandedParameterPack();
1152
1153 for (unsigned i = 0; i < NumAssocs; ++i) {
1154 if (Exprs[i]->containsUnexpandedParameterPack())
1155 ContainsUnexpandedParameterPack = true;
1156
1157 if (Types[i]) {
1158 if (Types[i]->getType()->containsUnexpandedParameterPack())
1159 ContainsUnexpandedParameterPack = true;
1160
1161 if (Types[i]->getType()->isDependentType()) {
1162 IsResultDependent = true;
1163 } else {
Benjamin Kramere56f3932011-12-23 17:00:35 +00001164 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbourne91147592011-04-15 00:35:48 +00001165 // complete object type other than a variably modified type."
1166 unsigned D = 0;
1167 if (Types[i]->getType()->isIncompleteType())
1168 D = diag::err_assoc_type_incomplete;
1169 else if (!Types[i]->getType()->isObjectType())
1170 D = diag::err_assoc_type_nonobject;
1171 else if (Types[i]->getType()->isVariablyModifiedType())
1172 D = diag::err_assoc_type_variably_modified;
1173
1174 if (D != 0) {
1175 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1176 << Types[i]->getTypeLoc().getSourceRange()
1177 << Types[i]->getType();
1178 TypeErrorFound = true;
1179 }
1180
Benjamin Kramere56f3932011-12-23 17:00:35 +00001181 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbourne91147592011-04-15 00:35:48 +00001182 // selection shall specify compatible types."
1183 for (unsigned j = i+1; j < NumAssocs; ++j)
1184 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1185 Context.typesAreCompatible(Types[i]->getType(),
1186 Types[j]->getType())) {
1187 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1188 diag::err_assoc_compatible_types)
1189 << Types[j]->getTypeLoc().getSourceRange()
1190 << Types[j]->getType()
1191 << Types[i]->getType();
1192 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1193 diag::note_compat_assoc)
1194 << Types[i]->getTypeLoc().getSourceRange()
1195 << Types[i]->getType();
1196 TypeErrorFound = true;
1197 }
1198 }
1199 }
1200 }
1201 if (TypeErrorFound)
1202 return ExprError();
1203
1204 // If we determined that the generic selection is result-dependent, don't
1205 // try to compute the result expression.
1206 if (IsResultDependent)
1207 return Owned(new (Context) GenericSelectionExpr(
1208 Context, KeyLoc, ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001209 llvm::makeArrayRef(Types, NumAssocs),
1210 llvm::makeArrayRef(Exprs, NumAssocs),
1211 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
Peter Collingbourne91147592011-04-15 00:35:48 +00001212
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001213 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +00001214 unsigned DefaultIndex = -1U;
1215 for (unsigned i = 0; i < NumAssocs; ++i) {
1216 if (!Types[i])
1217 DefaultIndex = i;
1218 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1219 Types[i]->getType()))
1220 CompatIndices.push_back(i);
1221 }
1222
Benjamin Kramere56f3932011-12-23 17:00:35 +00001223 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbourne91147592011-04-15 00:35:48 +00001224 // type compatible with at most one of the types named in its generic
1225 // association list."
1226 if (CompatIndices.size() > 1) {
1227 // We strip parens here because the controlling expression is typically
1228 // parenthesized in macro definitions.
1229 ControllingExpr = ControllingExpr->IgnoreParens();
1230 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1231 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1232 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001233 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +00001234 E = CompatIndices.end(); I != E; ++I) {
1235 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1236 diag::note_compat_assoc)
1237 << Types[*I]->getTypeLoc().getSourceRange()
1238 << Types[*I]->getType();
1239 }
1240 return ExprError();
1241 }
1242
Benjamin Kramere56f3932011-12-23 17:00:35 +00001243 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbourne91147592011-04-15 00:35:48 +00001244 // its controlling expression shall have type compatible with exactly one of
1245 // the types named in its generic association list."
1246 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1247 // We strip parens here because the controlling expression is typically
1248 // parenthesized in macro definitions.
1249 ControllingExpr = ControllingExpr->IgnoreParens();
1250 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1251 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1252 return ExprError();
1253 }
1254
Benjamin Kramere56f3932011-12-23 17:00:35 +00001255 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbourne91147592011-04-15 00:35:48 +00001256 // type name that is compatible with the type of the controlling expression,
1257 // then the result expression of the generic selection is the expression
1258 // in that generic association. Otherwise, the result expression of the
1259 // generic selection is the expression in the default generic association."
1260 unsigned ResultIndex =
1261 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1262
1263 return Owned(new (Context) GenericSelectionExpr(
1264 Context, KeyLoc, ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001265 llvm::makeArrayRef(Types, NumAssocs),
1266 llvm::makeArrayRef(Exprs, NumAssocs),
1267 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
Peter Collingbourne91147592011-04-15 00:35:48 +00001268 ResultIndex));
1269}
1270
Richard Smith75b67d62012-03-08 01:34:56 +00001271/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1272/// location of the token and the offset of the ud-suffix within it.
1273static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1274 unsigned Offset) {
1275 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001276 S.getLangOpts());
Richard Smith75b67d62012-03-08 01:34:56 +00001277}
1278
Richard Smithbcc22fc2012-03-09 08:00:36 +00001279/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1280/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1281static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1282 IdentifierInfo *UDSuffix,
1283 SourceLocation UDSuffixLoc,
1284 ArrayRef<Expr*> Args,
1285 SourceLocation LitEndLoc) {
1286 assert(Args.size() <= 2 && "too many arguments for literal operator");
1287
1288 QualType ArgTy[2];
1289 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1290 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1291 if (ArgTy[ArgIdx]->isArrayType())
1292 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1293 }
1294
1295 DeclarationName OpName =
1296 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1297 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1298 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1299
1300 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1301 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1302 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1303 return ExprError();
1304
1305 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1306}
1307
Steve Naroff83895f72007-09-16 03:34:24 +00001308/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001309/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1310/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1311/// multiple tokens. However, the common case is that StringToks points to one
1312/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001313///
John McCalldadc5752010-08-24 06:29:42 +00001314ExprResult
Richard Smithbcc22fc2012-03-09 08:00:36 +00001315Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1316 Scope *UDLScope) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001317 assert(NumStringToks && "Must have at least one string!");
1318
Chris Lattner8a24e582009-01-16 18:51:42 +00001319 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001320 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001321 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001322
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001323 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001324 for (unsigned i = 0; i != NumStringToks; ++i)
1325 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001326
Chris Lattner36fc8792008-02-11 00:02:17 +00001327 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001328 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001329 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001330 else if (Literal.isUTF16())
1331 StrTy = Context.Char16Ty;
1332 else if (Literal.isUTF32())
1333 StrTy = Context.Char32Ty;
Eli Friedmanfcec6302011-11-01 02:23:42 +00001334 else if (Literal.isPascal())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001335 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001336
Douglas Gregorfb65e592011-07-27 05:40:30 +00001337 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1338 if (Literal.isWide())
1339 Kind = StringLiteral::Wide;
1340 else if (Literal.isUTF8())
1341 Kind = StringLiteral::UTF8;
1342 else if (Literal.isUTF16())
1343 Kind = StringLiteral::UTF16;
1344 else if (Literal.isUTF32())
1345 Kind = StringLiteral::UTF32;
1346
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001347 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001348 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001349 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001350
Chris Lattner36fc8792008-02-11 00:02:17 +00001351 // Get an array type for the string, according to C99 6.4.5. This includes
1352 // the nul terminator character as well as the string length for pascal
1353 // strings.
1354 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001355 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001356 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001357
Chris Lattner5b183d82006-11-10 05:03:26 +00001358 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smithc67fdd42012-03-07 08:35:16 +00001359 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1360 Kind, Literal.Pascal, StrTy,
1361 &StringTokLocs[0],
1362 StringTokLocs.size());
1363 if (Literal.getUDSuffix().empty())
1364 return Owned(Lit);
1365
1366 // We're building a user-defined literal.
1367 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smith75b67d62012-03-08 01:34:56 +00001368 SourceLocation UDSuffixLoc =
1369 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1370 Literal.getUDSuffixOffset());
Richard Smithc67fdd42012-03-07 08:35:16 +00001371
Richard Smithbcc22fc2012-03-09 08:00:36 +00001372 // Make sure we're allowed user-defined literals here.
1373 if (!UDLScope)
1374 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1375
Richard Smithc67fdd42012-03-07 08:35:16 +00001376 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1377 // operator "" X (str, len)
1378 QualType SizeType = Context.getSizeType();
1379 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1380 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1381 StringTokLocs[0]);
1382 Expr *Args[] = { Lit, LenArg };
Richard Smithbcc22fc2012-03-09 08:00:36 +00001383 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1384 Args, StringTokLocs.back());
Chris Lattner5b183d82006-11-10 05:03:26 +00001385}
1386
John McCalldadc5752010-08-24 06:29:42 +00001387ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001388Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001389 SourceLocation Loc,
1390 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001391 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001392 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001393}
1394
John McCallf4cd4f92011-02-09 01:13:10 +00001395/// BuildDeclRefExpr - Build an expression that references a
1396/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001397ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001398Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001399 const DeclarationNameInfo &NameInfo,
1400 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001401 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00001402 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1403 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1404 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1405 CalleeTarget = IdentifyCUDATarget(Callee);
1406 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1407 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1408 << CalleeTarget << D->getIdentifier() << CallerTarget;
1409 Diag(D->getLocation(), diag::note_previous_decl)
1410 << D->getIdentifier();
1411 return ExprError();
1412 }
1413 }
1414
John McCall113bee02012-03-10 09:33:50 +00001415 bool refersToEnclosingScope =
1416 (CurContext != D->getDeclContext() &&
1417 D->getDeclContext()->isFunctionOrMethod());
1418
Eli Friedmanfa0df832012-02-02 03:46:19 +00001419 DeclRefExpr *E = DeclRefExpr::Create(Context,
1420 SS ? SS->getWithLocInContext(Context)
1421 : NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00001422 SourceLocation(),
1423 D, refersToEnclosingScope,
1424 NameInfo, Ty, VK);
Mike Stump11289f42009-09-09 15:08:12 +00001425
Eli Friedmanfa0df832012-02-02 03:46:19 +00001426 MarkDeclRefReferenced(E);
John McCall086a4642010-11-24 05:12:34 +00001427
Jordan Rose657b5f42012-09-28 22:21:35 +00001428 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1429 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1430 DiagnosticsEngine::Level Level =
1431 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1432 E->getLocStart());
1433 if (Level != DiagnosticsEngine::Ignored)
1434 getCurFunction()->recordUseOfWeak(E);
1435 }
1436
John McCall086a4642010-11-24 05:12:34 +00001437 // Just in case we're building an illegal pointer-to-member.
Richard Smithcaf33902011-10-10 18:28:20 +00001438 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1439 if (FD && FD->isBitField())
John McCall086a4642010-11-24 05:12:34 +00001440 E->setObjectKind(OK_BitField);
1441
1442 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001443}
1444
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001445/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001446/// possibly a list of template arguments.
1447///
1448/// If this produces template arguments, it is permitted to call
1449/// DecomposeTemplateName.
1450///
1451/// This actually loses a lot of source location information for
1452/// non-standard name kinds; we should consider preserving that in
1453/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001454void
1455Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1456 TemplateArgumentListInfo &Buffer,
1457 DeclarationNameInfo &NameInfo,
1458 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001459 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1460 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1461 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1462
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001463 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
John McCall10eae182009-11-30 22:42:35 +00001464 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001465 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001466
John McCall3e56fd42010-08-23 07:28:44 +00001467 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001468 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001469 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001470 TemplateArgs = &Buffer;
1471 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001472 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001473 TemplateArgs = 0;
1474 }
1475}
1476
John McCalld681c392009-12-16 08:11:27 +00001477/// Diagnose an empty lookup.
1478///
1479/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001480bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001481 CorrectionCandidateCallback &CCC,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001482 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001483 llvm::ArrayRef<Expr *> Args) {
John McCalld681c392009-12-16 08:11:27 +00001484 DeclarationName Name = R.getLookupName();
1485
John McCalld681c392009-12-16 08:11:27 +00001486 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001487 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001488 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1489 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001490 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001491 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001492 diagnostic_suggest = diag::err_undeclared_use_suggest;
1493 }
John McCalld681c392009-12-16 08:11:27 +00001494
Douglas Gregor598b08f2009-12-31 05:20:13 +00001495 // If the original lookup was an unqualified lookup, fake an
1496 // unqualified lookup. This is useful when (for example) the
1497 // original lookup would not have found something because it was a
1498 // dependent name.
David Blaikiec4c0e8a2012-05-28 01:26:45 +00001499 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1500 ? CurContext : 0;
Francois Pichetde232cb2011-11-25 01:10:54 +00001501 while (DC) {
John McCalld681c392009-12-16 08:11:27 +00001502 if (isa<CXXRecordDecl>(DC)) {
1503 LookupQualifiedName(R, DC);
1504
1505 if (!R.empty()) {
1506 // Don't give errors about ambiguities in this lookup.
1507 R.suppressDiagnostics();
1508
Francois Pichet857f9d62011-11-17 03:44:24 +00001509 // During a default argument instantiation the CurContext points
1510 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1511 // function parameter list, hence add an explicit check.
1512 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1513 ActiveTemplateInstantiations.back().Kind ==
1514 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCalld681c392009-12-16 08:11:27 +00001515 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1516 bool isInstance = CurMethod &&
1517 CurMethod->isInstance() &&
Francois Pichet857f9d62011-11-17 03:44:24 +00001518 DC == CurMethod->getParent() && !isDefaultArgument;
1519
John McCalld681c392009-12-16 08:11:27 +00001520
1521 // Give a code modification hint to insert 'this->'.
1522 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1523 // Actually quite difficult!
Nico Weberdf7dffb2012-06-20 20:21:42 +00001524 if (getLangOpts().MicrosoftMode)
1525 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001526 if (isInstance) {
Nico Weber3c10fb12012-06-22 16:39:39 +00001527 Diag(R.getNameLoc(), diagnostic) << Name
1528 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001529 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1530 CallsUndergoingInstantiation.back()->getCallee());
Nico Weber3c10fb12012-06-22 16:39:39 +00001531
1532
1533 CXXMethodDecl *DepMethod;
1534 if (CurMethod->getTemplatedKind() ==
1535 FunctionDecl::TK_FunctionTemplateSpecialization)
1536 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1537 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1538 else
1539 DepMethod = cast<CXXMethodDecl>(
1540 CurMethod->getInstantiatedFromMemberFunction());
1541 assert(DepMethod && "No template pattern found");
1542
1543 QualType DepThisType = DepMethod->getThisType(Context);
1544 CheckCXXThisCapture(R.getNameLoc());
1545 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1546 R.getNameLoc(), DepThisType, false);
1547 TemplateArgumentListInfo TList;
1548 if (ULE->hasExplicitTemplateArgs())
1549 ULE->copyTemplateArgumentsInto(TList);
1550
1551 CXXScopeSpec SS;
1552 SS.Adopt(ULE->getQualifierLoc());
1553 CXXDependentScopeMemberExpr *DepExpr =
1554 CXXDependentScopeMemberExpr::Create(
1555 Context, DepThis, DepThisType, true, SourceLocation(),
1556 SS.getWithLocInContext(Context),
1557 ULE->getTemplateKeywordLoc(), 0,
1558 R.getLookupNameInfo(),
1559 ULE->hasExplicitTemplateArgs() ? &TList : 0);
1560 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001561 } else {
John McCalld681c392009-12-16 08:11:27 +00001562 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001563 }
John McCalld681c392009-12-16 08:11:27 +00001564
1565 // Do we really want to note all of these?
1566 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1567 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1568
Francois Pichet857f9d62011-11-17 03:44:24 +00001569 // Return true if we are inside a default argument instantiation
1570 // and the found name refers to an instance member function, otherwise
1571 // the function calling DiagnoseEmptyLookup will try to create an
1572 // implicit member call and this is wrong for default argument.
1573 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1574 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1575 return true;
1576 }
1577
John McCalld681c392009-12-16 08:11:27 +00001578 // Tell the callee to try to recover.
1579 return false;
1580 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001581
1582 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001583 }
Francois Pichetde232cb2011-11-25 01:10:54 +00001584
1585 // In Microsoft mode, if we are performing lookup from within a friend
1586 // function definition declared at class scope then we must set
1587 // DC to the lexical parent to be able to search into the parent
1588 // class.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001589 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetde232cb2011-11-25 01:10:54 +00001590 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1591 DC->getLexicalParent()->isRecord())
1592 DC = DC->getLexicalParent();
1593 else
1594 DC = DC->getParent();
John McCalld681c392009-12-16 08:11:27 +00001595 }
1596
Douglas Gregor598b08f2009-12-31 05:20:13 +00001597 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001598 TypoCorrection Corrected;
1599 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001600 S, &SS, CCC))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001601 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1602 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001603 R.setLookupName(Corrected.getCorrection());
1604
Hans Wennborg38198de2011-07-12 08:45:31 +00001605 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001606 if (Corrected.isOverloaded()) {
1607 OverloadCandidateSet OCS(R.getNameLoc());
1608 OverloadCandidateSet::iterator Best;
1609 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1610 CDEnd = Corrected.end();
1611 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001612 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001613 dyn_cast<FunctionTemplateDecl>(*CD))
1614 AddTemplateOverloadCandidate(
1615 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001616 Args, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001617 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1618 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1619 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001620 Args, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001621 }
1622 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1623 case OR_Success:
1624 ND = Best->Function;
1625 break;
1626 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001627 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001628 }
1629 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001630 R.addDecl(ND);
1631 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001632 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001633 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1634 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001635 else
1636 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001637 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001638 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001639 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1640 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001641 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001642 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001643
1644 // Tell the callee to try to recover.
1645 return false;
1646 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001647
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001648 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001649 // FIXME: If we ended up with a typo for a type name or
1650 // Objective-C class name, we're in trouble because the parser
1651 // is in the wrong place to recover. Suggest the typo
1652 // correction, but don't make it a fix-it since we're not going
1653 // to recover well anyway.
1654 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001655 Diag(R.getNameLoc(), diagnostic_suggest)
1656 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001657 else
1658 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001659 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001660 << SS.getRange();
1661
1662 // Don't try to recover; it won't work.
1663 return true;
1664 }
1665 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001666 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001667 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001668 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001669 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001670 else
Douglas Gregor25363982010-01-01 00:15:04 +00001671 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001672 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001673 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001674 return true;
1675 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001676 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001677 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001678
1679 // Emit a special diagnostic for failed member lookups.
1680 // FIXME: computing the declaration context might fail here (?)
1681 if (!SS.isEmpty()) {
1682 Diag(R.getNameLoc(), diag::err_no_member)
1683 << Name << computeDeclContext(SS, false)
1684 << SS.getRange();
1685 return true;
1686 }
1687
John McCalld681c392009-12-16 08:11:27 +00001688 // Give up, we can't recover.
1689 Diag(R.getNameLoc(), diagnostic) << Name;
1690 return true;
1691}
1692
John McCalldadc5752010-08-24 06:29:42 +00001693ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001694 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001695 SourceLocation TemplateKWLoc,
John McCall24d18942010-08-24 22:52:39 +00001696 UnqualifiedId &Id,
1697 bool HasTrailingLParen,
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001698 bool IsAddressOfOperand,
1699 CorrectionCandidateCallback *CCC) {
Richard Trieuba63ce62011-09-09 01:45:06 +00001700 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCalle66edc12009-11-24 19:00:30 +00001701 "cannot be direct & operand and have a trailing lparen");
1702
1703 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001704 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001705
John McCall10eae182009-11-30 22:42:35 +00001706 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001707
1708 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001709 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001710 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001711 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001712
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001713 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001714 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001715 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001716
John McCalle66edc12009-11-24 19:00:30 +00001717 // C++ [temp.dep.expr]p3:
1718 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001719 // -- an identifier that was declared with a dependent type,
1720 // (note: handled after lookup)
1721 // -- a template-id that is dependent,
1722 // (note: handled in BuildTemplateIdExpr)
1723 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001724 // -- a nested-name-specifier that contains a class-name that
1725 // names a dependent type.
1726 // Determine whether this is a member of an unknown specialization;
1727 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001728 bool DependentID = false;
1729 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1730 Name.getCXXNameType()->isDependentType()) {
1731 DependentID = true;
1732 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001733 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001734 if (RequireCompleteDeclContext(SS, DC))
1735 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001736 } else {
1737 DependentID = true;
1738 }
1739 }
1740
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001741 if (DependentID)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001742 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1743 IsAddressOfOperand, TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001744
John McCalle66edc12009-11-24 19:00:30 +00001745 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001746 LookupResult R(*this, NameInfo,
1747 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1748 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001749 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001750 // Lookup the template name again to correctly establish the context in
1751 // which it was found. This is really unfortunate as we already did the
1752 // lookup to determine that it was a template name in the first place. If
1753 // this becomes a performance hit, we can work harder to preserve those
1754 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001755 bool MemberOfUnknownSpecialization;
1756 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1757 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001758
1759 if (MemberOfUnknownSpecialization ||
1760 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001761 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1762 IsAddressOfOperand, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001763 } else {
Benjamin Kramer46921442012-01-20 14:57:34 +00001764 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001765 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001766
Douglas Gregora5226932011-02-04 13:35:07 +00001767 // If the result might be in a dependent base class, this is a dependent
1768 // id-expression.
1769 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001770 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1771 IsAddressOfOperand, TemplateArgs);
1772
John McCalle66edc12009-11-24 19:00:30 +00001773 // If this reference is in an Objective-C method, then we need to do
1774 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001775 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001776 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001777 if (E.isInvalid())
1778 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001779
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001780 if (Expr *Ex = E.takeAs<Expr>())
1781 return Owned(Ex);
Steve Naroffebf4cb42008-06-02 23:03:37 +00001782 }
Chris Lattner59a25942008-03-31 00:36:02 +00001783 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001784
John McCalle66edc12009-11-24 19:00:30 +00001785 if (R.isAmbiguous())
1786 return ExprError();
1787
Douglas Gregor171c45a2009-02-18 21:56:37 +00001788 // Determine whether this name might be a candidate for
1789 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001790 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001791
John McCalle66edc12009-11-24 19:00:30 +00001792 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001793 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001794 // in C90, extension in C99, forbidden in C++).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001795 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
John McCalle66edc12009-11-24 19:00:30 +00001796 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1797 if (D) R.addDecl(D);
1798 }
1799
1800 // If this name wasn't predeclared and if this is not a function
1801 // call, diagnose the problem.
1802 if (R.empty()) {
Francois Pichetd8e4e412011-09-24 10:38:05 +00001803
1804 // In Microsoft mode, if we are inside a template class member function
1805 // and we can't resolve an identifier then assume the identifier is type
1806 // dependent. The goal is to postpone name lookup to instantiation time
1807 // to be able to search into type dependent base classes.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001808 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetd8e4e412011-09-24 10:38:05 +00001809 isa<CXXMethodDecl>(CurContext))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001810 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1811 IsAddressOfOperand, TemplateArgs);
Francois Pichetd8e4e412011-09-24 10:38:05 +00001812
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001813 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001814 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCalld681c392009-12-16 08:11:27 +00001815 return ExprError();
1816
1817 assert(!R.empty() &&
1818 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001819
1820 // If we found an Objective-C instance variable, let
1821 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001822 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001823 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1824 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001825 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanian44653702011-09-23 23:11:38 +00001826 // In a hopelessly buggy code, Objective-C instance variable
1827 // lookup fails and no expression will be built to reference it.
1828 if (!E.isInvalid() && !E.get())
1829 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001830 return E;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001831 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001832 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001833 }
Mike Stump11289f42009-09-09 15:08:12 +00001834
John McCalle66edc12009-11-24 19:00:30 +00001835 // This is guaranteed from this point on.
1836 assert(!R.empty() || ADL);
1837
John McCall2d74de92009-12-01 22:10:20 +00001838 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001839 // C++ [class.mfct.non-static]p3:
1840 // When an id-expression that is not part of a class member access
1841 // syntax and not used to form a pointer to member is used in the
1842 // body of a non-static member function of class X, if name lookup
1843 // resolves the name in the id-expression to a non-static non-type
1844 // member of some class C, the id-expression is transformed into a
1845 // class member access expression using (*this) as the
1846 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001847 //
1848 // But we don't actually need to do this for '&' operands if R
1849 // resolved to a function or overloaded function set, because the
1850 // expression is ill-formed if it actually works out to be a
1851 // non-static member function:
1852 //
1853 // C++ [expr.ref]p4:
1854 // Otherwise, if E1.E2 refers to a non-static member function. . .
1855 // [t]he expression can be used only as the left-hand operand of a
1856 // member function call.
1857 //
1858 // There are other safeguards against such uses, but it's important
1859 // to get this right here so that we don't end up making a
1860 // spuriously dependent expression if we're inside a dependent
1861 // instance method.
John McCall57500772009-12-16 12:17:52 +00001862 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001863 bool MightBeImplicitMember;
Richard Trieuba63ce62011-09-09 01:45:06 +00001864 if (!IsAddressOfOperand)
John McCall8d08b9b2010-08-27 09:08:28 +00001865 MightBeImplicitMember = true;
1866 else if (!SS.isEmpty())
1867 MightBeImplicitMember = false;
1868 else if (R.isOverloadedResult())
1869 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001870 else if (R.isUnresolvableResult())
1871 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001872 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001873 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1874 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001875
1876 if (MightBeImplicitMember)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001877 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1878 R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001879 }
1880
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001881 if (TemplateArgs || TemplateKWLoc.isValid())
1882 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001883
John McCalle66edc12009-11-24 19:00:30 +00001884 return BuildDeclarationNameExpr(SS, R, ADL);
1885}
1886
John McCall10eae182009-11-30 22:42:35 +00001887/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1888/// declaration name, generally during template instantiation.
1889/// There's a large number of things which don't need to be done along
1890/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001891ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001892Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001893 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001894 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001895 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001896 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1897 NameInfo, /*TemplateArgs=*/0);
John McCalle66edc12009-11-24 19:00:30 +00001898
John McCall0b66eb32010-05-01 00:40:08 +00001899 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001900 return ExprError();
1901
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001902 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001903 LookupQualifiedName(R, DC);
1904
1905 if (R.isAmbiguous())
1906 return ExprError();
1907
1908 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001909 Diag(NameInfo.getLoc(), diag::err_no_member)
1910 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001911 return ExprError();
1912 }
1913
1914 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1915}
1916
1917/// LookupInObjCMethod - The parser has read a name in, and Sema has
1918/// detected that we're currently inside an ObjC method. Perform some
1919/// additional lookup.
1920///
1921/// Ideally, most of this would be done by lookup, but there's
1922/// actually quite a lot of extra work involved.
1923///
1924/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001925ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001926Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001927 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001928 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001929 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001930
John McCalle66edc12009-11-24 19:00:30 +00001931 // There are two cases to handle here. 1) scoped lookup could have failed,
1932 // in which case we should look for an ivar. 2) scoped lookup could have
1933 // found a decl, but that decl is outside the current instance method (i.e.
1934 // a global variable). In these two cases, we do a lookup for an ivar with
1935 // this name, if the lookup sucedes, we replace it our current decl.
1936
1937 // If we're in a class method, we don't normally want to look for
1938 // ivars. But if we don't find anything else, and there's an
1939 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001940 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001941
1942 bool LookForIvars;
1943 if (Lookup.empty())
1944 LookForIvars = true;
1945 else if (IsClassMethod)
1946 LookForIvars = false;
1947 else
1948 LookForIvars = (Lookup.isSingleResult() &&
1949 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001950 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001951 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001952 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001953 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis4e8b1362011-10-19 02:25:16 +00001954 ObjCIvarDecl *IV = 0;
1955 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCalle66edc12009-11-24 19:00:30 +00001956 // Diagnose using an ivar in a class method.
1957 if (IsClassMethod)
1958 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1959 << IV->getDeclName());
1960
1961 // If we're referencing an invalid decl, just return this as a silent
1962 // error node. The error diagnostic was already emitted on the decl.
1963 if (IV->isInvalidDecl())
1964 return ExprError();
1965
1966 // Check if referencing a field with __attribute__((deprecated)).
1967 if (DiagnoseUseOfDecl(IV, Loc))
1968 return ExprError();
1969
1970 // Diagnose the use of an ivar outside of the declaring class.
1971 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001972 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001973 !getLangOpts().DebuggerSupport)
John McCalle66edc12009-11-24 19:00:30 +00001974 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1975
1976 // FIXME: This should use a new expr for a direct reference, don't
1977 // turn this into Self->ivar, just return a BareIVarExpr or something.
1978 IdentifierInfo &II = Context.Idents.get("self");
1979 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001980 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001981 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001982 CXXScopeSpec SelfScopeSpec;
Abramo Bagnara7945c982012-01-27 09:46:47 +00001983 SourceLocation TemplateKWLoc;
1984 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001985 SelfName, false, false);
1986 if (SelfExpr.isInvalid())
1987 return ExprError();
1988
John Wiegley01296292011-04-08 18:41:53 +00001989 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1990 if (SelfExpr.isInvalid())
1991 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001992
Eli Friedmanfa0df832012-02-02 03:46:19 +00001993 MarkAnyDeclReferenced(Loc, IV);
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00001994
1995 ObjCMethodFamily MF = CurMethod->getMethodFamily();
1996 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize)
1997 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
Jordan Rose657b5f42012-09-28 22:21:35 +00001998
1999 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2000 Loc,
2001 SelfExpr.take(),
2002 true, true);
2003
2004 if (getLangOpts().ObjCAutoRefCount) {
2005 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2006 DiagnosticsEngine::Level Level =
2007 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2008 if (Level != DiagnosticsEngine::Ignored)
2009 getCurFunction()->recordUseOfWeak(Result);
2010 }
2011 }
2012
2013 return Owned(Result);
John McCalle66edc12009-11-24 19:00:30 +00002014 }
Chris Lattner87313662010-04-12 05:10:17 +00002015 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00002016 // We should warn if a local variable hides an ivar.
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00002017 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2018 ObjCInterfaceDecl *ClassDeclared;
2019 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2020 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor0b144e12011-12-15 00:29:59 +00002021 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00002022 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2023 }
John McCalle66edc12009-11-24 19:00:30 +00002024 }
Fariborz Jahanian028b9e12011-12-20 22:21:08 +00002025 } else if (Lookup.isSingleResult() &&
2026 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2027 // If accessing a stand-alone ivar in a class method, this is an error.
2028 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2029 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2030 << IV->getDeclName());
John McCalle66edc12009-11-24 19:00:30 +00002031 }
2032
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002033 if (Lookup.empty() && II && AllowBuiltinCreation) {
2034 // FIXME. Consolidate this with similar code in LookupName.
2035 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002036 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002037 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2038 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2039 S, Lookup.isForRedeclaration(),
2040 Lookup.getNameLoc());
2041 if (D) Lookup.addDecl(D);
2042 }
2043 }
2044 }
John McCalle66edc12009-11-24 19:00:30 +00002045 // Sentinel value saying that we didn't do anything special.
2046 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00002047}
John McCalld14a8642009-11-21 08:51:07 +00002048
John McCall16df1e52010-03-30 21:47:33 +00002049/// \brief Cast a base object to a member's actual type.
2050///
2051/// Logically this happens in three phases:
2052///
2053/// * First we cast from the base type to the naming class.
2054/// The naming class is the class into which we were looking
2055/// when we found the member; it's the qualifier type if a
2056/// qualifier was provided, and otherwise it's the base type.
2057///
2058/// * Next we cast from the naming class to the declaring class.
2059/// If the member we found was brought into a class's scope by
2060/// a using declaration, this is that class; otherwise it's
2061/// the class declaring the member.
2062///
2063/// * Finally we cast from the declaring class to the "true"
2064/// declaring class of the member. This conversion does not
2065/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00002066ExprResult
2067Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002068 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002069 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002070 NamedDecl *Member) {
2071 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2072 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00002073 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002074
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002075 QualType DestRecordType;
2076 QualType DestType;
2077 QualType FromRecordType;
2078 QualType FromType = From->getType();
2079 bool PointerConversions = false;
2080 if (isa<FieldDecl>(Member)) {
2081 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002082
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002083 if (FromType->getAs<PointerType>()) {
2084 DestType = Context.getPointerType(DestRecordType);
2085 FromRecordType = FromType->getPointeeType();
2086 PointerConversions = true;
2087 } else {
2088 DestType = DestRecordType;
2089 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002090 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002091 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2092 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00002093 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002094
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002095 DestType = Method->getThisType(Context);
2096 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002097
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002098 if (FromType->getAs<PointerType>()) {
2099 FromRecordType = FromType->getPointeeType();
2100 PointerConversions = true;
2101 } else {
2102 FromRecordType = FromType;
2103 DestType = DestRecordType;
2104 }
2105 } else {
2106 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00002107 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002108 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002109
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002110 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00002111 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002112
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002113 // If the unqualified types are the same, no conversion is necessary.
2114 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002115 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002116
John McCall16df1e52010-03-30 21:47:33 +00002117 SourceRange FromRange = From->getSourceRange();
2118 SourceLocation FromLoc = FromRange.getBegin();
2119
Eli Friedmanbe4b3632011-09-27 21:58:52 +00002120 ExprValueKind VK = From->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002121
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002122 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002123 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002124 // class name.
2125 //
2126 // If the member was a qualified name and the qualified referred to a
2127 // specific base subobject type, we'll cast to that intermediate type
2128 // first and then to the object in which the member is declared. That allows
2129 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2130 //
2131 // class Base { public: int x; };
2132 // class Derived1 : public Base { };
2133 // class Derived2 : public Base { };
2134 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2135 //
2136 // void VeryDerived::f() {
2137 // x = 17; // error: ambiguous base subobjects
2138 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2139 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002140 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002141 QualType QType = QualType(Qualifier->getAsType(), 0);
2142 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2143 assert(QType->isRecordType() && "lookup done with non-record type");
2144
2145 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2146
2147 // In C++98, the qualifier type doesn't actually have to be a base
2148 // type of the object type, in which case we just ignore it.
2149 // Otherwise build the appropriate casts.
2150 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002151 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002152 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002153 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002154 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002155
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002156 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002157 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002158 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2159 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002160
2161 FromType = QType;
2162 FromRecordType = QRecordType;
2163
2164 // If the qualifier type was the same as the destination type,
2165 // we're done.
2166 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002167 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002168 }
2169 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002170
John McCall16df1e52010-03-30 21:47:33 +00002171 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002172
John McCall16df1e52010-03-30 21:47:33 +00002173 // If we actually found the member through a using declaration, cast
2174 // down to the using declaration's type.
2175 //
2176 // Pointer equality is fine here because only one declaration of a
2177 // class ever has member declarations.
2178 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2179 assert(isa<UsingShadowDecl>(FoundDecl));
2180 QualType URecordType = Context.getTypeDeclType(
2181 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2182
2183 // We only need to do this if the naming-class to declaring-class
2184 // conversion is non-trivial.
2185 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2186 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002187 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002188 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002189 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002190 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002191
John McCall16df1e52010-03-30 21:47:33 +00002192 QualType UType = URecordType;
2193 if (PointerConversions)
2194 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002195 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2196 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002197 FromType = UType;
2198 FromRecordType = URecordType;
2199 }
2200
2201 // We don't do access control for the conversion from the
2202 // declaring class to the true declaring class.
2203 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002204 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002205
John McCallcf142162010-08-07 06:22:56 +00002206 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002207 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2208 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002209 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002210 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002211
John Wiegley01296292011-04-08 18:41:53 +00002212 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2213 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002214}
Douglas Gregor3256d042009-06-30 15:47:41 +00002215
John McCalle66edc12009-11-24 19:00:30 +00002216bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002217 const LookupResult &R,
2218 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002219 // Only when used directly as the postfix-expression of a call.
2220 if (!HasTrailingLParen)
2221 return false;
2222
2223 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002224 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002225 return false;
2226
2227 // Only in C++ or ObjC++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002228 if (!getLangOpts().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002229 return false;
2230
2231 // Turn off ADL when we find certain kinds of declarations during
2232 // normal lookup:
2233 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2234 NamedDecl *D = *I;
2235
2236 // C++0x [basic.lookup.argdep]p3:
2237 // -- a declaration of a class member
2238 // Since using decls preserve this property, we check this on the
2239 // original decl.
John McCall57500772009-12-16 12:17:52 +00002240 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002241 return false;
2242
2243 // C++0x [basic.lookup.argdep]p3:
2244 // -- a block-scope function declaration that is not a
2245 // using-declaration
2246 // NOTE: we also trigger this for function templates (in fact, we
2247 // don't check the decl type at all, since all other decl types
2248 // turn off ADL anyway).
2249 if (isa<UsingShadowDecl>(D))
2250 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2251 else if (D->getDeclContext()->isFunctionOrMethod())
2252 return false;
2253
2254 // C++0x [basic.lookup.argdep]p3:
2255 // -- a declaration that is neither a function or a function
2256 // template
2257 // And also for builtin functions.
2258 if (isa<FunctionDecl>(D)) {
2259 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2260
2261 // But also builtin functions.
2262 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2263 return false;
2264 } else if (!isa<FunctionTemplateDecl>(D))
2265 return false;
2266 }
2267
2268 return true;
2269}
2270
2271
John McCalld14a8642009-11-21 08:51:07 +00002272/// Diagnoses obvious problems with the use of the given declaration
2273/// as an expression. This is only actually called for lookups that
2274/// were not overloaded, and it doesn't promise that the declaration
2275/// will in fact be used.
2276static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002277 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002278 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2279 return true;
2280 }
2281
2282 if (isa<ObjCInterfaceDecl>(D)) {
2283 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2284 return true;
2285 }
2286
2287 if (isa<NamespaceDecl>(D)) {
2288 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2289 return true;
2290 }
2291
2292 return false;
2293}
2294
John McCalldadc5752010-08-24 06:29:42 +00002295ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002296Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002297 LookupResult &R,
2298 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002299 // If this is a single, fully-resolved result and we don't need ADL,
2300 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002301 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002302 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2303 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002304
2305 // We only need to check the declaration if there's exactly one
2306 // result, because in the overloaded case the results can only be
2307 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002308 if (R.isSingleResult() &&
2309 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002310 return ExprError();
2311
John McCall58cc69d2010-01-27 01:50:18 +00002312 // Otherwise, just build an unresolved lookup expression. Suppress
2313 // any lookup-related diagnostics; we'll hash these out later, when
2314 // we've picked a target.
2315 R.suppressDiagnostics();
2316
John McCalld14a8642009-11-21 08:51:07 +00002317 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002318 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002319 SS.getWithLocInContext(Context),
2320 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002321 NeedsADL, R.isOverloadedResult(),
2322 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002323
2324 return Owned(ULE);
2325}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002326
John McCalld14a8642009-11-21 08:51:07 +00002327/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002328ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002329Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002330 const DeclarationNameInfo &NameInfo,
2331 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002332 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002333 assert(!isa<FunctionTemplateDecl>(D) &&
2334 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002335
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002336 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002337 if (CheckDeclInExpr(*this, Loc, D))
2338 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002339
Douglas Gregore7488b92009-12-01 16:58:18 +00002340 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2341 // Specifically diagnose references to class templates that are missing
2342 // a template argument list.
2343 Diag(Loc, diag::err_template_decl_ref)
2344 << Template << SS.getRange();
2345 Diag(Template->getLocation(), diag::note_template_decl_here);
2346 return ExprError();
2347 }
2348
2349 // Make sure that we're referring to a value.
2350 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2351 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002352 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002353 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002354 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002355 return ExprError();
2356 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002357
Douglas Gregor171c45a2009-02-18 21:56:37 +00002358 // Check whether this declaration can be used. Note that we suppress
2359 // this check when we're going to perform argument-dependent lookup
2360 // on this function name, because this might not be the function
2361 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002362 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002363 return ExprError();
2364
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002365 // Only create DeclRefExpr's for valid Decl's.
2366 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002367 return ExprError();
2368
John McCallf3a88602011-02-03 08:15:49 +00002369 // Handle members of anonymous structs and unions. If we got here,
2370 // and the reference is to a class member indirect field, then this
2371 // must be the subject of a pointer-to-member expression.
2372 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2373 if (!indirectField->isCXXClassMember())
2374 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2375 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002376
Eli Friedman9bb33f52012-02-03 02:04:35 +00002377 {
John McCallf4cd4f92011-02-09 01:13:10 +00002378 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002379 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002380
2381 switch (D->getKind()) {
2382 // Ignore all the non-ValueDecl kinds.
2383#define ABSTRACT_DECL(kind)
2384#define VALUE(type, base)
2385#define DECL(type, base) \
2386 case Decl::type:
2387#include "clang/AST/DeclNodes.inc"
2388 llvm_unreachable("invalid value decl kind");
John McCallf4cd4f92011-02-09 01:13:10 +00002389
2390 // These shouldn't make it here.
2391 case Decl::ObjCAtDefsField:
2392 case Decl::ObjCIvar:
2393 llvm_unreachable("forming non-member reference to ivar?");
John McCallf4cd4f92011-02-09 01:13:10 +00002394
2395 // Enum constants are always r-values and never references.
2396 // Unresolved using declarations are dependent.
2397 case Decl::EnumConstant:
2398 case Decl::UnresolvedUsingValue:
2399 valueKind = VK_RValue;
2400 break;
2401
2402 // Fields and indirect fields that got here must be for
2403 // pointer-to-member expressions; we just call them l-values for
2404 // internal consistency, because this subexpression doesn't really
2405 // exist in the high-level semantics.
2406 case Decl::Field:
2407 case Decl::IndirectField:
David Blaikiebbafb8a2012-03-11 07:00:24 +00002408 assert(getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002409 "building reference to field in C?");
2410
2411 // These can't have reference type in well-formed programs, but
2412 // for internal consistency we do this anyway.
2413 type = type.getNonReferenceType();
2414 valueKind = VK_LValue;
2415 break;
2416
2417 // Non-type template parameters are either l-values or r-values
2418 // depending on the type.
2419 case Decl::NonTypeTemplateParm: {
2420 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2421 type = reftype->getPointeeType();
2422 valueKind = VK_LValue; // even if the parameter is an r-value reference
2423 break;
2424 }
2425
2426 // For non-references, we need to strip qualifiers just in case
2427 // the template parameter was declared as 'const int' or whatever.
2428 valueKind = VK_RValue;
2429 type = type.getUnqualifiedType();
2430 break;
2431 }
2432
2433 case Decl::Var:
2434 // In C, "extern void blah;" is valid and is an r-value.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002435 if (!getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002436 !type.hasQualifiers() &&
2437 type->isVoidType()) {
2438 valueKind = VK_RValue;
2439 break;
2440 }
2441 // fallthrough
2442
2443 case Decl::ImplicitParam:
Douglas Gregor812d8f62012-02-18 05:51:20 +00002444 case Decl::ParmVar: {
John McCallf4cd4f92011-02-09 01:13:10 +00002445 // These are always l-values.
2446 valueKind = VK_LValue;
2447 type = type.getNonReferenceType();
Eli Friedman9bb33f52012-02-03 02:04:35 +00002448
Douglas Gregor812d8f62012-02-18 05:51:20 +00002449 // FIXME: Does the addition of const really only apply in
2450 // potentially-evaluated contexts? Since the variable isn't actually
2451 // captured in an unevaluated context, it seems that the answer is no.
David Blaikie131fcb42012-08-06 22:47:24 +00002452 if (!isUnevaluatedContext()) {
Douglas Gregor812d8f62012-02-18 05:51:20 +00002453 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2454 if (!CapturedType.isNull())
2455 type = CapturedType;
2456 }
2457
John McCallf4cd4f92011-02-09 01:13:10 +00002458 break;
Douglas Gregor812d8f62012-02-18 05:51:20 +00002459 }
2460
John McCallf4cd4f92011-02-09 01:13:10 +00002461 case Decl::Function: {
Eli Friedman34866c72012-08-31 00:14:07 +00002462 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2463 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2464 type = Context.BuiltinFnTy;
2465 valueKind = VK_RValue;
2466 break;
2467 }
2468 }
2469
John McCall2979fe02011-04-12 00:42:48 +00002470 const FunctionType *fty = type->castAs<FunctionType>();
2471
2472 // If we're referring to a function with an __unknown_anytype
2473 // result type, make the entire expression __unknown_anytype.
2474 if (fty->getResultType() == Context.UnknownAnyTy) {
2475 type = Context.UnknownAnyTy;
2476 valueKind = VK_RValue;
2477 break;
2478 }
2479
John McCallf4cd4f92011-02-09 01:13:10 +00002480 // Functions are l-values in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002481 if (getLangOpts().CPlusPlus) {
John McCallf4cd4f92011-02-09 01:13:10 +00002482 valueKind = VK_LValue;
2483 break;
2484 }
2485
2486 // C99 DR 316 says that, if a function type comes from a
2487 // function definition (without a prototype), that type is only
2488 // used for checking compatibility. Therefore, when referencing
2489 // the function, we pretend that we don't have the full function
2490 // type.
John McCall2979fe02011-04-12 00:42:48 +00002491 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2492 isa<FunctionProtoType>(fty))
2493 type = Context.getFunctionNoProtoType(fty->getResultType(),
2494 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002495
2496 // Functions are r-values in C.
2497 valueKind = VK_RValue;
2498 break;
2499 }
2500
2501 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002502 // If we're referring to a method with an __unknown_anytype
2503 // result type, make the entire expression __unknown_anytype.
2504 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002505 if (const FunctionProtoType *proto
2506 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002507 if (proto->getResultType() == Context.UnknownAnyTy) {
2508 type = Context.UnknownAnyTy;
2509 valueKind = VK_RValue;
2510 break;
2511 }
2512
John McCallf4cd4f92011-02-09 01:13:10 +00002513 // C++ methods are l-values if static, r-values if non-static.
2514 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2515 valueKind = VK_LValue;
2516 break;
2517 }
2518 // fallthrough
2519
2520 case Decl::CXXConversion:
2521 case Decl::CXXDestructor:
2522 case Decl::CXXConstructor:
2523 valueKind = VK_RValue;
2524 break;
2525 }
2526
2527 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2528 }
Chris Lattner17ed4872006-11-20 04:58:19 +00002529}
Chris Lattnere168f762006-11-10 05:29:30 +00002530
John McCall2979fe02011-04-12 00:42:48 +00002531ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002532 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002533
Chris Lattnere168f762006-11-10 05:29:30 +00002534 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002535 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002536 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2537 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
Nico Weber3a691a32012-06-23 02:07:59 +00002538 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
Chris Lattner6307f192008-08-10 01:53:14 +00002539 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002540 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002541
Chris Lattnera81a0272008-01-12 08:14:25 +00002542 // Pre-defined identifiers are of type char[x], where x is the length of the
2543 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002544
Anders Carlsson2fb08242009-09-08 18:24:21 +00002545 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002546 if (!currentDecl && getCurBlock())
2547 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002548 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002549 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002550 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002551 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002552
Anders Carlsson0b209a82009-09-11 01:22:35 +00002553 QualType ResTy;
2554 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2555 ResTy = Context.DependentTy;
2556 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002557 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002558
Anders Carlsson0b209a82009-09-11 01:22:35 +00002559 llvm::APInt LengthI(32, Length + 1);
Nico Weber3052abd2012-06-29 16:39:58 +00002560 if (IT == PredefinedExpr::LFunction)
Nico Weber3a691a32012-06-23 02:07:59 +00002561 ResTy = Context.WCharTy.withConst();
2562 else
2563 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002564 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2565 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002566 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002567}
2568
Richard Smithbcc22fc2012-03-09 08:00:36 +00002569ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002570 SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002571 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002572 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002573 if (Invalid)
2574 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002575
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002576 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002577 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002578 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002579 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002580
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002581 QualType Ty;
Seth Cantrell02f86052012-01-18 12:27:06 +00002582 if (Literal.isWide())
2583 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002584 else if (Literal.isUTF16())
Seth Cantrell02f86052012-01-18 12:27:06 +00002585 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002586 else if (Literal.isUTF32())
Seth Cantrell02f86052012-01-18 12:27:06 +00002587 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002588 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell02f86052012-01-18 12:27:06 +00002589 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002590 else
2591 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002592
Douglas Gregorfb65e592011-07-27 05:40:30 +00002593 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2594 if (Literal.isWide())
2595 Kind = CharacterLiteral::Wide;
2596 else if (Literal.isUTF16())
2597 Kind = CharacterLiteral::UTF16;
2598 else if (Literal.isUTF32())
2599 Kind = CharacterLiteral::UTF32;
2600
Richard Smith75b67d62012-03-08 01:34:56 +00002601 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2602 Tok.getLocation());
2603
2604 if (Literal.getUDSuffix().empty())
2605 return Owned(Lit);
2606
2607 // We're building a user-defined literal.
2608 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2609 SourceLocation UDSuffixLoc =
2610 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2611
Richard Smithbcc22fc2012-03-09 08:00:36 +00002612 // Make sure we're allowed user-defined literals here.
2613 if (!UDLScope)
2614 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2615
Richard Smith75b67d62012-03-08 01:34:56 +00002616 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2617 // operator "" X (ch)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002618 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2619 llvm::makeArrayRef(&Lit, 1),
2620 Tok.getLocation());
Steve Naroffae4143e2007-04-26 20:39:23 +00002621}
2622
Ted Kremeneke65b0862012-03-06 20:05:56 +00002623ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2624 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2625 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2626 Context.IntTy, Loc));
2627}
2628
Richard Smith39570d002012-03-08 08:45:32 +00002629static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2630 QualType Ty, SourceLocation Loc) {
2631 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2632
2633 using llvm::APFloat;
2634 APFloat Val(Format);
2635
2636 APFloat::opStatus result = Literal.GetFloatValue(Val);
2637
2638 // Overflow is always an error, but underflow is only an error if
2639 // we underflowed to zero (APFloat reports denormals as underflow).
2640 if ((result & APFloat::opOverflow) ||
2641 ((result & APFloat::opUnderflow) && Val.isZero())) {
2642 unsigned diagnostic;
2643 SmallString<20> buffer;
2644 if (result & APFloat::opOverflow) {
2645 diagnostic = diag::warn_float_overflow;
2646 APFloat::getLargest(Format).toString(buffer);
2647 } else {
2648 diagnostic = diag::warn_float_underflow;
2649 APFloat::getSmallest(Format).toString(buffer);
2650 }
2651
2652 S.Diag(Loc, diagnostic)
2653 << Ty
2654 << StringRef(buffer.data(), buffer.size());
2655 }
2656
2657 bool isExact = (result == APFloat::opOK);
2658 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2659}
2660
Richard Smithbcc22fc2012-03-09 08:00:36 +00002661ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002662 // Fast path for a single digit (which is quite common). A single digit
Richard Smithbcc22fc2012-03-09 08:00:36 +00002663 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Steve Narofff2fb89e2007-03-13 20:29:44 +00002664 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002665 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002666 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Steve Narofff2fb89e2007-03-13 20:29:44 +00002667 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002668
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002669 SmallString<128> SpellingBuffer;
2670 // NumericLiteralParser wants to overread by one character. Add padding to
2671 // the buffer in case the token is copied to the buffer. If getSpelling()
2672 // returns a StringRef to the memory buffer, it should have a null char at
2673 // the EOF, so it is also safe.
2674 SpellingBuffer.resize(Tok.getLength() + 1);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002675
Chris Lattner67ca9252007-05-21 01:08:44 +00002676 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002677 bool Invalid = false;
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002678 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002679 if (Invalid)
2680 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002681
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002682 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002683 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002684 return ExprError();
2685
Richard Smith39570d002012-03-08 08:45:32 +00002686 if (Literal.hasUDSuffix()) {
2687 // We're building a user-defined literal.
2688 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2689 SourceLocation UDSuffixLoc =
2690 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2691
Richard Smithbcc22fc2012-03-09 08:00:36 +00002692 // Make sure we're allowed user-defined literals here.
2693 if (!UDLScope)
2694 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smith39570d002012-03-08 08:45:32 +00002695
Richard Smithbcc22fc2012-03-09 08:00:36 +00002696 QualType CookedTy;
Richard Smith39570d002012-03-08 08:45:32 +00002697 if (Literal.isFloatingLiteral()) {
2698 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2699 // long double, the literal is treated as a call of the form
2700 // operator "" X (f L)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002701 CookedTy = Context.LongDoubleTy;
Richard Smith39570d002012-03-08 08:45:32 +00002702 } else {
2703 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2704 // unsigned long long, the literal is treated as a call of the form
2705 // operator "" X (n ULL)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002706 CookedTy = Context.UnsignedLongLongTy;
Richard Smith39570d002012-03-08 08:45:32 +00002707 }
2708
Richard Smithbcc22fc2012-03-09 08:00:36 +00002709 DeclarationName OpName =
2710 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2711 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2712 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2713
2714 // Perform literal operator lookup to determine if we're building a raw
2715 // literal or a cooked one.
2716 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2717 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2718 /*AllowRawAndTemplate*/true)) {
2719 case LOLR_Error:
2720 return ExprError();
2721
2722 case LOLR_Cooked: {
2723 Expr *Lit;
2724 if (Literal.isFloatingLiteral()) {
2725 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2726 } else {
2727 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2728 if (Literal.GetIntegerValue(ResultVal))
2729 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2730 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2731 Tok.getLocation());
2732 }
2733 return BuildLiteralOperatorCall(R, OpNameInfo,
2734 llvm::makeArrayRef(&Lit, 1),
2735 Tok.getLocation());
2736 }
2737
2738 case LOLR_Raw: {
2739 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2740 // literal is treated as a call of the form
2741 // operator "" X ("n")
2742 SourceLocation TokLoc = Tok.getLocation();
2743 unsigned Length = Literal.getUDSuffixOffset();
2744 QualType StrTy = Context.getConstantArrayType(
2745 Context.CharTy, llvm::APInt(32, Length + 1),
2746 ArrayType::Normal, 0);
2747 Expr *Lit = StringLiteral::Create(
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002748 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
Richard Smithbcc22fc2012-03-09 08:00:36 +00002749 /*Pascal*/false, StrTy, &TokLoc, 1);
2750 return BuildLiteralOperatorCall(R, OpNameInfo,
2751 llvm::makeArrayRef(&Lit, 1), TokLoc);
2752 }
2753
2754 case LOLR_Template:
2755 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2756 // template), L is treated as a call fo the form
2757 // operator "" X <'c1', 'c2', ... 'ck'>()
2758 // where n is the source character sequence c1 c2 ... ck.
2759 TemplateArgumentListInfo ExplicitArgs;
2760 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2761 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2762 llvm::APSInt Value(CharBits, CharIsUnsigned);
2763 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002764 Value = TokSpelling[I];
Benjamin Kramer6003ad52012-06-07 15:09:51 +00002765 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smithbcc22fc2012-03-09 08:00:36 +00002766 TemplateArgumentLocInfo ArgInfo;
2767 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2768 }
2769 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2770 Tok.getLocation(), &ExplicitArgs);
2771 }
2772
2773 llvm_unreachable("unexpected literal operator lookup result");
Richard Smith39570d002012-03-08 08:45:32 +00002774 }
2775
Chris Lattner1c20a172007-08-26 03:42:43 +00002776 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002777
Chris Lattner1c20a172007-08-26 03:42:43 +00002778 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002779 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002780 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002781 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002782 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002783 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002784 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002785 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002786
Richard Smith39570d002012-03-08 08:45:32 +00002787 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002788
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002789 if (Ty == Context.DoubleTy) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002790 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002791 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002792 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002793 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002794 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002795 }
2796 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002797 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002798 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002799 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002800 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002801
Dmitri Gribenko1cd23052012-09-24 18:19:21 +00002802 // 'long long' is a C99 or C++11 feature.
2803 if (!getLangOpts().C99 && Literal.isLongLong) {
2804 if (getLangOpts().CPlusPlus)
2805 Diag(Tok.getLocation(),
2806 getLangOpts().CPlusPlus0x ?
2807 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
2808 else
2809 Diag(Tok.getLocation(), diag::ext_c99_longlong);
2810 }
Neil Boothac582c52007-08-29 22:00:19 +00002811
Chris Lattner67ca9252007-05-21 01:08:44 +00002812 // Get the value in the widest-possible width.
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002813 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2814 // The microsoft literal suffix extensions support 128-bit literals, which
2815 // may be wider than [u]intmax_t.
2816 if (Literal.isMicrosoftInteger && MaxWidth < 128)
2817 MaxWidth = 128;
2818 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002819
Chris Lattner67ca9252007-05-21 01:08:44 +00002820 if (Literal.GetIntegerValue(ResultVal)) {
2821 // If this value didn't fit into uintmax_t, warn and force to ull.
2822 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002823 Ty = Context.UnsignedLongLongTy;
2824 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002825 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002826 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002827 // If this value fits into a ULL, try to figure out what else it fits into
2828 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002829
Chris Lattner67ca9252007-05-21 01:08:44 +00002830 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2831 // be an unsigned int.
2832 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2833
2834 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002835 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002836 if (!Literal.isLong && !Literal.isLongLong) {
2837 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00002838 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002839
Chris Lattner67ca9252007-05-21 01:08:44 +00002840 // Does it fit in a unsigned int?
2841 if (ResultVal.isIntN(IntSize)) {
2842 // Does it fit in a signed int?
2843 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002844 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002845 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002846 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002847 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002848 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002849 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002850
Chris Lattner67ca9252007-05-21 01:08:44 +00002851 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002852 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002853 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002854
Chris Lattner67ca9252007-05-21 01:08:44 +00002855 // Does it fit in a unsigned long?
2856 if (ResultVal.isIntN(LongSize)) {
2857 // Does it fit in a signed long?
2858 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002859 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002860 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002861 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002862 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002863 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002864 }
2865
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002866 // Check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002867 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002868 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002869
Chris Lattner67ca9252007-05-21 01:08:44 +00002870 // Does it fit in a unsigned long long?
2871 if (ResultVal.isIntN(LongLongSize)) {
2872 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002873 // To be compatible with MSVC, hex integer literals ending with the
2874 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002875 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00002876 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002877 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002878 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002879 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002880 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002881 }
2882 }
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002883
2884 // If it doesn't fit in unsigned long long, and we're using Microsoft
2885 // extensions, then its a 128-bit integer literal.
2886 if (Ty.isNull() && Literal.isMicrosoftInteger) {
2887 if (Literal.isUnsigned)
2888 Ty = Context.UnsignedInt128Ty;
2889 else
2890 Ty = Context.Int128Ty;
2891 Width = 128;
2892 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002893
Chris Lattner67ca9252007-05-21 01:08:44 +00002894 // If we still couldn't decide a type, we probably have something that
2895 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002896 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002897 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002898 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00002899 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002900 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002901
Chris Lattner55258cf2008-05-09 05:59:00 +00002902 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002903 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002904 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002905 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002906 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002907
Chris Lattner1c20a172007-08-26 03:42:43 +00002908 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2909 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002910 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002911 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002912
2913 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002914}
2915
Richard Trieuba63ce62011-09-09 01:45:06 +00002916ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002917 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002918 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002919}
2920
Chandler Carruth62da79c2011-05-26 08:53:12 +00002921static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2922 SourceLocation Loc,
2923 SourceRange ArgRange) {
2924 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2925 // scalar or vector data type argument..."
2926 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2927 // type (C99 6.2.5p18) or void.
2928 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2929 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2930 << T << ArgRange;
2931 return true;
2932 }
2933
2934 assert((T->isVoidType() || !T->isIncompleteType()) &&
2935 "Scalar types should always be complete");
2936 return false;
2937}
2938
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002939static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2940 SourceLocation Loc,
2941 SourceRange ArgRange,
2942 UnaryExprOrTypeTrait TraitKind) {
2943 // C99 6.5.3.4p1:
2944 if (T->isFunctionType()) {
2945 // alignof(function) is allowed as an extension.
2946 if (TraitKind == UETT_SizeOf)
2947 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2948 return false;
2949 }
2950
2951 // Allow sizeof(void)/alignof(void) as an extension.
2952 if (T->isVoidType()) {
2953 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2954 return false;
2955 }
2956
2957 return true;
2958}
2959
2960static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2961 SourceLocation Loc,
2962 SourceRange ArgRange,
2963 UnaryExprOrTypeTrait TraitKind) {
John McCallf2538342012-07-31 05:14:30 +00002964 // Reject sizeof(interface) and sizeof(interface<proto>) if the
2965 // runtime doesn't allow it.
2966 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002967 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2968 << T << (TraitKind == UETT_SizeOf)
2969 << ArgRange;
2970 return true;
2971 }
2972
2973 return false;
2974}
2975
Chandler Carruth14502c22011-05-26 08:53:10 +00002976/// \brief Check the constrains on expression operands to unary type expression
2977/// and type traits.
2978///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002979/// Completes any types necessary and validates the constraints on the operand
2980/// expression. The logic mostly mirrors the type-based overload, but may modify
2981/// the expression as it completes the type for that expression through template
2982/// instantiation, etc.
Richard Trieuba63ce62011-09-09 01:45:06 +00002983bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth14502c22011-05-26 08:53:10 +00002984 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002985 QualType ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002986
2987 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2988 // the result is the size of the referenced type."
2989 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2990 // result shall be the alignment of the referenced type."
2991 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2992 ExprTy = Ref->getPointeeType();
2993
2994 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002995 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2996 E->getSourceRange());
Chandler Carruth7c430c02011-05-27 01:33:31 +00002997
2998 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002999 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3000 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00003001 return false;
3002
Richard Trieuba63ce62011-09-09 01:45:06 +00003003 if (RequireCompleteExprType(E,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003004 diag::err_sizeof_alignof_incomplete_type,
3005 ExprKind, E->getSourceRange()))
Chandler Carruth7c430c02011-05-27 01:33:31 +00003006 return true;
3007
3008 // Completeing the expression's type may have changed it.
Richard Trieuba63ce62011-09-09 01:45:06 +00003009 ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00003010 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3011 ExprTy = Ref->getPointeeType();
3012
Richard Trieuba63ce62011-09-09 01:45:06 +00003013 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3014 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00003015 return true;
3016
Nico Weber0870deb2011-06-15 02:47:03 +00003017 if (ExprKind == UETT_SizeOf) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003018 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Weber0870deb2011-06-15 02:47:03 +00003019 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3020 QualType OType = PVD->getOriginalType();
3021 QualType Type = PVD->getType();
3022 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003023 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Weber0870deb2011-06-15 02:47:03 +00003024 << Type << OType;
3025 Diag(PVD->getLocation(), diag::note_declared_at);
3026 }
3027 }
3028 }
3029 }
3030
Chandler Carruth7c430c02011-05-27 01:33:31 +00003031 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00003032}
3033
3034/// \brief Check the constraints on operands to unary expression and type
3035/// traits.
3036///
3037/// This will complete any types necessary, and validate the various constraints
3038/// on those operands.
3039///
Steve Naroff71b59a92007-06-04 22:22:31 +00003040/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00003041/// C99 6.3.2.1p[2-4] all state:
3042/// Except when it is the operand of the sizeof operator ...
3043///
3044/// C++ [expr.sizeof]p4
3045/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3046/// standard conversions are not applied to the operand of sizeof.
3047///
3048/// This policy is followed for all of the unary trait expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00003049bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00003050 SourceLocation OpLoc,
3051 SourceRange ExprRange,
3052 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003053 if (ExprType->isDependentType())
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003054 return false;
3055
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003056 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3057 // the result is the size of the referenced type."
3058 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3059 // result shall be the alignment of the referenced type."
Richard Trieuba63ce62011-09-09 01:45:06 +00003060 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3061 ExprType = Ref->getPointeeType();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003062
Chandler Carruth62da79c2011-05-26 08:53:12 +00003063 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00003064 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003065
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003066 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00003067 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003068 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00003069 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003070
Richard Trieuba63ce62011-09-09 01:45:06 +00003071 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003072 diag::err_sizeof_alignof_incomplete_type,
3073 ExprKind, ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00003074 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003075
Richard Trieuba63ce62011-09-09 01:45:06 +00003076 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003077 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00003078 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003079
Chris Lattner62975a72009-04-24 00:30:45 +00003080 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00003081}
3082
Chandler Carruth14502c22011-05-26 08:53:10 +00003083static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00003084 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003085
Mike Stump11289f42009-09-09 15:08:12 +00003086 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00003087 if (isa<DeclRefExpr>(E))
3088 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003089
3090 // Cannot know anything else if the expression is dependent.
3091 if (E->isTypeDependent())
3092 return false;
3093
Douglas Gregor71235ec2009-05-02 02:18:30 +00003094 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003095 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3096 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003097 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00003098 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00003099
3100 // Alignment of a field access is always okay, so long as it isn't a
3101 // bit-field.
3102 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00003103 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003104 return false;
3105
Chandler Carruth14502c22011-05-26 08:53:10 +00003106 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003107}
3108
Chandler Carruth14502c22011-05-26 08:53:10 +00003109bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00003110 E = E->IgnoreParens();
3111
3112 // Cannot know anything else if the expression is dependent.
3113 if (E->isTypeDependent())
3114 return false;
3115
Chandler Carruth14502c22011-05-26 08:53:10 +00003116 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00003117}
3118
Douglas Gregor0950e412009-03-13 21:01:28 +00003119/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00003120ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003121Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3122 SourceLocation OpLoc,
3123 UnaryExprOrTypeTrait ExprKind,
3124 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00003125 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00003126 return ExprError();
3127
John McCallbcd03502009-12-07 02:54:59 +00003128 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00003129
Douglas Gregor0950e412009-03-13 21:01:28 +00003130 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00003131 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00003132 return ExprError();
3133
3134 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003135 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3136 Context.getSizeType(),
3137 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003138}
3139
3140/// \brief Build a sizeof or alignof expression given an expression
3141/// operand.
John McCalldadc5752010-08-24 06:29:42 +00003142ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00003143Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3144 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00003145 ExprResult PE = CheckPlaceholderExpr(E);
3146 if (PE.isInvalid())
3147 return ExprError();
3148
3149 E = PE.get();
3150
Douglas Gregor0950e412009-03-13 21:01:28 +00003151 // Verify that the operand is valid.
3152 bool isInvalid = false;
3153 if (E->isTypeDependent()) {
3154 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003155 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003156 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003157 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003158 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00003159 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00003160 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00003161 isInvalid = true;
3162 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00003163 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00003164 }
3165
3166 if (isInvalid)
3167 return ExprError();
3168
Eli Friedmane0afc982012-01-21 01:01:51 +00003169 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3170 PE = TranformToPotentiallyEvaluated(E);
3171 if (PE.isInvalid()) return ExprError();
3172 E = PE.take();
3173 }
3174
Douglas Gregor0950e412009-03-13 21:01:28 +00003175 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00003176 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00003177 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00003178 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003179}
3180
Peter Collingbournee190dee2011-03-11 19:24:49 +00003181/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3182/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00003183/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00003184ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003185Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003186 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00003187 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00003188 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003189 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00003190
Richard Trieuba63ce62011-09-09 01:45:06 +00003191 if (IsType) {
John McCallbcd03502009-12-07 02:54:59 +00003192 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00003193 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003194 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00003195 }
Sebastian Redl6f282892008-11-11 17:56:53 +00003196
Douglas Gregor0950e412009-03-13 21:01:28 +00003197 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00003198 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003199 return Result;
Chris Lattnere168f762006-11-10 05:29:30 +00003200}
3201
John Wiegley01296292011-04-08 18:41:53 +00003202static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003203 bool IsReal) {
John Wiegley01296292011-04-08 18:41:53 +00003204 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00003205 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00003206
John McCall34376a62010-12-04 03:47:34 +00003207 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00003208 if (V.get()->getObjectKind() != OK_Ordinary) {
3209 V = S.DefaultLvalueConversion(V.take());
3210 if (V.isInvalid())
3211 return QualType();
3212 }
John McCall34376a62010-12-04 03:47:34 +00003213
Chris Lattnere267f5d2007-08-26 05:39:26 +00003214 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00003215 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00003216 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00003217
Chris Lattnere267f5d2007-08-26 05:39:26 +00003218 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00003219 if (V.get()->getType()->isArithmeticType())
3220 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003221
John McCall36226622010-10-12 02:09:17 +00003222 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00003223 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00003224 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003225 if (PR.get() != V.get()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003226 V = PR;
Richard Trieuba63ce62011-09-09 01:45:06 +00003227 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall36226622010-10-12 02:09:17 +00003228 }
3229
Chris Lattnere267f5d2007-08-26 05:39:26 +00003230 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00003231 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuba63ce62011-09-09 01:45:06 +00003232 << (IsReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00003233 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00003234}
3235
3236
Chris Lattnere168f762006-11-10 05:29:30 +00003237
John McCalldadc5752010-08-24 06:29:42 +00003238ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003239Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003240 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00003241 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00003242 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003243 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003244 case tok::plusplus: Opc = UO_PostInc; break;
3245 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003246 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003247
Sebastian Redla9351792012-02-11 23:51:47 +00003248 // Since this might is a postfix expression, get rid of ParenListExprs.
3249 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3250 if (Result.isInvalid()) return ExprError();
3251 Input = Result.take();
3252
John McCallb268a282010-08-23 23:25:46 +00003253 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003254}
3255
John McCallf2538342012-07-31 05:14:30 +00003256/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3257///
3258/// \return true on error
3259static bool checkArithmeticOnObjCPointer(Sema &S,
3260 SourceLocation opLoc,
3261 Expr *op) {
3262 assert(op->getType()->isObjCObjectPointerType());
3263 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3264 return false;
3265
3266 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3267 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3268 << op->getSourceRange();
3269 return true;
3270}
3271
John McCalldadc5752010-08-24 06:29:42 +00003272ExprResult
John McCallb268a282010-08-23 23:25:46 +00003273Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3274 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003275 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003276 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003277 if (Result.isInvalid()) return ExprError();
3278 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003279
John McCallb268a282010-08-23 23:25:46 +00003280 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003281
David Blaikiebbafb8a2012-03-11 07:00:24 +00003282 if (getLangOpts().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003283 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003284 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003285 Context.DependentTy,
3286 VK_LValue, OK_Ordinary,
3287 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003288 }
3289
David Blaikiebbafb8a2012-03-11 07:00:24 +00003290 if (getLangOpts().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003291 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003292 LHSExp->getType()->isEnumeralType() ||
3293 RHSExp->getType()->isRecordType() ||
Ted Kremeneke65b0862012-03-06 20:05:56 +00003294 RHSExp->getType()->isEnumeralType()) &&
3295 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCallb268a282010-08-23 23:25:46 +00003296 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003297 }
3298
John McCallb268a282010-08-23 23:25:46 +00003299 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003300}
3301
John McCalldadc5752010-08-24 06:29:42 +00003302ExprResult
John McCallb268a282010-08-23 23:25:46 +00003303Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003304 Expr *Idx, SourceLocation RLoc) {
John McCallb268a282010-08-23 23:25:46 +00003305 Expr *LHSExp = Base;
3306 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003307
Chris Lattner36d572b2007-07-16 00:14:47 +00003308 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003309 if (!LHSExp->getType()->getAs<VectorType>()) {
3310 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3311 if (Result.isInvalid())
3312 return ExprError();
3313 LHSExp = Result.take();
3314 }
3315 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3316 if (Result.isInvalid())
3317 return ExprError();
3318 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003319
Chris Lattner36d572b2007-07-16 00:14:47 +00003320 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003321 ExprValueKind VK = VK_LValue;
3322 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003323
Steve Naroffc1aadb12007-03-28 21:49:40 +00003324 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003325 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003326 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003327 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003328 Expr *BaseExpr, *IndexExpr;
3329 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003330 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3331 BaseExpr = LHSExp;
3332 IndexExpr = RHSExp;
3333 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003334 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003335 BaseExpr = LHSExp;
3336 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003337 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003338 } else if (const ObjCObjectPointerType *PTy =
John McCallf2538342012-07-31 05:14:30 +00003339 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003340 BaseExpr = LHSExp;
3341 IndexExpr = RHSExp;
John McCallf2538342012-07-31 05:14:30 +00003342
3343 // Use custom logic if this should be the pseudo-object subscript
3344 // expression.
3345 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3346 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3347
Steve Naroff7cae42b2009-07-10 23:34:53 +00003348 ResultType = PTy->getPointeeType();
John McCallf2538342012-07-31 05:14:30 +00003349 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3350 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3351 << ResultType << BaseExpr->getSourceRange();
3352 return ExprError();
3353 }
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00003354 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3355 // Handle the uncommon case of "123[Ptr]".
3356 BaseExpr = RHSExp;
3357 IndexExpr = LHSExp;
3358 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003359 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003360 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003361 // Handle the uncommon case of "123[Ptr]".
3362 BaseExpr = RHSExp;
3363 IndexExpr = LHSExp;
3364 ResultType = PTy->getPointeeType();
John McCallf2538342012-07-31 05:14:30 +00003365 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3366 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3367 << ResultType << BaseExpr->getSourceRange();
3368 return ExprError();
3369 }
John McCall9dd450b2009-09-21 23:43:11 +00003370 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003371 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003372 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003373 VK = LHSExp->getValueKind();
3374 if (VK != VK_RValue)
3375 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003376
Chris Lattner36d572b2007-07-16 00:14:47 +00003377 // FIXME: need to deal with const...
3378 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003379 } else if (LHSTy->isArrayType()) {
3380 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003381 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003382 // wasn't promoted because of the C90 rule that doesn't
3383 // allow promoting non-lvalue arrays. Warn, then
3384 // force the promotion here.
3385 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3386 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003387 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3388 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003389 LHSTy = LHSExp->getType();
3390
3391 BaseExpr = LHSExp;
3392 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003393 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003394 } else if (RHSTy->isArrayType()) {
3395 // Same as previous, except for 123[f().a] case
3396 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3397 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003398 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3399 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003400 RHSTy = RHSExp->getType();
3401
3402 BaseExpr = RHSExp;
3403 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003404 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003405 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003406 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3407 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003408 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003409 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003410 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003411 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3412 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003413
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003414 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003415 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3416 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003417 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3418
Douglas Gregorac1fb652009-03-24 19:52:54 +00003419 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003420 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3421 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003422 // incomplete types are not object types.
3423 if (ResultType->isFunctionType()) {
3424 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3425 << ResultType << BaseExpr->getSourceRange();
3426 return ExprError();
3427 }
Mike Stump11289f42009-09-09 15:08:12 +00003428
David Blaikiebbafb8a2012-03-11 07:00:24 +00003429 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003430 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003431 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3432 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003433
3434 // C forbids expressions of unqualified void type from being l-values.
3435 // See IsCForbiddenLValueType.
3436 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003437 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003438 RequireCompleteType(LLoc, ResultType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003439 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003440 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003441
John McCall4bc41ae2010-11-18 19:01:18 +00003442 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003443 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003444
Mike Stump4e1f26a2009-02-19 03:04:26 +00003445 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003446 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003447}
3448
John McCalldadc5752010-08-24 06:29:42 +00003449ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003450 FunctionDecl *FD,
3451 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003452 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003453 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003454 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003455 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003456 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003457 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003458 return ExprError();
3459 }
3460
3461 if (Param->hasUninstantiatedDefaultArg()) {
3462 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003463
Richard Smith505df232012-07-22 23:45:10 +00003464 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3465 Param);
3466
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003467 // Instantiate the expression.
3468 MultiLevelTemplateArgumentList ArgList
3469 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003470
Nico Weber44887f62010-11-29 18:19:25 +00003471 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003472 = ArgList.getInnermost();
Richard Smith80934652012-07-16 01:09:10 +00003473 InstantiatingTemplate Inst(*this, CallLoc, Param,
3474 ArrayRef<TemplateArgument>(Innermost.first,
3475 Innermost.second));
Richard Smith8a874c92012-07-08 02:38:24 +00003476 if (Inst)
3477 return ExprError();
Anders Carlsson355933d2009-08-25 03:49:14 +00003478
Nico Weber44887f62010-11-29 18:19:25 +00003479 ExprResult Result;
3480 {
3481 // C++ [dcl.fct.default]p5:
3482 // The names in the [default argument] expression are bound, and
3483 // the semantic constraints are checked, at the point where the
3484 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003485 ContextRAII SavedContext(*this, FD);
Douglas Gregora86bc002012-02-16 21:36:18 +00003486 LocalInstantiationScope Local(*this);
Nico Weber44887f62010-11-29 18:19:25 +00003487 Result = SubstExpr(UninstExpr, ArgList);
3488 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003489 if (Result.isInvalid())
3490 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003491
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003492 // Check the expression as an initializer for the parameter.
3493 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003494 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003495 InitializationKind Kind
3496 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003497 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003498 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003499
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003500 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003501 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003502 if (Result.isInvalid())
3503 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003504
David Blaikief68e8092012-04-30 18:21:31 +00003505 Expr *Arg = Result.takeAs<Expr>();
David Blaikie18e9ac72012-05-15 21:57:38 +00003506 CheckImplicitConversions(Arg, Param->getOuterLocStart());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003507 // Build the default argument expression.
David Blaikief68e8092012-04-30 18:21:31 +00003508 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson355933d2009-08-25 03:49:14 +00003509 }
3510
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003511 // If the default expression creates temporaries, we need to
3512 // push them to the current stack of expression temporaries so they'll
3513 // be properly destroyed.
3514 // FIXME: We should really be rebuilding the default argument with new
3515 // bound temporaries; see the comment in PR5810.
John McCall28fc7092011-11-10 05:35:25 +00003516 // We don't need to do that with block decls, though, because
3517 // blocks in default argument expression can never capture anything.
3518 if (isa<ExprWithCleanups>(Param->getInit())) {
3519 // Set the "needs cleanups" bit regardless of whether there are
3520 // any explicit objects.
John McCall31168b02011-06-15 23:02:42 +00003521 ExprNeedsCleanups = true;
John McCall28fc7092011-11-10 05:35:25 +00003522
3523 // Append all the objects to the cleanup list. Right now, this
3524 // should always be a no-op, because blocks in default argument
3525 // expressions should never be able to capture anything.
3526 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3527 "default argument expression has capturing blocks?");
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003528 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003529
3530 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003531 // Just mark all of the declarations in this potentially-evaluated expression
3532 // as being "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +00003533 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3534 /*SkipLocalVariables=*/true);
Douglas Gregor033f6752009-12-23 23:03:06 +00003535 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003536}
3537
Richard Smith55ce3522012-06-25 20:30:08 +00003538
3539Sema::VariadicCallType
3540Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3541 Expr *Fn) {
3542 if (Proto && Proto->isVariadic()) {
3543 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3544 return VariadicConstructor;
3545 else if (Fn && Fn->getType()->isBlockPointerType())
3546 return VariadicBlock;
3547 else if (FDecl) {
3548 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3549 if (Method->isInstance())
3550 return VariadicMethod;
3551 }
3552 return VariadicFunction;
3553 }
3554 return VariadicDoesNotApply;
3555}
3556
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003557/// ConvertArgumentsForCall - Converts the arguments specified in
3558/// Args/NumArgs to the parameter types of the function FDecl with
3559/// function prototype Proto. Call is the call expression itself, and
3560/// Fn is the function expression. For a C++ member function, this
3561/// routine does not attempt to convert the object argument. Returns
3562/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003563bool
3564Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003565 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003566 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003567 Expr **Args, unsigned NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003568 SourceLocation RParenLoc,
3569 bool IsExecConfig) {
John McCallbebede42011-02-26 05:39:39 +00003570 // Bail out early if calling a builtin with custom typechecking.
3571 // We don't need to do this in the
3572 if (FDecl)
3573 if (unsigned ID = FDecl->getBuiltinID())
3574 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3575 return false;
3576
Mike Stump4e1f26a2009-02-19 03:04:26 +00003577 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003578 // assignment, to the types of the corresponding parameter, ...
3579 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003580 bool Invalid = false;
Peter Collingbourne740afe22011-10-02 23:49:20 +00003581 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003582 unsigned FnKind = Fn->getType()->isBlockPointerType()
3583 ? 1 /* block */
3584 : (IsExecConfig ? 3 /* kernel function (exec config) */
3585 : 0 /* function */);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003586
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003587 // If too few arguments are available (and we don't have default
3588 // arguments for the remaining parameters), don't make the call.
3589 if (NumArgs < NumArgsInProto) {
Peter Collingbourne740afe22011-10-02 23:49:20 +00003590 if (NumArgs < MinArgs) {
Richard Smith10ff50d2012-05-11 05:16:41 +00003591 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3592 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3593 ? diag::err_typecheck_call_too_few_args_one
3594 : diag::err_typecheck_call_too_few_args_at_least_one)
3595 << FnKind
3596 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3597 else
3598 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3599 ? diag::err_typecheck_call_too_few_args
3600 : diag::err_typecheck_call_too_few_args_at_least)
3601 << FnKind
3602 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003603
3604 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003605 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003606 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3607 << FDecl;
3608
3609 return true;
3610 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003611 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003612 }
3613
3614 // If too many are passed and not variadic, error on the extras and drop
3615 // them.
3616 if (NumArgs > NumArgsInProto) {
3617 if (!Proto->isVariadic()) {
Richard Smithd72da152012-05-15 06:21:54 +00003618 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3619 Diag(Args[NumArgsInProto]->getLocStart(),
3620 MinArgs == NumArgsInProto
3621 ? diag::err_typecheck_call_too_many_args_one
3622 : diag::err_typecheck_call_too_many_args_at_most_one)
3623 << FnKind
3624 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3625 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3626 Args[NumArgs-1]->getLocEnd());
3627 else
3628 Diag(Args[NumArgsInProto]->getLocStart(),
3629 MinArgs == NumArgsInProto
3630 ? diag::err_typecheck_call_too_many_args
3631 : diag::err_typecheck_call_too_many_args_at_most)
3632 << FnKind
3633 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3634 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3635 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003636
3637 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003638 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003639 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3640 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003641
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003642 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003643 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003644 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003645 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003646 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003647 SmallVector<Expr *, 8> AllArgs;
Richard Smith55ce3522012-06-25 20:30:08 +00003648 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3649
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003650 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003651 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003652 if (Invalid)
3653 return true;
3654 unsigned TotalNumArgs = AllArgs.size();
3655 for (unsigned i = 0; i < TotalNumArgs; ++i)
3656 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003657
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003658 return false;
3659}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003660
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003661bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3662 FunctionDecl *FDecl,
3663 const FunctionProtoType *Proto,
3664 unsigned FirstProtoArg,
3665 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003666 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003667 VariadicCallType CallType,
3668 bool AllowExplicit) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003669 unsigned NumArgsInProto = Proto->getNumArgs();
3670 unsigned NumArgsToCheck = NumArgs;
3671 bool Invalid = false;
3672 if (NumArgs != NumArgsInProto)
3673 // Use default arguments for missing arguments
3674 NumArgsToCheck = NumArgsInProto;
3675 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003676 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003677 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003678 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003679
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003680 Expr *Arg;
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003681 ParmVarDecl *Param;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003682 if (ArgIx < NumArgs) {
3683 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003684
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003685 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedman3164fb12009-03-22 22:00:50 +00003686 ProtoArgType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003687 diag::err_call_incomplete_argument, Arg))
Eli Friedman3164fb12009-03-22 22:00:50 +00003688 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003689
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003690 // Pass the argument
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003691 Param = 0;
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003692 if (FDecl && i < FDecl->getNumParams())
3693 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003694
John McCall4124c492011-10-17 18:40:02 +00003695 // Strip the unbridged-cast placeholder expression off, if applicable.
3696 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3697 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3698 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3699 Arg = stripARCUnbridgedCast(Arg);
3700
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003701 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003702 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003703 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3704 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003705 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003706 SourceLocation(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00003707 Owned(Arg),
3708 /*TopLevelOfInitList=*/false,
3709 AllowExplicit);
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003710 if (ArgE.isInvalid())
3711 return true;
3712
3713 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003714 } else {
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003715 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003716
John McCalldadc5752010-08-24 06:29:42 +00003717 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003718 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003719 if (ArgExpr.isInvalid())
3720 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003721
Anders Carlsson355933d2009-08-25 03:49:14 +00003722 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003723 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003724
3725 // Check for array bounds violations for each argument to the call. This
3726 // check only triggers warnings when the argument isn't a more complex Expr
3727 // with its own checking, such as a BinaryOperator.
3728 CheckArrayAccess(Arg);
3729
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003730 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3731 CheckStaticArrayArgument(CallLoc, Param, Arg);
3732
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003733 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003734 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003735
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003736 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003737 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003738 // Assume that extern "C" functions with variadic arguments that
3739 // return __unknown_anytype aren't *really* variadic.
3740 if (Proto->getResultType() == Context.UnknownAnyTy &&
3741 FDecl && FDecl->isExternC()) {
3742 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3743 ExprResult arg;
3744 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3745 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3746 else
3747 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3748 Invalid |= arg.isInvalid();
3749 AllArgs.push_back(arg.take());
3750 }
3751
3752 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3753 } else {
3754 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003755 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3756 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003757 Invalid |= Arg.isInvalid();
3758 AllArgs.push_back(Arg.take());
3759 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003760 }
Ted Kremenekd41f3462011-09-26 23:36:13 +00003761
3762 // Check for array bounds violations.
3763 for (unsigned i = ArgIx; i != NumArgs; ++i)
3764 CheckArrayAccess(Args[i]);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003765 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003766 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003767}
3768
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003769static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3770 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3771 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3772 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3773 << ATL->getLocalSourceRange();
3774}
3775
3776/// CheckStaticArrayArgument - If the given argument corresponds to a static
3777/// array parameter, check that it is non-null, and that if it is formed by
3778/// array-to-pointer decay, the underlying array is sufficiently large.
3779///
3780/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3781/// array type derivation, then for each call to the function, the value of the
3782/// corresponding actual argument shall provide access to the first element of
3783/// an array with at least as many elements as specified by the size expression.
3784void
3785Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3786 ParmVarDecl *Param,
3787 const Expr *ArgExpr) {
3788 // Static array parameters are not supported in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003789 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003790 return;
3791
3792 QualType OrigTy = Param->getOriginalType();
3793
3794 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3795 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3796 return;
3797
3798 if (ArgExpr->isNullPointerConstant(Context,
3799 Expr::NPC_NeverValueDependent)) {
3800 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3801 DiagnoseCalleeStaticArrayParam(*this, Param);
3802 return;
3803 }
3804
3805 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3806 if (!CAT)
3807 return;
3808
3809 const ConstantArrayType *ArgCAT =
3810 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3811 if (!ArgCAT)
3812 return;
3813
3814 if (ArgCAT->getSize().ult(CAT->getSize())) {
3815 Diag(CallLoc, diag::warn_static_array_too_small)
3816 << ArgExpr->getSourceRange()
3817 << (unsigned) ArgCAT->getSize().getZExtValue()
3818 << (unsigned) CAT->getSize().getZExtValue();
3819 DiagnoseCalleeStaticArrayParam(*this, Param);
3820 }
3821}
3822
John McCall2979fe02011-04-12 00:42:48 +00003823/// Given a function expression of unknown-any type, try to rebuild it
3824/// to have a function type.
3825static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3826
Steve Naroff83895f72007-09-16 03:34:24 +00003827/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003828/// This provides the location of the left/right parens and a list of comma
3829/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003830ExprResult
John McCallb268a282010-08-23 23:25:46 +00003831Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003832 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003833 Expr *ExecConfig, bool IsExecConfig) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003834 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003835 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003836 if (Result.isInvalid()) return ExprError();
3837 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003838
David Blaikiebbafb8a2012-03-11 07:00:24 +00003839 if (getLangOpts().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003840 // If this is a pseudo-destructor expression, build the call immediately.
3841 if (isa<CXXPseudoDestructorExpr>(Fn)) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003842 if (!ArgExprs.empty()) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003843 // Pseudo-destructor calls should not have any arguments.
3844 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003845 << FixItHint::CreateRemoval(
Benjamin Kramerc215e762012-08-24 11:54:20 +00003846 SourceRange(ArgExprs[0]->getLocStart(),
3847 ArgExprs.back()->getLocEnd()));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003848 }
Mike Stump11289f42009-09-09 15:08:12 +00003849
Benjamin Kramerc215e762012-08-24 11:54:20 +00003850 return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(),
3851 Context.VoidTy, VK_RValue,
3852 RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003853 }
Mike Stump11289f42009-09-09 15:08:12 +00003854
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003855 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003856 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003857 // FIXME: Will need to cache the results of name lookup (including ADL) in
3858 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003859 bool Dependent = false;
3860 if (Fn->isTypeDependent())
3861 Dependent = true;
Benjamin Kramerc215e762012-08-24 11:54:20 +00003862 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003863 Dependent = true;
3864
Peter Collingbourne41f85462011-02-09 21:07:24 +00003865 if (Dependent) {
3866 if (ExecConfig) {
3867 return Owned(new (Context) CUDAKernelCallExpr(
Benjamin Kramerc215e762012-08-24 11:54:20 +00003868 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003869 Context.DependentTy, VK_RValue, RParenLoc));
3870 } else {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003871 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003872 Context.DependentTy, VK_RValue,
3873 RParenLoc));
3874 }
3875 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003876
3877 // Determine whether this is a call to an object (C++ [over.call.object]).
3878 if (Fn->getType()->isRecordType())
Benjamin Kramerc215e762012-08-24 11:54:20 +00003879 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
3880 ArgExprs.data(),
3881 ArgExprs.size(), RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003882
John McCall2979fe02011-04-12 00:42:48 +00003883 if (Fn->getType() == Context.UnknownAnyTy) {
3884 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3885 if (result.isInvalid()) return ExprError();
3886 Fn = result.take();
3887 }
3888
John McCall0009fcc2011-04-26 20:42:42 +00003889 if (Fn->getType() == Context.BoundMemberTy) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003890 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3891 ArgExprs.size(), RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003892 }
John McCall0009fcc2011-04-26 20:42:42 +00003893 }
John McCall10eae182009-11-30 22:42:35 +00003894
John McCall0009fcc2011-04-26 20:42:42 +00003895 // Check for overloaded calls. This can happen even in C due to extensions.
3896 if (Fn->getType() == Context.OverloadTy) {
3897 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3898
Douglas Gregorcda22702011-10-13 18:10:35 +00003899 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregorf4a06c22011-10-13 18:26:27 +00003900 if (!find.HasFormOfMemberPointer) {
John McCall0009fcc2011-04-26 20:42:42 +00003901 OverloadExpr *ovl = find.Expression;
3902 if (isa<UnresolvedLookupExpr>(ovl)) {
3903 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
Benjamin Kramerc215e762012-08-24 11:54:20 +00003904 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(),
3905 ArgExprs.size(), RParenLoc, ExecConfig);
John McCall0009fcc2011-04-26 20:42:42 +00003906 } else {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003907 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3908 ArgExprs.size(), RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003909 }
3910 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003911 }
3912
Douglas Gregore254f902009-02-04 00:32:51 +00003913 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregord8fb1e32011-12-01 01:37:36 +00003914 if (Fn->getType() == Context.UnknownAnyTy) {
3915 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3916 if (result.isInvalid()) return ExprError();
3917 Fn = result.take();
3918 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003919
Eli Friedmane14b1992009-12-26 03:35:45 +00003920 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003921
John McCall57500772009-12-16 12:17:52 +00003922 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003923 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3924 if (UnOp->getOpcode() == UO_AddrOf)
3925 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3926
John McCall57500772009-12-16 12:17:52 +00003927 if (isa<DeclRefExpr>(NakedFn))
3928 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003929 else if (isa<MemberExpr>(NakedFn))
3930 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003931
Benjamin Kramerc215e762012-08-24 11:54:20 +00003932 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(),
3933 ArgExprs.size(), RParenLoc, ExecConfig,
3934 IsExecConfig);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003935}
3936
3937ExprResult
3938Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003939 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbourne41f85462011-02-09 21:07:24 +00003940 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3941 if (!ConfigDecl)
3942 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3943 << "cudaConfigureCall");
3944 QualType ConfigQTy = ConfigDecl->getType();
3945
3946 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCall113bee02012-03-10 09:33:50 +00003947 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedmanfa0df832012-02-02 03:46:19 +00003948 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003949
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003950 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3951 /*IsExecConfig=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003952}
3953
Tanya Lattner55808c12011-06-04 00:47:47 +00003954/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3955///
3956/// __builtin_astype( value, dst type )
3957///
Richard Trieuba63ce62011-09-09 01:45:06 +00003958ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00003959 SourceLocation BuiltinLoc,
3960 SourceLocation RParenLoc) {
3961 ExprValueKind VK = VK_RValue;
3962 ExprObjectKind OK = OK_Ordinary;
Richard Trieuba63ce62011-09-09 01:45:06 +00003963 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3964 QualType SrcTy = E->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00003965 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3966 return ExprError(Diag(BuiltinLoc,
3967 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003968 << DstTy
3969 << SrcTy
Richard Trieuba63ce62011-09-09 01:45:06 +00003970 << E->getSourceRange());
3971 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieucfc491d2011-08-02 04:35:43 +00003972 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003973}
3974
John McCall57500772009-12-16 12:17:52 +00003975/// BuildResolvedCallExpr - Build a call to a resolved expression,
3976/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003977/// unary-convert to an expression of function-pointer or
3978/// block-pointer type.
3979///
3980/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003981ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003982Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3983 SourceLocation LParenLoc,
3984 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003985 SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003986 Expr *Config, bool IsExecConfig) {
John McCall2d74de92009-12-01 22:10:20 +00003987 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
Eli Friedman34866c72012-08-31 00:14:07 +00003988 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
John McCall2d74de92009-12-01 22:10:20 +00003989
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003990 // Promote the function operand.
Eli Friedman34866c72012-08-31 00:14:07 +00003991 // We special-case function promotion here because we only allow promoting
3992 // builtin functions to function pointers in the callee of a call.
3993 ExprResult Result;
3994 if (BuiltinID &&
3995 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
3996 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
3997 CK_BuiltinFnToFnPtr).take();
3998 } else {
3999 Result = UsualUnaryConversions(Fn);
4000 }
John Wiegley01296292011-04-08 18:41:53 +00004001 if (Result.isInvalid())
4002 return ExprError();
4003 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004004
Chris Lattner08464942007-12-28 05:29:59 +00004005 // Make the call expr early, before semantic checks. This guarantees cleanup
4006 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00004007 CallExpr *TheCall;
Eric Christopher13586ab2012-05-30 01:14:28 +00004008 if (Config)
Peter Collingbourne41f85462011-02-09 21:07:24 +00004009 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4010 cast<CallExpr>(Config),
Benjamin Kramerc215e762012-08-24 11:54:20 +00004011 llvm::makeArrayRef(Args,NumArgs),
Peter Collingbourne41f85462011-02-09 21:07:24 +00004012 Context.BoolTy,
4013 VK_RValue,
4014 RParenLoc);
Eric Christopher13586ab2012-05-30 01:14:28 +00004015 else
Peter Collingbourne41f85462011-02-09 21:07:24 +00004016 TheCall = new (Context) CallExpr(Context, Fn,
Benjamin Kramerc215e762012-08-24 11:54:20 +00004017 llvm::makeArrayRef(Args, NumArgs),
Peter Collingbourne41f85462011-02-09 21:07:24 +00004018 Context.BoolTy,
4019 VK_RValue,
4020 RParenLoc);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004021
John McCallbebede42011-02-26 05:39:39 +00004022 // Bail out early if calling a builtin with custom typechecking.
4023 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4024 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4025
John McCall31996342011-04-07 08:22:57 +00004026 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004027 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00004028 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004029 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4030 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00004031 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00004032 if (FuncT == 0)
4033 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4034 << Fn->getType() << Fn->getSourceRange());
4035 } else if (const BlockPointerType *BPT =
4036 Fn->getType()->getAs<BlockPointerType>()) {
4037 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4038 } else {
John McCall31996342011-04-07 08:22:57 +00004039 // Handle calls to expressions of unknown-any type.
4040 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00004041 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00004042 if (rewrite.isInvalid()) return ExprError();
4043 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00004044 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00004045 goto retry;
4046 }
4047
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004048 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4049 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00004050 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004051
David Blaikiebbafb8a2012-03-11 07:00:24 +00004052 if (getLangOpts().CUDA) {
Peter Collingbourne4b66c472011-02-23 01:53:29 +00004053 if (Config) {
4054 // CUDA: Kernel calls must be to global functions
4055 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4056 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4057 << FDecl->getName() << Fn->getSourceRange());
4058
4059 // CUDA: Kernel function must have 'void' return type
4060 if (!FuncT->getResultType()->isVoidType())
4061 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4062 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne34a20b02011-10-02 23:49:15 +00004063 } else {
4064 // CUDA: Calls to global functions must be configured
4065 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4066 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4067 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne4b66c472011-02-23 01:53:29 +00004068 }
4069 }
4070
Eli Friedman3164fb12009-03-22 22:00:50 +00004071 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004072 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004073 Fn->getLocStart(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004074 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00004075 return ExprError();
4076
Chris Lattner08464942007-12-28 05:29:59 +00004077 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004078 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00004079 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004080
Richard Smith55ce3522012-06-25 20:30:08 +00004081 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4082 if (Proto) {
John McCallb268a282010-08-23 23:25:46 +00004083 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00004084 RParenLoc, IsExecConfig))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004085 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00004086 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004087 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004088
Douglas Gregord8e97de2009-04-02 15:37:10 +00004089 if (FDecl) {
4090 // Check if we have too few/too many template arguments, based
4091 // on our knowledge of the function definition.
4092 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00004093 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Richard Smith55ce3522012-06-25 20:30:08 +00004094 Proto = Def->getType()->getAs<FunctionProtoType>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00004095 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004096 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4097 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004098 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00004099
4100 // If the function we're calling isn't a function prototype, but we have
4101 // a function prototype from a prior declaratiom, use that prototype.
4102 if (!FDecl->hasPrototype())
4103 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00004104 }
4105
Steve Naroff0b661582007-08-28 23:30:39 +00004106 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00004107 for (unsigned i = 0; i != NumArgs; i++) {
4108 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00004109
4110 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004111 InitializedEntity Entity
4112 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00004113 Proto->getArgType(i),
4114 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00004115 ExprResult ArgE = PerformCopyInitialization(Entity,
4116 SourceLocation(),
4117 Owned(Arg));
4118 if (ArgE.isInvalid())
4119 return true;
4120
4121 Arg = ArgE.takeAs<Expr>();
4122
4123 } else {
John Wiegley01296292011-04-08 18:41:53 +00004124 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4125
4126 if (ArgE.isInvalid())
4127 return true;
4128
4129 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00004130 }
4131
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004132 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor83025412010-10-26 05:45:40 +00004133 Arg->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004134 diag::err_call_incomplete_argument, Arg))
Douglas Gregor83025412010-10-26 05:45:40 +00004135 return ExprError();
4136
Chris Lattner08464942007-12-28 05:29:59 +00004137 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00004138 }
Steve Naroffae4143e2007-04-26 20:39:23 +00004139 }
Chris Lattner08464942007-12-28 05:29:59 +00004140
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004141 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4142 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004143 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4144 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004145
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00004146 // Check for sentinels
4147 if (NDecl)
4148 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004149
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004150 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004151 if (FDecl) {
Richard Smith55ce3522012-06-25 20:30:08 +00004152 if (CheckFunctionCall(FDecl, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004153 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004154
John McCallbebede42011-02-26 05:39:39 +00004155 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00004156 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004157 } else if (NDecl) {
Richard Smith55ce3522012-06-25 20:30:08 +00004158 if (CheckBlockCall(NDecl, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004159 return ExprError();
4160 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004161
John McCallb268a282010-08-23 23:25:46 +00004162 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00004163}
4164
John McCalldadc5752010-08-24 06:29:42 +00004165ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004166Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004167 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00004168 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00004169 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00004170 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00004171
4172 TypeSourceInfo *TInfo;
4173 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4174 if (!TInfo)
4175 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4176
John McCallb268a282010-08-23 23:25:46 +00004177 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00004178}
4179
John McCalldadc5752010-08-24 06:29:42 +00004180ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00004181Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00004182 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00004183 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00004184
Eli Friedman37a186d2008-05-20 05:22:08 +00004185 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004186 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004187 diag::err_illegal_decl_array_incomplete_type,
4188 SourceRange(LParenLoc,
4189 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004190 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00004191 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004192 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuba63ce62011-09-09 01:45:06 +00004193 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00004194 } else if (!literalType->isDependentType() &&
4195 RequireCompleteType(LParenLoc, literalType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004196 diag::err_typecheck_decl_incomplete_type,
4197 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004198 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00004199
Douglas Gregor85dabae2009-12-16 01:38:02 +00004200 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00004201 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004202 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00004203 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl0501c632012-02-12 16:37:36 +00004204 SourceRange(LParenLoc, RParenLoc),
4205 /*InitList=*/true);
Richard Trieuba63ce62011-09-09 01:45:06 +00004206 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004207 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4208 &literalType);
Eli Friedmana553d4a2009-12-22 02:35:53 +00004209 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004210 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004211 LiteralExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00004212
Chris Lattner79413952008-12-04 23:50:19 +00004213 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00004214 if (isFileScope) { // 6.5.2.5p3
Richard Trieuba63ce62011-09-09 01:45:06 +00004215 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004216 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004217 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004218
John McCall7decc9e2010-11-18 06:31:45 +00004219 // In C, compound literals are l-values for some reason.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004220 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00004221
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00004222 return MaybeBindToTemporary(
4223 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuba63ce62011-09-09 01:45:06 +00004224 VK, LiteralExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004225}
4226
John McCalldadc5752010-08-24 06:29:42 +00004227ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004228Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004229 SourceLocation RBraceLoc) {
John McCall526ab472011-10-25 17:37:35 +00004230 // Immediately handle non-overload placeholders. Overloads can be
4231 // resolved contextually, but everything else here can't.
Benjamin Kramerc215e762012-08-24 11:54:20 +00004232 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4233 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4234 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
John McCall526ab472011-10-25 17:37:35 +00004235
4236 // Ignore failures; dropping the entire initializer list because
4237 // of one failure would be terrible for indexing/etc.
4238 if (result.isInvalid()) continue;
4239
Benjamin Kramerc215e762012-08-24 11:54:20 +00004240 InitArgList[I] = result.take();
John McCall526ab472011-10-25 17:37:35 +00004241 }
4242 }
4243
Steve Naroff30d242c2007-09-15 18:49:24 +00004244 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004245 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004246
Benjamin Kramerc215e762012-08-24 11:54:20 +00004247 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4248 RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004249 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004250 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004251}
4252
John McCallcd78e802011-09-10 01:16:55 +00004253/// Do an explicit extend of the given block pointer if we're in ARC.
4254static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4255 assert(E.get()->getType()->isBlockPointerType());
4256 assert(E.get()->isRValue());
4257
4258 // Only do this in an r-value context.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004259 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallcd78e802011-09-10 01:16:55 +00004260
4261 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall2d637d22011-09-10 06:18:15 +00004262 CK_ARCExtendBlockObject, E.get(),
John McCallcd78e802011-09-10 01:16:55 +00004263 /*base path*/ 0, VK_RValue);
4264 S.ExprNeedsCleanups = true;
4265}
4266
4267/// Prepare a conversion of the given expression to an ObjC object
4268/// pointer type.
4269CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4270 QualType type = E.get()->getType();
4271 if (type->isObjCObjectPointerType()) {
4272 return CK_BitCast;
4273 } else if (type->isBlockPointerType()) {
4274 maybeExtendBlockObject(*this, E);
4275 return CK_BlockPointerToObjCPointerCast;
4276 } else {
4277 assert(type->isPointerType());
4278 return CK_CPointerToObjCPointerCast;
4279 }
4280}
4281
John McCalld7646252010-11-14 08:17:51 +00004282/// Prepares for a scalar cast, performing all the necessary stages
4283/// except the final cast and returning the kind required.
John McCall9776e432011-10-06 23:25:11 +00004284CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00004285 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4286 // Also, callers should have filtered out the invalid cases with
4287 // pointers. Everything else should be possible.
4288
John Wiegley01296292011-04-08 18:41:53 +00004289 QualType SrcTy = Src.get()->getType();
John McCall9776e432011-10-06 23:25:11 +00004290 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004291 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004292
John McCall9320b872011-09-09 05:25:32 +00004293 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00004294 case Type::STK_MemberPointer:
4295 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00004296
John McCall9320b872011-09-09 05:25:32 +00004297 case Type::STK_CPointer:
4298 case Type::STK_BlockPointer:
4299 case Type::STK_ObjCObjectPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004300 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004301 case Type::STK_CPointer:
4302 return CK_BitCast;
4303 case Type::STK_BlockPointer:
4304 return (SrcKind == Type::STK_BlockPointer
4305 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4306 case Type::STK_ObjCObjectPointer:
4307 if (SrcKind == Type::STK_ObjCObjectPointer)
4308 return CK_BitCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004309 if (SrcKind == Type::STK_CPointer)
John McCall9320b872011-09-09 05:25:32 +00004310 return CK_CPointerToObjCPointerCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004311 maybeExtendBlockObject(*this, Src);
4312 return CK_BlockPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00004313 case Type::STK_Bool:
4314 return CK_PointerToBoolean;
4315 case Type::STK_Integral:
4316 return CK_PointerToIntegral;
4317 case Type::STK_Floating:
4318 case Type::STK_FloatingComplex:
4319 case Type::STK_IntegralComplex:
4320 case Type::STK_MemberPointer:
4321 llvm_unreachable("illegal cast from pointer");
4322 }
David Blaikie8a40f702012-01-17 06:56:22 +00004323 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004324
John McCall8cb679e2010-11-15 09:13:47 +00004325 case Type::STK_Bool: // casting from bool is like casting from an integer
4326 case Type::STK_Integral:
4327 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004328 case Type::STK_CPointer:
4329 case Type::STK_ObjCObjectPointer:
4330 case Type::STK_BlockPointer:
John McCall9776e432011-10-06 23:25:11 +00004331 if (Src.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00004332 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004333 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004334 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004335 case Type::STK_Bool:
4336 return CK_IntegralToBoolean;
4337 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004338 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004339 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004340 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004341 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004342 Src = ImpCastExprToType(Src.take(),
4343 DestTy->castAs<ComplexType>()->getElementType(),
4344 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004345 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004346 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004347 Src = ImpCastExprToType(Src.take(),
4348 DestTy->castAs<ComplexType>()->getElementType(),
4349 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00004350 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004351 case Type::STK_MemberPointer:
4352 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004353 }
David Blaikie8a40f702012-01-17 06:56:22 +00004354 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004355
John McCall8cb679e2010-11-15 09:13:47 +00004356 case Type::STK_Floating:
4357 switch (DestTy->getScalarTypeKind()) {
4358 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004359 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004360 case Type::STK_Bool:
4361 return CK_FloatingToBoolean;
4362 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004363 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004364 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004365 Src = ImpCastExprToType(Src.take(),
4366 DestTy->castAs<ComplexType>()->getElementType(),
4367 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004368 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004369 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004370 Src = ImpCastExprToType(Src.take(),
4371 DestTy->castAs<ComplexType>()->getElementType(),
4372 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00004373 return CK_IntegralRealToComplex;
John McCall9320b872011-09-09 05:25:32 +00004374 case Type::STK_CPointer:
4375 case Type::STK_ObjCObjectPointer:
4376 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004377 llvm_unreachable("valid float->pointer cast?");
4378 case Type::STK_MemberPointer:
4379 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004380 }
David Blaikie8a40f702012-01-17 06:56:22 +00004381 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004382
John McCall8cb679e2010-11-15 09:13:47 +00004383 case Type::STK_FloatingComplex:
4384 switch (DestTy->getScalarTypeKind()) {
4385 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004386 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004387 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004388 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004389 case Type::STK_Floating: {
John McCall9776e432011-10-06 23:25:11 +00004390 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4391 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004392 return CK_FloatingComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004393 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004394 return CK_FloatingCast;
4395 }
John McCall8cb679e2010-11-15 09:13:47 +00004396 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004397 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004398 case Type::STK_Integral:
John McCall9776e432011-10-06 23:25:11 +00004399 Src = ImpCastExprToType(Src.take(),
4400 SrcTy->castAs<ComplexType>()->getElementType(),
4401 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004402 return CK_FloatingToIntegral;
John McCall9320b872011-09-09 05:25:32 +00004403 case Type::STK_CPointer:
4404 case Type::STK_ObjCObjectPointer:
4405 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004406 llvm_unreachable("valid complex float->pointer cast?");
4407 case Type::STK_MemberPointer:
4408 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004409 }
David Blaikie8a40f702012-01-17 06:56:22 +00004410 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004411
John McCall8cb679e2010-11-15 09:13:47 +00004412 case Type::STK_IntegralComplex:
4413 switch (DestTy->getScalarTypeKind()) {
4414 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004415 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004416 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004417 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004418 case Type::STK_Integral: {
John McCall9776e432011-10-06 23:25:11 +00004419 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4420 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004421 return CK_IntegralComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004422 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004423 return CK_IntegralCast;
4424 }
John McCall8cb679e2010-11-15 09:13:47 +00004425 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004426 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004427 case Type::STK_Floating:
John McCall9776e432011-10-06 23:25:11 +00004428 Src = ImpCastExprToType(Src.take(),
4429 SrcTy->castAs<ComplexType>()->getElementType(),
4430 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004431 return CK_IntegralToFloating;
John McCall9320b872011-09-09 05:25:32 +00004432 case Type::STK_CPointer:
4433 case Type::STK_ObjCObjectPointer:
4434 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004435 llvm_unreachable("valid complex int->pointer cast?");
4436 case Type::STK_MemberPointer:
4437 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004438 }
David Blaikie8a40f702012-01-17 06:56:22 +00004439 llvm_unreachable("Should have returned before this");
Anders Carlsson094c4592009-10-18 18:12:03 +00004440 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004441
John McCalld7646252010-11-14 08:17:51 +00004442 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson094c4592009-10-18 18:12:03 +00004443}
4444
Anders Carlsson525b76b2009-10-16 02:48:28 +00004445bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004446 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004447 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004448
Anders Carlssonde71adf2007-11-27 05:51:55 +00004449 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004450 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004451 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004452 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004453 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004454 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004455 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004456 } else
4457 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004458 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004459 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004460
John McCalle3027922010-08-25 11:45:40 +00004461 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004462 return false;
4463}
4464
John Wiegley01296292011-04-08 18:41:53 +00004465ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4466 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004467 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004468
Anders Carlsson43d70f82009-10-16 05:23:41 +00004469 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004470
Nate Begemanc8961a42009-06-27 22:05:55 +00004471 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4472 // an ExtVectorType.
Tobias Grosser766bcc22011-09-22 13:03:14 +00004473 // In OpenCL, casts between vectors of different types are not allowed.
4474 // (See OpenCL 6.2).
Nate Begemanc69b7402009-06-26 00:50:28 +00004475 if (SrcTy->isVectorType()) {
Tobias Grosser766bcc22011-09-22 13:03:14 +00004476 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikiebbafb8a2012-03-11 07:00:24 +00004477 || (getLangOpts().OpenCL &&
Tobias Grosser766bcc22011-09-22 13:03:14 +00004478 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004479 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004480 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004481 return ExprError();
4482 }
John McCalle3027922010-08-25 11:45:40 +00004483 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004484 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004485 }
4486
Nate Begemanbd956c42009-06-28 02:36:38 +00004487 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004488 // conversion will take place first from scalar to elt type, and then
4489 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004490 if (SrcTy->isPointerType())
4491 return Diag(R.getBegin(),
4492 diag::err_invalid_conversion_between_vector_and_scalar)
4493 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004494
4495 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004496 ExprResult CastExprRes = Owned(CastExpr);
John McCall9776e432011-10-06 23:25:11 +00004497 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley01296292011-04-08 18:41:53 +00004498 if (CastExprRes.isInvalid())
4499 return ExprError();
4500 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004501
John McCalle3027922010-08-25 11:45:40 +00004502 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004503 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004504}
4505
John McCalldadc5752010-08-24 06:29:42 +00004506ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004507Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4508 Declarator &D, ParsedType &Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004509 SourceLocation RParenLoc, Expr *CastExpr) {
4510 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004511 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004512
Richard Trieuba63ce62011-09-09 01:45:06 +00004513 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004514 if (D.isInvalidType())
4515 return ExprError();
4516
David Blaikiebbafb8a2012-03-11 07:00:24 +00004517 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004518 // Check that there are no default arguments (C++ only).
4519 CheckExtraCXXDefaultArguments(D);
4520 }
4521
John McCall42856de2011-10-01 05:17:03 +00004522 checkUnusedDeclAttributes(D);
4523
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004524 QualType castType = castTInfo->getType();
4525 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004526
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004527 bool isVectorLiteral = false;
4528
4529 // Check for an altivec or OpenCL literal,
4530 // i.e. all the elements are integer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00004531 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4532 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004533 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser0a3a22f2011-09-21 18:28:29 +00004534 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004535 if (PLE && PLE->getNumExprs() == 0) {
4536 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4537 return ExprError();
4538 }
4539 if (PE || PLE->getNumExprs() == 1) {
4540 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4541 if (!E->getType()->isVectorType())
4542 isVectorLiteral = true;
4543 }
4544 else
4545 isVectorLiteral = true;
4546 }
4547
4548 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4549 // then handle it as such.
4550 if (isVectorLiteral)
Richard Trieuba63ce62011-09-09 01:45:06 +00004551 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004552
Nate Begeman5ec4b312009-08-10 23:49:36 +00004553 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004554 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4555 // sequence of BinOp comma operators.
Richard Trieuba63ce62011-09-09 01:45:06 +00004556 if (isa<ParenListExpr>(CastExpr)) {
4557 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004558 if (Result.isInvalid()) return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004559 CastExpr = Result.take();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004560 }
John McCallebe54742010-01-15 18:56:44 +00004561
Richard Trieuba63ce62011-09-09 01:45:06 +00004562 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallebe54742010-01-15 18:56:44 +00004563}
4564
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004565ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4566 SourceLocation RParenLoc, Expr *E,
4567 TypeSourceInfo *TInfo) {
4568 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4569 "Expected paren or paren list expression");
4570
4571 Expr **exprs;
4572 unsigned numExprs;
4573 Expr *subExpr;
4574 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4575 exprs = PE->getExprs();
4576 numExprs = PE->getNumExprs();
4577 } else {
4578 subExpr = cast<ParenExpr>(E)->getSubExpr();
4579 exprs = &subExpr;
4580 numExprs = 1;
4581 }
4582
4583 QualType Ty = TInfo->getType();
4584 assert(Ty->isVectorType() && "Expected vector type");
4585
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004586 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004587 const VectorType *VTy = Ty->getAs<VectorType>();
4588 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4589
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004590 // '(...)' form of vector initialization in AltiVec: the number of
4591 // initializers must be one or must match the size of the vector.
4592 // If a single value is specified in the initializer then it will be
4593 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004594 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004595 // The number of initializers must be one or must match the size of the
4596 // vector. If a single value is specified in the initializer then it will
4597 // be replicated to all the components of the vector
4598 if (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();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004603 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004604 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004605 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4606 }
4607 else if (numExprs < numElems) {
4608 Diag(E->getExprLoc(),
4609 diag::err_incorrect_number_of_vector_initializers);
4610 return ExprError();
4611 }
4612 else
Benjamin Kramer8001f742012-02-14 12:06:21 +00004613 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004614 }
Tanya Lattner83559382011-07-15 23:07:01 +00004615 else {
4616 // For OpenCL, when the number of initializers is a single value,
4617 // it will be replicated to all components of the vector.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004618 if (getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +00004619 VTy->getVectorKind() == VectorType::GenericVector &&
4620 numExprs == 1) {
4621 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004622 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4623 if (Literal.isInvalid())
4624 return ExprError();
Tanya Lattner83559382011-07-15 23:07:01 +00004625 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004626 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner83559382011-07-15 23:07:01 +00004627 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4628 }
4629
Benjamin Kramer8001f742012-02-14 12:06:21 +00004630 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner83559382011-07-15 23:07:01 +00004631 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004632 // FIXME: This means that pretty-printing the final AST will produce curly
4633 // braces instead of the original commas.
4634 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00004635 initExprs, RParenLoc);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004636 initE->setType(Ty);
4637 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4638}
4639
Sebastian Redla9351792012-02-11 23:51:47 +00004640/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4641/// the ParenListExpr into a sequence of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004642ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004643Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4644 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004645 if (!E)
Richard Trieuba63ce62011-09-09 01:45:06 +00004646 return Owned(OrigExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004647
John McCalldadc5752010-08-24 06:29:42 +00004648 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004649
Nate Begeman5ec4b312009-08-10 23:49:36 +00004650 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004651 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4652 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004653
John McCallb268a282010-08-23 23:25:46 +00004654 if (Result.isInvalid()) return ExprError();
4655
4656 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004657}
4658
Sebastian Redla9351792012-02-11 23:51:47 +00004659ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4660 SourceLocation R,
4661 MultiExprArg Val) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00004662 assert(Val.data() != 0 && "ActOnParenOrParenListExpr() missing expr list");
4663 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004664 return Owned(expr);
4665}
4666
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004667/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004668/// constant and the other is not a pointer. Returns true if a diagnostic is
4669/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00004670bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004671 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004672 Expr *NullExpr = LHSExpr;
4673 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004674 Expr::NullPointerConstantKind NullKind =
4675 NullExpr->isNullPointerConstant(Context,
4676 Expr::NPC_ValueDependentIsNotNull);
4677
4678 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004679 NullExpr = RHSExpr;
4680 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004681 NullKind =
4682 NullExpr->isNullPointerConstant(Context,
4683 Expr::NPC_ValueDependentIsNotNull);
4684 }
4685
4686 if (NullKind == Expr::NPCK_NotNull)
4687 return false;
4688
David Blaikie1c7c8f72012-08-08 17:33:31 +00004689 if (NullKind == Expr::NPCK_ZeroExpression)
4690 return false;
4691
4692 if (NullKind == Expr::NPCK_ZeroLiteral) {
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004693 // In this case, check to make sure that we got here from a "NULL"
4694 // string in the source code.
4695 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004696 SourceLocation loc = NullExpr->getExprLoc();
4697 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004698 return false;
4699 }
4700
4701 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4702 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4703 << NonPointerExpr->getType() << DiagType
4704 << NonPointerExpr->getSourceRange();
4705 return true;
4706}
4707
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004708/// \brief Return false if the condition expression is valid, true otherwise.
4709static bool checkCondition(Sema &S, Expr *Cond) {
4710 QualType CondTy = Cond->getType();
4711
4712 // C99 6.5.15p2
4713 if (CondTy->isScalarType()) return false;
4714
4715 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004716 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004717 return false;
4718
4719 // Emit the proper error message.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004720 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004721 diag::err_typecheck_cond_expect_scalar :
4722 diag::err_typecheck_cond_expect_scalar_or_vector)
4723 << CondTy;
4724 return true;
4725}
4726
4727/// \brief Return false if the two expressions can be converted to a vector,
4728/// true otherwise
4729static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4730 ExprResult &RHS,
4731 QualType CondTy) {
4732 // Both operands should be of scalar type.
4733 if (!LHS.get()->getType()->isScalarType()) {
4734 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4735 << CondTy;
4736 return true;
4737 }
4738 if (!RHS.get()->getType()->isScalarType()) {
4739 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4740 << CondTy;
4741 return true;
4742 }
4743
4744 // Implicity convert these scalars to the type of the condition.
4745 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4746 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4747 return false;
4748}
4749
4750/// \brief Handle when one or both operands are void type.
4751static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4752 ExprResult &RHS) {
4753 Expr *LHSExpr = LHS.get();
4754 Expr *RHSExpr = RHS.get();
4755
4756 if (!LHSExpr->getType()->isVoidType())
4757 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4758 << RHSExpr->getSourceRange();
4759 if (!RHSExpr->getType()->isVoidType())
4760 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4761 << LHSExpr->getSourceRange();
4762 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4763 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4764 return S.Context.VoidTy;
4765}
4766
4767/// \brief Return false if the NullExpr can be promoted to PointerTy,
4768/// true otherwise.
4769static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4770 QualType PointerTy) {
4771 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4772 !NullExpr.get()->isNullPointerConstant(S.Context,
4773 Expr::NPC_ValueDependentIsNull))
4774 return true;
4775
4776 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4777 return false;
4778}
4779
4780/// \brief Checks compatibility between two pointers and return the resulting
4781/// type.
4782static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4783 ExprResult &RHS,
4784 SourceLocation Loc) {
4785 QualType LHSTy = LHS.get()->getType();
4786 QualType RHSTy = RHS.get()->getType();
4787
4788 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4789 // Two identical pointers types are always compatible.
4790 return LHSTy;
4791 }
4792
4793 QualType lhptee, rhptee;
4794
4795 // Get the pointee types.
John McCall9320b872011-09-09 05:25:32 +00004796 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4797 lhptee = LHSBTy->getPointeeType();
4798 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004799 } else {
John McCall9320b872011-09-09 05:25:32 +00004800 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4801 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004802 }
4803
Eli Friedman57a75392012-04-05 22:30:04 +00004804 // C99 6.5.15p6: If both operands are pointers to compatible types or to
4805 // differently qualified versions of compatible types, the result type is
4806 // a pointer to an appropriately qualified version of the composite
4807 // type.
4808
4809 // Only CVR-qualifiers exist in the standard, and the differently-qualified
4810 // clause doesn't make sense for our extensions. E.g. address space 2 should
4811 // be incompatible with address space 3: they may live on different devices or
4812 // anything.
4813 Qualifiers lhQual = lhptee.getQualifiers();
4814 Qualifiers rhQual = rhptee.getQualifiers();
4815
4816 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4817 lhQual.removeCVRQualifiers();
4818 rhQual.removeCVRQualifiers();
4819
4820 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4821 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4822
4823 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4824
4825 if (CompositeTy.isNull()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004826 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4827 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4828 << RHS.get()->getSourceRange();
4829 // In this situation, we assume void* type. No especially good
4830 // reason, but this is what gcc does, and we do have to pick
4831 // to get a consistent AST.
4832 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4833 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4834 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4835 return incompatTy;
4836 }
4837
4838 // The pointer types are compatible.
Eli Friedman57a75392012-04-05 22:30:04 +00004839 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4840 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004841
Eli Friedman57a75392012-04-05 22:30:04 +00004842 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4843 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4844 return ResultTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004845}
4846
4847/// \brief Return the resulting type when the operands are both block pointers.
4848static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4849 ExprResult &LHS,
4850 ExprResult &RHS,
4851 SourceLocation Loc) {
4852 QualType LHSTy = LHS.get()->getType();
4853 QualType RHSTy = RHS.get()->getType();
4854
4855 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4856 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4857 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4858 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4859 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4860 return destType;
4861 }
4862 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4863 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4864 << RHS.get()->getSourceRange();
4865 return QualType();
4866 }
4867
4868 // We have 2 block pointer types.
4869 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4870}
4871
4872/// \brief Return the resulting type when the operands are both pointers.
4873static QualType
4874checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4875 ExprResult &RHS,
4876 SourceLocation Loc) {
4877 // get the pointer types
4878 QualType LHSTy = LHS.get()->getType();
4879 QualType RHSTy = RHS.get()->getType();
4880
4881 // get the "pointed to" types
4882 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4883 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4884
4885 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4886 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4887 // Figure out necessary qualifiers (C99 6.5.15p6)
4888 QualType destPointee
4889 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4890 QualType destType = S.Context.getPointerType(destPointee);
4891 // Add qualifiers if necessary.
4892 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4893 // Promote to void*.
4894 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4895 return destType;
4896 }
4897 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4898 QualType destPointee
4899 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4900 QualType destType = S.Context.getPointerType(destPointee);
4901 // Add qualifiers if necessary.
4902 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4903 // Promote to void*.
4904 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4905 return destType;
4906 }
4907
4908 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4909}
4910
4911/// \brief Return false if the first expression is not an integer and the second
4912/// expression is not a pointer, true otherwise.
4913static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4914 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004915 bool IsIntFirstExpr) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004916 if (!PointerExpr->getType()->isPointerType() ||
4917 !Int.get()->getType()->isIntegerType())
4918 return false;
4919
Richard Trieuba63ce62011-09-09 01:45:06 +00004920 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4921 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004922
4923 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4924 << Expr1->getType() << Expr2->getType()
4925 << Expr1->getSourceRange() << Expr2->getSourceRange();
4926 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4927 CK_IntegralToPointer);
4928 return true;
4929}
4930
Richard Trieud33e46e2011-09-06 20:06:39 +00004931/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4932/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004933/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004934QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4935 ExprResult &RHS, ExprValueKind &VK,
4936 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004937 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004938
Richard Trieud33e46e2011-09-06 20:06:39 +00004939 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4940 if (!LHSResult.isUsable()) return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004941 LHS = LHSResult;
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004942
Richard Trieud33e46e2011-09-06 20:06:39 +00004943 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4944 if (!RHSResult.isUsable()) return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004945 RHS = RHSResult;
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004946
Sebastian Redl1a99f442009-04-16 17:51:27 +00004947 // C++ is sufficiently different to merit its own checker.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004948 if (getLangOpts().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004949 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004950
4951 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004952 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004953
John Wiegley01296292011-04-08 18:41:53 +00004954 Cond = UsualUnaryConversions(Cond.take());
4955 if (Cond.isInvalid())
4956 return QualType();
4957 LHS = UsualUnaryConversions(LHS.take());
4958 if (LHS.isInvalid())
4959 return QualType();
4960 RHS = UsualUnaryConversions(RHS.take());
4961 if (RHS.isInvalid())
4962 return QualType();
4963
4964 QualType CondTy = Cond.get()->getType();
4965 QualType LHSTy = LHS.get()->getType();
4966 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004967
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004968 // first, check the condition.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004969 if (checkCondition(*this, Cond.get()))
4970 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004971
Chris Lattnere2949f42008-01-06 22:42:25 +00004972 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004973 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004974 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004975
Nate Begemanabb5a732010-09-20 22:41:17 +00004976 // OpenCL: If the condition is a vector, and both operands are scalar,
4977 // attempt to implicity convert them to the vector type to act like the
4978 // built in select.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004979 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004980 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begemanabb5a732010-09-20 22:41:17 +00004981 return QualType();
Nate Begemanabb5a732010-09-20 22:41:17 +00004982
Chris Lattnere2949f42008-01-06 22:42:25 +00004983 // If both operands have arithmetic type, do the usual arithmetic conversions
4984 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004985 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4986 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004987 if (LHS.isInvalid() || RHS.isInvalid())
4988 return QualType();
4989 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004990 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004991
Chris Lattnere2949f42008-01-06 22:42:25 +00004992 // If both operands are the same structure or union type, the result is that
4993 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004994 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4995 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004996 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004997 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004998 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004999 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00005000 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005001 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005002
Chris Lattnere2949f42008-01-06 22:42:25 +00005003 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00005004 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00005005 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005006 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00005007 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005008
Steve Naroff039ad3c2008-01-08 01:11:38 +00005009 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5010 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005011 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5012 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005013
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005014 // All objective-c pointer type analysis is done here.
5015 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5016 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005017 if (LHS.isInvalid() || RHS.isInvalid())
5018 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005019 if (!compositeType.isNull())
5020 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005021
5022
Steve Naroff05efa972009-07-01 14:36:47 +00005023 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005024 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5025 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5026 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005027
Steve Naroff05efa972009-07-01 14:36:47 +00005028 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005029 if (LHSTy->isPointerType() && RHSTy->isPointerType())
5030 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5031 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00005032
John McCalle84af4e2010-11-13 01:35:44 +00005033 // GCC compatibility: soften pointer/integer mismatch. Note that
5034 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005035 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5036 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00005037 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005038 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5039 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00005040 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00005041
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005042 // Emit a better diagnostic if one of the expressions is a null pointer
5043 // constant and the other is not a pointer type. In this case, the user most
5044 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005045 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005046 return QualType();
5047
Chris Lattnere2949f42008-01-06 22:42:25 +00005048 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00005049 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00005050 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5051 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005052 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00005053}
5054
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005055/// FindCompositeObjCPointerType - Helper method to find composite type of
5056/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00005057QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00005058 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005059 QualType LHSTy = LHS.get()->getType();
5060 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005061
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005062 // Handle things like Class and struct objc_class*. Here we case the result
5063 // to the pseudo-builtin, because that will be implicitly cast back to the
5064 // redefinition type if an attempt is made to access its fields.
5065 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005066 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005067 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005068 return LHSTy;
5069 }
5070 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005071 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005072 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005073 return RHSTy;
5074 }
5075 // And the same for struct objc_object* / id
5076 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005077 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005078 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005079 return LHSTy;
5080 }
5081 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005082 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005083 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005084 return RHSTy;
5085 }
5086 // And the same for struct objc_selector* / SEL
5087 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00005088 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005089 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005090 return LHSTy;
5091 }
5092 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00005093 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005094 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005095 return RHSTy;
5096 }
5097 // Check constraints for Objective-C object pointers types.
5098 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005099
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005100 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5101 // Two identical object pointer types are always compatible.
5102 return LHSTy;
5103 }
John McCall9320b872011-09-09 05:25:32 +00005104 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5105 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005106 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005107
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005108 // If both operands are interfaces and either operand can be
5109 // assigned to the other, use that type as the composite
5110 // type. This allows
5111 // xxx ? (A*) a : (B*) b
5112 // where B is a subclass of A.
5113 //
5114 // Additionally, as for assignment, if either type is 'id'
5115 // allow silent coercion. Finally, if the types are
5116 // incompatible then make sure to use 'id' as the composite
5117 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005118
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005119 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5120 // It could return the composite type.
5121 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5122 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5123 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5124 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5125 } else if ((LHSTy->isObjCQualifiedIdType() ||
5126 RHSTy->isObjCQualifiedIdType()) &&
5127 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5128 // Need to handle "id<xx>" explicitly.
5129 // GCC allows qualified id and any Objective-C type to devolve to
5130 // id. Currently localizing to here until clear this should be
5131 // part of ObjCQualifiedIdTypesAreCompatible.
5132 compositeType = Context.getObjCIdType();
5133 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5134 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005135 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005136 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5137 ;
5138 else {
5139 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5140 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00005141 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005142 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00005143 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5144 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005145 return incompatTy;
5146 }
5147 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00005148 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5149 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005150 return compositeType;
5151 }
5152 // Check Objective-C object pointer types and 'void *'
5153 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005154 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00005155 // ARC forbids the implicit conversion of object pointers to 'void *',
5156 // so these types are not compatible.
5157 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5158 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5159 LHS = RHS = true;
5160 return QualType();
5161 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005162 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5163 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5164 QualType destPointee
5165 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5166 QualType destType = Context.getPointerType(destPointee);
5167 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005168 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005169 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005170 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005171 return destType;
5172 }
5173 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005174 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00005175 // ARC forbids the implicit conversion of object pointers to 'void *',
5176 // so these types are not compatible.
5177 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5178 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5179 LHS = RHS = true;
5180 return QualType();
5181 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005182 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5183 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5184 QualType destPointee
5185 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5186 QualType destType = Context.getPointerType(destPointee);
5187 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005188 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005189 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005190 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005191 return destType;
5192 }
5193 return QualType();
5194}
5195
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005196/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005197/// ParenRange in parentheses.
5198static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005199 const PartialDiagnostic &Note,
5200 SourceRange ParenRange) {
5201 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5202 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5203 EndLoc.isValid()) {
5204 Self.Diag(Loc, Note)
5205 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5206 << FixItHint::CreateInsertion(EndLoc, ")");
5207 } else {
5208 // We can't display the parentheses, so just show the bare note.
5209 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005210 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005211}
5212
5213static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5214 return Opc >= BO_Mul && Opc <= BO_Shr;
5215}
5216
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005217/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5218/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00005219/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5220/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005221static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00005222 Expr **RHSExprs) {
Hans Wennborgbe207b32011-09-12 12:07:30 +00005223 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5224 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005225 E = E->IgnoreConversionOperator();
Hans Wennborgbe207b32011-09-12 12:07:30 +00005226 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005227
5228 // Built-in binary operator.
5229 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5230 if (IsArithmeticOp(OP->getOpcode())) {
5231 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00005232 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005233 return true;
5234 }
5235 }
5236
5237 // Overloaded operator.
5238 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5239 if (Call->getNumArgs() != 2)
5240 return false;
5241
5242 // Make sure this is really a binary operator that is safe to pass into
5243 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5244 OverloadedOperatorKind OO = Call->getOperator();
5245 if (OO < OO_Plus || OO > OO_Arrow)
5246 return false;
5247
5248 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5249 if (IsArithmeticOp(OpKind)) {
5250 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00005251 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005252 return true;
5253 }
5254 }
5255
5256 return false;
5257}
5258
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005259static bool IsLogicOp(BinaryOperatorKind Opc) {
5260 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5261}
5262
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005263/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5264/// or is a logical expression such as (x==y) which has int type, but is
5265/// commonly interpreted as boolean.
5266static bool ExprLooksBoolean(Expr *E) {
5267 E = E->IgnoreParenImpCasts();
5268
5269 if (E->getType()->isBooleanType())
5270 return true;
5271 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5272 return IsLogicOp(OP->getOpcode());
5273 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5274 return OP->getOpcode() == UO_LNot;
5275
5276 return false;
5277}
5278
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005279/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5280/// and binary operator are mixed in a way that suggests the programmer assumed
5281/// the conditional operator has higher precedence, for example:
5282/// "int x = a + someBinaryCondition ? 1 : 2".
5283static void DiagnoseConditionalPrecedence(Sema &Self,
5284 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005285 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00005286 Expr *LHSExpr,
5287 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005288 BinaryOperatorKind CondOpcode;
5289 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005290
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005291 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005292 return;
5293 if (!ExprLooksBoolean(CondRHS))
5294 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005295
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005296 // The condition is an arithmetic binary expression, with a right-
5297 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005298
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005299 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005300 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005301 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005302
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005303 SuggestParentheses(Self, OpLoc,
5304 Self.PDiag(diag::note_precedence_conditional_silence)
5305 << BinaryOperator::getOpcodeStr(CondOpcode),
5306 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00005307
5308 SuggestParentheses(Self, OpLoc,
5309 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00005310 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005311}
5312
Steve Naroff83895f72007-09-16 03:34:24 +00005313/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005314/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005315ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005316 SourceLocation ColonLoc,
5317 Expr *CondExpr, Expr *LHSExpr,
5318 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005319 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5320 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005321 OpaqueValueExpr *opaqueValue = 0;
5322 Expr *commonExpr = 0;
5323 if (LHSExpr == 0) {
5324 commonExpr = CondExpr;
5325
5326 // We usually want to apply unary conversions *before* saving, except
5327 // in the special case of a C++ l-value conditional.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005328 if (!(getLangOpts().CPlusPlus
John McCallc07a0c72011-02-17 10:25:35 +00005329 && !commonExpr->isTypeDependent()
5330 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5331 && commonExpr->isGLValue()
5332 && commonExpr->isOrdinaryOrBitFieldObject()
5333 && RHSExpr->isOrdinaryOrBitFieldObject()
5334 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005335 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5336 if (commonRes.isInvalid())
5337 return ExprError();
5338 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00005339 }
5340
5341 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5342 commonExpr->getType(),
5343 commonExpr->getValueKind(),
Douglas Gregor2d5aea02012-02-23 22:17:26 +00005344 commonExpr->getObjectKind(),
5345 commonExpr);
John McCallc07a0c72011-02-17 10:25:35 +00005346 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005347 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005348
John McCall7decc9e2010-11-18 06:31:45 +00005349 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005350 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005351 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5352 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005353 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005354 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5355 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005356 return ExprError();
5357
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005358 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5359 RHS.get());
5360
John McCallc07a0c72011-02-17 10:25:35 +00005361 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005362 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5363 LHS.take(), ColonLoc,
5364 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005365
5366 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005367 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005368 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5369 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005370}
5371
John McCallaba90822011-01-31 23:13:11 +00005372// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005373// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005374// routine is it effectively iqnores the qualifiers on the top level pointee.
5375// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5376// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005377static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005378checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5379 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5380 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005381
Steve Naroff1f4d7272007-05-11 04:00:31 +00005382 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005383 const Type *lhptee, *rhptee;
5384 Qualifiers lhq, rhq;
Richard Trieua871b972011-09-06 20:21:22 +00005385 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5386 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005387
John McCallaba90822011-01-31 23:13:11 +00005388 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005389
5390 // C99 6.5.16.1p1: This following citation is common to constraints
5391 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5392 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005393 Qualifiers lq;
5394
John McCall31168b02011-06-15 23:02:42 +00005395 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5396 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5397 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5398 // Ignore lifetime for further calculation.
5399 lhq.removeObjCLifetime();
5400 rhq.removeObjCLifetime();
5401 }
5402
John McCall4fff8f62011-02-01 00:10:29 +00005403 if (!lhq.compatiblyIncludes(rhq)) {
5404 // Treat address-space mismatches as fatal. TODO: address subspaces
5405 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5406 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5407
John McCall31168b02011-06-15 23:02:42 +00005408 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005409 // and from void*.
John McCall18ce25e2012-02-08 00:46:36 +00005410 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCall31168b02011-06-15 23:02:42 +00005411 .compatiblyIncludes(
John McCall18ce25e2012-02-08 00:46:36 +00005412 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall78535952011-03-26 02:56:45 +00005413 && (lhptee->isVoidType() || rhptee->isVoidType()))
5414 ; // keep old
5415
John McCall31168b02011-06-15 23:02:42 +00005416 // Treat lifetime mismatches as fatal.
5417 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5418 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5419
John McCall4fff8f62011-02-01 00:10:29 +00005420 // For GCC compatibility, other qualifier mismatches are treated
5421 // as still compatible in C.
5422 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5423 }
Steve Naroff3f597292007-05-11 22:18:03 +00005424
Mike Stump4e1f26a2009-02-19 03:04:26 +00005425 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5426 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005427 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005428 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005429 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005430 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005431
Chris Lattner0a788432008-01-03 22:56:36 +00005432 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005433 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005434 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005435 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005436
Chris Lattner0a788432008-01-03 22:56:36 +00005437 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005438 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005439 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005440
5441 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005442 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005443 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005444 }
John McCall4fff8f62011-02-01 00:10:29 +00005445
Mike Stump4e1f26a2009-02-19 03:04:26 +00005446 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005447 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005448 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5449 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005450 // Check if the pointee types are compatible ignoring the sign.
5451 // We explicitly check for char so that we catch "char" vs
5452 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005453 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005454 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005455 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005456 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005457
Chris Lattnerec3a1562009-10-17 20:33:28 +00005458 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005459 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005460 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005461 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005462
John McCall4fff8f62011-02-01 00:10:29 +00005463 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005464 // Types are compatible ignoring the sign. Qualifier incompatibility
5465 // takes priority over sign incompatibility because the sign
5466 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005467 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005468 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005469
John McCallaba90822011-01-31 23:13:11 +00005470 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005471 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005472
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005473 // If we are a multi-level pointer, it's possible that our issue is simply
5474 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5475 // the eventual target type is the same and the pointers have the same
5476 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005477 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005478 do {
John McCall4fff8f62011-02-01 00:10:29 +00005479 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5480 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005481 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005482
John McCall4fff8f62011-02-01 00:10:29 +00005483 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005484 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005485 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005486
Eli Friedman80160bd2009-03-22 23:59:44 +00005487 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005488 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005489 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00005490 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005491 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5492 return Sema::IncompatiblePointer;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005493 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005494}
5495
John McCallaba90822011-01-31 23:13:11 +00005496/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005497/// block pointer types are compatible or whether a block and normal pointer
5498/// are compatible. It is more restrict than comparing two function pointer
5499// types.
John McCallaba90822011-01-31 23:13:11 +00005500static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005501checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5502 QualType RHSType) {
5503 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5504 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005505
Steve Naroff081c7422008-09-04 15:10:53 +00005506 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005507
Steve Naroff081c7422008-09-04 15:10:53 +00005508 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00005509 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5510 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005511
John McCallaba90822011-01-31 23:13:11 +00005512 // In C++, the types have to match exactly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005513 if (S.getLangOpts().CPlusPlus)
John McCallaba90822011-01-31 23:13:11 +00005514 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005515
John McCallaba90822011-01-31 23:13:11 +00005516 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005517
Steve Naroff081c7422008-09-04 15:10:53 +00005518 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005519 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5520 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005521
Richard Trieua871b972011-09-06 20:21:22 +00005522 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005523 return Sema::IncompatibleBlockPointer;
5524
Steve Naroff081c7422008-09-04 15:10:53 +00005525 return ConvTy;
5526}
5527
John McCallaba90822011-01-31 23:13:11 +00005528/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005529/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005530static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005531checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5532 QualType RHSType) {
5533 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5534 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005535
Richard Trieua871b972011-09-06 20:21:22 +00005536 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005537 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00005538 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5539 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005540 return Sema::IncompatiblePointer;
5541 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005542 }
Richard Trieua871b972011-09-06 20:21:22 +00005543 if (RHSType->isObjCBuiltinType()) {
Richard Trieua871b972011-09-06 20:21:22 +00005544 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5545 !LHSType->isObjCQualifiedClassType())
Fariborz Jahaniand923eb02011-09-15 20:40:18 +00005546 return Sema::IncompatiblePointer;
John McCallaba90822011-01-31 23:13:11 +00005547 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005548 }
Richard Trieua871b972011-09-06 20:21:22 +00005549 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5550 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005551
Fariborz Jahaniane74d47e2012-01-12 22:12:08 +00005552 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5553 // make an exception for id<P>
5554 !LHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005555 return Sema::CompatiblePointerDiscardsQualifiers;
5556
Richard Trieua871b972011-09-06 20:21:22 +00005557 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005558 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00005559 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005560 return Sema::IncompatibleObjCQualifiedId;
5561 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005562}
5563
John McCall29600e12010-11-16 02:32:08 +00005564Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005565Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00005566 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00005567 // Fake up an opaque expression. We don't actually care about what
5568 // cast operations are required, so if CheckAssignmentConstraints
5569 // adds casts to this they'll be wasted, but fortunately that doesn't
5570 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00005571 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5572 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00005573 CastKind K = CK_Invalid;
5574
Richard Trieua871b972011-09-06 20:21:22 +00005575 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall29600e12010-11-16 02:32:08 +00005576}
5577
Mike Stump4e1f26a2009-02-19 03:04:26 +00005578/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5579/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005580/// pointers. Here are some objectionable examples that GCC considers warnings:
5581///
5582/// int a, *pint;
5583/// short *pshort;
5584/// struct foo *pfoo;
5585///
5586/// pint = pshort; // warning: assignment from incompatible pointer type
5587/// a = pint; // warning: assignment makes integer from pointer without a cast
5588/// pint = a; // warning: assignment makes pointer from integer without a cast
5589/// pint = pfoo; // warning: assignment from incompatible pointer type
5590///
5591/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005592/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005593///
John McCall8cb679e2010-11-15 09:13:47 +00005594/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005595Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00005596Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCall8cb679e2010-11-15 09:13:47 +00005597 CastKind &Kind) {
Richard Trieude4958f2011-09-06 20:30:53 +00005598 QualType RHSType = RHS.get()->getType();
5599 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00005600
Chris Lattnera52c2f22008-01-04 23:18:45 +00005601 // Get canonical types. We're not formatting these types, just comparing
5602 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00005603 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5604 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005605
Eli Friedman0dfb8892011-10-06 23:00:33 +00005606
John McCalle5255932011-01-31 22:28:28 +00005607 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00005608 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00005609 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005610 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005611 }
5612
Eli Friedman93ee5ca2012-06-16 02:19:17 +00005613 // If we have an atomic type, try a non-atomic assignment, then just add an
5614 // atomic qualification step.
David Chisnallfa35df62012-01-16 17:27:18 +00005615 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman93ee5ca2012-06-16 02:19:17 +00005616 Sema::AssignConvertType result =
5617 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5618 if (result != Compatible)
5619 return result;
5620 if (Kind != CK_NoOp)
5621 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5622 Kind = CK_NonAtomicToAtomic;
5623 return Compatible;
David Chisnallfa35df62012-01-16 17:27:18 +00005624 }
5625
Douglas Gregor6b754842008-10-28 00:22:11 +00005626 // If the left-hand side is a reference type, then we are in a
5627 // (rare!) case where we've allowed the use of references in C,
5628 // e.g., as a parameter type in a built-in function. In this case,
5629 // just make sure that the type referenced is compatible with the
5630 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00005631 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00005632 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00005633 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5634 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005635 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005636 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005637 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005638 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005639 }
John McCalle5255932011-01-31 22:28:28 +00005640
Nate Begemanbd956c42009-06-28 02:36:38 +00005641 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5642 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005643 if (LHSType->isExtVectorType()) {
5644 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005645 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00005646 if (RHSType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005647 // CK_VectorSplat does T -> vector T, so first cast to the
5648 // element type.
Richard Trieude4958f2011-09-06 20:30:53 +00005649 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5650 if (elType != RHSType) {
John McCall9776e432011-10-06 23:25:11 +00005651 Kind = PrepareScalarCast(RHS, elType);
Richard Trieude4958f2011-09-06 20:30:53 +00005652 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005653 }
5654 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005655 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005656 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005657 }
Mike Stump11289f42009-09-09 15:08:12 +00005658
John McCalle5255932011-01-31 22:28:28 +00005659 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005660 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5661 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005662 // Allow assignments of an AltiVec vector type to an equivalent GCC
5663 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00005664 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00005665 Kind = CK_BitCast;
5666 return Compatible;
5667 }
5668
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005669 // If we are allowing lax vector conversions, and LHS and RHS are both
5670 // vectors, the total size only needs to be the same. This is a bitcast;
5671 // no bits are changed but the result type is different.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005672 if (getLangOpts().LaxVectorConversions &&
Richard Trieude4958f2011-09-06 20:30:53 +00005673 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall3065d042010-11-15 10:08:00 +00005674 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005675 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005676 }
Chris Lattner881a2122008-01-04 23:32:24 +00005677 }
5678 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005679 }
Eli Friedman3360d892008-05-30 18:07:22 +00005680
John McCalle5255932011-01-31 22:28:28 +00005681 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00005682 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00005683 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCall9776e432011-10-06 23:25:11 +00005684 Kind = PrepareScalarCast(RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005685 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005686 }
Eli Friedman3360d892008-05-30 18:07:22 +00005687
John McCalle5255932011-01-31 22:28:28 +00005688 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005689 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005690 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005691 if (isa<PointerType>(RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005692 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005693 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005694 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005695
John McCalle5255932011-01-31 22:28:28 +00005696 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005697 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00005698 Kind = CK_IntegralToPointer; // FIXME: null?
5699 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005700 }
John McCalle5255932011-01-31 22:28:28 +00005701
5702 // C pointers are not compatible with ObjC object pointers,
5703 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005704 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005705 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00005706 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall9320b872011-09-09 05:25:32 +00005707 Kind = CK_BitCast;
John McCalle5255932011-01-31 22:28:28 +00005708 return Compatible;
5709 }
5710
5711 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005712 if (RHSType->isObjCClassType() &&
5713 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005714 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00005715 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005716 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005717 }
Douglas Gregor486b74e2011-09-27 16:10:05 +00005718
John McCalle5255932011-01-31 22:28:28 +00005719 Kind = CK_BitCast;
5720 return IncompatiblePointer;
5721 }
5722
5723 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00005724 if (RHSType->getAs<BlockPointerType>()) {
5725 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00005726 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005727 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005728 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005729 }
John McCalle5255932011-01-31 22:28:28 +00005730
Steve Naroff081c7422008-09-04 15:10:53 +00005731 return Incompatible;
5732 }
5733
John McCalle5255932011-01-31 22:28:28 +00005734 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005735 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005736 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005737 if (RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00005738 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005739 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00005740 }
5741
5742 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005743 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005744 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005745 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005746 }
5747
John McCalle5255932011-01-31 22:28:28 +00005748 // id -> T^
David Blaikiebbafb8a2012-03-11 07:00:24 +00005749 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00005750 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005751 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005752 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005753
John McCalle5255932011-01-31 22:28:28 +00005754 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005755 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005756 if (RHSPT->getPointeeType()->isVoidType()) {
5757 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005758 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005759 }
John McCall8cb679e2010-11-15 09:13:47 +00005760
Chris Lattnera52c2f22008-01-04 23:18:45 +00005761 return Incompatible;
5762 }
5763
John McCalle5255932011-01-31 22:28:28 +00005764 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005765 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005766 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00005767 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00005768 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005769 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00005770 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikiebbafb8a2012-03-11 07:00:24 +00005771 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005772 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00005773 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005774 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005775 return result;
John McCalle5255932011-01-31 22:28:28 +00005776 }
5777
5778 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005779 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005780 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005781 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005782 }
5783
John McCalle5255932011-01-31 22:28:28 +00005784 // In general, C pointers are not compatible with ObjC object pointers,
5785 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005786 if (isa<PointerType>(RHSType)) {
John McCall9320b872011-09-09 05:25:32 +00005787 Kind = CK_CPointerToObjCPointerCast;
5788
John McCalle5255932011-01-31 22:28:28 +00005789 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00005790 if (RHSType->isVoidPointerType()) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005791 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005792 }
5793
5794 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005795 if (LHSType->isObjCClassType() &&
5796 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005797 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00005798 return Compatible;
5799 }
5800
Steve Naroffaccc4882009-07-20 17:56:53 +00005801 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005802 }
John McCalle5255932011-01-31 22:28:28 +00005803
5804 // T^ -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005805 if (RHSType->isBlockPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00005806 maybeExtendBlockObject(*this, RHS);
John McCall9320b872011-09-09 05:25:32 +00005807 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005808 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005809 }
5810
Steve Naroff7cae42b2009-07-10 23:34:53 +00005811 return Incompatible;
5812 }
John McCalle5255932011-01-31 22:28:28 +00005813
5814 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005815 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005816 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005817 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005818 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005819 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005820 }
Eli Friedman3360d892008-05-30 18:07:22 +00005821
John McCalle5255932011-01-31 22:28:28 +00005822 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005823 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005824 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005825 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005826 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005827
Chris Lattnera52c2f22008-01-04 23:18:45 +00005828 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005829 }
John McCalle5255932011-01-31 22:28:28 +00005830
5831 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005832 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005833 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005834 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005835 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005836 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005837 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005838
John McCalle5255932011-01-31 22:28:28 +00005839 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005840 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005841 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005842 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005843 }
5844
Steve Naroff7cae42b2009-07-10 23:34:53 +00005845 return Incompatible;
5846 }
Eli Friedman3360d892008-05-30 18:07:22 +00005847
John McCalle5255932011-01-31 22:28:28 +00005848 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00005849 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5850 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005851 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005852 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005853 }
Bill Wendling216423b2007-05-30 06:30:29 +00005854 }
John McCalle5255932011-01-31 22:28:28 +00005855
Steve Naroff98cf3e92007-06-06 18:38:38 +00005856 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005857}
5858
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005859/// \brief Constructs a transparent union from an expression that is
5860/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005861static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5862 ExprResult &EResult, QualType UnionType,
5863 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005864 // Build an initializer list that designates the appropriate member
5865 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005866 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005867 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00005868 E, SourceLocation());
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005869 Initializer->setType(UnionType);
5870 Initializer->setInitializedFieldInUnion(Field);
5871
5872 // Build a compound literal constructing a value of the transparent
5873 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005874 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005875 EResult = S.Owned(
5876 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5877 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005878}
5879
5880Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005881Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00005882 ExprResult &RHS) {
5883 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005884
Mike Stump11289f42009-09-09 15:08:12 +00005885 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005886 // transparent_union GCC extension.
5887 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005888 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005889 return Incompatible;
5890
5891 // The field to initialize within the transparent union.
5892 RecordDecl *UD = UT->getDecl();
5893 FieldDecl *InitField = 0;
5894 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005895 for (RecordDecl::field_iterator it = UD->field_begin(),
5896 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005897 it != itend; ++it) {
5898 if (it->getType()->isPointerType()) {
5899 // If the transparent union contains a pointer type, we allow:
5900 // 1) void pointer
5901 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00005902 if (RHSType->isPointerType())
John McCall9320b872011-09-09 05:25:32 +00005903 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieueb299142011-09-06 20:40:12 +00005904 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie40ed2972012-06-06 20:45:41 +00005905 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005906 break;
5907 }
Mike Stump11289f42009-09-09 15:08:12 +00005908
Richard Trieueb299142011-09-06 20:40:12 +00005909 if (RHS.get()->isNullPointerConstant(Context,
5910 Expr::NPC_ValueDependentIsNull)) {
5911 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5912 CK_NullToPointer);
David Blaikie40ed2972012-06-06 20:45:41 +00005913 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005914 break;
5915 }
5916 }
5917
John McCall8cb679e2010-11-15 09:13:47 +00005918 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00005919 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005920 == Compatible) {
Richard Trieueb299142011-09-06 20:40:12 +00005921 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie40ed2972012-06-06 20:45:41 +00005922 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005923 break;
5924 }
5925 }
5926
5927 if (!InitField)
5928 return Incompatible;
5929
Richard Trieueb299142011-09-06 20:40:12 +00005930 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005931 return Compatible;
5932}
5933
Chris Lattner9bad62c2008-01-04 18:04:52 +00005934Sema::AssignConvertType
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005935Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5936 bool Diagnose) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005937 if (getLangOpts().CPlusPlus) {
Eli Friedman0dfb8892011-10-06 23:00:33 +00005938 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005939 // C++ 5.17p3: If the left operand is not of class type, the
5940 // expression is implicitly converted (C++ 4) to the
5941 // cv-unqualified type of the left operand.
Sebastian Redlcc152642011-10-16 18:19:06 +00005942 ExprResult Res;
5943 if (Diagnose) {
5944 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5945 AA_Assigning);
5946 } else {
5947 ImplicitConversionSequence ICS =
5948 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5949 /*SuppressUserConversions=*/false,
5950 /*AllowExplicit=*/false,
5951 /*InOverloadResolution=*/false,
5952 /*CStyle=*/false,
5953 /*AllowObjCWritebackConversion=*/false);
5954 if (ICS.isFailure())
5955 return Incompatible;
5956 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5957 ICS, AA_Assigning);
5958 }
John Wiegley01296292011-04-08 18:41:53 +00005959 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005960 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005961 Sema::AssignConvertType result = Compatible;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005962 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieueb299142011-09-06 20:40:12 +00005963 !CheckObjCARCUnavailableWeakConversion(LHSType,
5964 RHS.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005965 result = IncompatibleObjCWeakRef;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005966 RHS = Res;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005967 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005968 }
5969
5970 // FIXME: Currently, we fall through and treat C++ classes like C
5971 // structures.
Eli Friedman0dfb8892011-10-06 23:00:33 +00005972 // FIXME: We also fall through for atomics; not sure what should
5973 // happen there, though.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005974 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005975
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005976 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5977 // a null pointer constant.
Richard Trieueb299142011-09-06 20:40:12 +00005978 if ((LHSType->isPointerType() ||
5979 LHSType->isObjCObjectPointerType() ||
5980 LHSType->isBlockPointerType())
5981 && RHS.get()->isNullPointerConstant(Context,
5982 Expr::NPC_ValueDependentIsNull)) {
5983 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005984 return Compatible;
5985 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005986
Chris Lattnere6dcd502007-10-16 02:55:40 +00005987 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005988 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005989 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005990 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005991 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005992 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00005993 if (!LHSType->isReferenceType()) {
5994 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5995 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005996 return Incompatible;
5997 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005998
John McCall8cb679e2010-11-15 09:13:47 +00005999 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006000 Sema::AssignConvertType result =
Richard Trieueb299142011-09-06 20:40:12 +00006001 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006002
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006003 // C99 6.5.16.1p2: The value of the right operand is converted to the
6004 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00006005 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6006 // so that we can use references in built-in functions even in C.
6007 // The getNonReferenceType() call makes sure that the resulting expression
6008 // does not have reference type.
Richard Trieueb299142011-09-06 20:40:12 +00006009 if (result != Incompatible && RHS.get()->getType() != LHSType)
6010 RHS = ImpCastExprToType(RHS.take(),
6011 LHSType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006012 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006013}
6014
Richard Trieueb299142011-09-06 20:40:12 +00006015QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6016 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006017 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00006018 << LHS.get()->getType() << RHS.get()->getType()
6019 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00006020 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00006021}
6022
Richard Trieu859d23f2011-09-06 21:01:04 +00006023QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006024 SourceLocation Loc, bool IsCompAssign) {
Richard Smith508ebf32011-10-28 03:31:48 +00006025 if (!IsCompAssign) {
6026 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6027 if (LHS.isInvalid())
6028 return QualType();
6029 }
6030 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6031 if (RHS.isInvalid())
6032 return QualType();
6033
Mike Stump4e1f26a2009-02-19 03:04:26 +00006034 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006035 // For example, "const float" and "float" are equivalent.
Richard Trieu859d23f2011-09-06 21:01:04 +00006036 QualType LHSType =
6037 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6038 QualType RHSType =
6039 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006040
Nate Begeman191a6b12008-07-14 18:02:46 +00006041 // If the vector types are identical, return.
Richard Trieu859d23f2011-09-06 21:01:04 +00006042 if (LHSType == RHSType)
6043 return LHSType;
Nate Begeman330aaa72007-12-30 02:59:45 +00006044
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006045 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu859d23f2011-09-06 21:01:04 +00006046 if (LHSType->isVectorType() && RHSType->isVectorType() &&
6047 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6048 if (LHSType->isExtVectorType()) {
6049 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6050 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00006051 }
6052
Richard Trieuba63ce62011-09-09 01:45:06 +00006053 if (!IsCompAssign)
Richard Trieu859d23f2011-09-06 21:01:04 +00006054 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6055 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006056 }
6057
David Blaikiebbafb8a2012-03-11 07:00:24 +00006058 if (getLangOpts().LaxVectorConversions &&
Richard Trieu859d23f2011-09-06 21:01:04 +00006059 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00006060 // If we are allowing lax vector conversions, and LHS and RHS are both
6061 // vectors, the total size only needs to be the same. This is a
6062 // bitcast; no bits are changed but the result type is different.
6063 // FIXME: Should we really be allowing this?
Richard Trieu859d23f2011-09-06 21:01:04 +00006064 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6065 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00006066 }
6067
Nate Begemanbd956c42009-06-28 02:36:38 +00006068 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6069 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6070 bool swapped = false;
Richard Trieuba63ce62011-09-09 01:45:06 +00006071 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006072 swapped = true;
Richard Trieu859d23f2011-09-06 21:01:04 +00006073 std::swap(RHS, LHS);
6074 std::swap(RHSType, LHSType);
Nate Begemanbd956c42009-06-28 02:36:38 +00006075 }
Mike Stump11289f42009-09-09 15:08:12 +00006076
Nate Begeman886448d2009-06-28 19:12:57 +00006077 // Handle the case of an ext vector and scalar.
Richard Trieu859d23f2011-09-06 21:01:04 +00006078 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006079 QualType EltTy = LV->getElementType();
Richard Trieu859d23f2011-09-06 21:01:04 +00006080 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6081 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00006082 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00006083 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00006084 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00006085 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6086 if (swapped) std::swap(RHS, LHS);
6087 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00006088 }
6089 }
Richard Trieu859d23f2011-09-06 21:01:04 +00006090 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6091 RHSType->isRealFloatingType()) {
6092 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00006093 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00006094 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00006095 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00006096 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6097 if (swapped) std::swap(RHS, LHS);
6098 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00006099 }
Nate Begeman330aaa72007-12-30 02:59:45 +00006100 }
6101 }
Mike Stump11289f42009-09-09 15:08:12 +00006102
Nate Begeman886448d2009-06-28 19:12:57 +00006103 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu859d23f2011-09-06 21:01:04 +00006104 if (swapped) std::swap(RHS, LHS);
Chris Lattner377d1f82008-11-18 22:52:51 +00006105 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu859d23f2011-09-06 21:01:04 +00006106 << LHS.get()->getType() << RHS.get()->getType()
6107 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00006108 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00006109}
6110
Richard Trieuf8916e12011-09-16 00:53:10 +00006111// checkArithmeticNull - Detect when a NULL constant is used improperly in an
6112// expression. These are mainly cases where the null pointer is used as an
6113// integer instead of a pointer.
6114static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6115 SourceLocation Loc, bool IsCompare) {
6116 // The canonical way to check for a GNU null is with isNullPointerConstant,
6117 // but we use a bit of a hack here for speed; this is a relatively
6118 // hot path, and isNullPointerConstant is slow.
6119 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6120 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6121
6122 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6123
6124 // Avoid analyzing cases where the result will either be invalid (and
6125 // diagnosed as such) or entirely valid and not something to warn about.
6126 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6127 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6128 return;
6129
6130 // Comparison operations would not make sense with a null pointer no matter
6131 // what the other expression is.
6132 if (!IsCompare) {
6133 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6134 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6135 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6136 return;
6137 }
6138
6139 // The rest of the operations only make sense with a null pointer
6140 // if the other expression is a pointer.
6141 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6142 NonNullType->canDecayToPointerType())
6143 return;
6144
6145 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6146 << LHSNull /* LHS is NULL */ << NonNullType
6147 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6148}
6149
Richard Trieu859d23f2011-09-06 21:01:04 +00006150QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006151 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006152 bool IsCompAssign, bool IsDiv) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006153 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6154
Richard Trieu859d23f2011-09-06 21:01:04 +00006155 if (LHS.get()->getType()->isVectorType() ||
6156 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006157 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006158
Richard Trieuba63ce62011-09-09 01:45:06 +00006159 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006160 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006161 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006162
David Chisnallfa35df62012-01-16 17:27:18 +00006163
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006164 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu859d23f2011-09-06 21:01:04 +00006165 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006166
Chris Lattnerfaa54172010-01-12 21:23:57 +00006167 // Check for division by zero.
Richard Trieuba63ce62011-09-09 01:45:06 +00006168 if (IsDiv &&
Richard Trieu859d23f2011-09-06 21:01:04 +00006169 RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00006170 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00006171 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6172 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006173
Chris Lattnerfaa54172010-01-12 21:23:57 +00006174 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006175}
6176
Chris Lattnerfaa54172010-01-12 21:23:57 +00006177QualType Sema::CheckRemainderOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00006178 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006179 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6180
Richard Trieu859d23f2011-09-06 21:01:04 +00006181 if (LHS.get()->getType()->isVectorType() ||
6182 RHS.get()->getType()->isVectorType()) {
6183 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6184 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00006185 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006186 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006187 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006188
Richard Trieuba63ce62011-09-09 01:45:06 +00006189 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006190 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006191 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006192
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006193 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu859d23f2011-09-06 21:01:04 +00006194 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006195
Chris Lattnerfaa54172010-01-12 21:23:57 +00006196 // Check for remainder by zero.
Richard Trieu859d23f2011-09-06 21:01:04 +00006197 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00006198 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00006199 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6200 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006201
Chris Lattnerfaa54172010-01-12 21:23:57 +00006202 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006203}
6204
Chandler Carruthc9332212011-06-27 08:02:19 +00006205/// \brief Diagnose invalid arithmetic on two void pointers.
6206static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006207 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006208 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006209 ? diag::err_typecheck_pointer_arith_void_type
6210 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006211 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6212 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00006213}
6214
6215/// \brief Diagnose invalid arithmetic on a void pointer.
6216static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6217 Expr *Pointer) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006218 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006219 ? diag::err_typecheck_pointer_arith_void_type
6220 : diag::ext_gnu_void_ptr)
6221 << 0 /* one pointer */ << Pointer->getSourceRange();
6222}
6223
6224/// \brief Diagnose invalid arithmetic on two function pointers.
6225static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6226 Expr *LHS, Expr *RHS) {
6227 assert(LHS->getType()->isAnyPointerType());
6228 assert(RHS->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006229 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006230 ? diag::err_typecheck_pointer_arith_function_type
6231 : diag::ext_gnu_ptr_func_arith)
6232 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6233 // We only show the second type if it differs from the first.
6234 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6235 RHS->getType())
6236 << RHS->getType()->getPointeeType()
6237 << LHS->getSourceRange() << RHS->getSourceRange();
6238}
6239
6240/// \brief Diagnose invalid arithmetic on a function pointer.
6241static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6242 Expr *Pointer) {
6243 assert(Pointer->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006244 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006245 ? diag::err_typecheck_pointer_arith_function_type
6246 : diag::ext_gnu_ptr_func_arith)
6247 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6248 << 0 /* one pointer, so only one type */
6249 << Pointer->getSourceRange();
6250}
6251
Richard Trieu993f3ab2011-09-12 18:08:02 +00006252/// \brief Emit error if Operand is incomplete pointer type
Richard Trieuaba22802011-09-02 02:15:37 +00006253///
6254/// \returns True if pointer has incomplete type
6255static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6256 Expr *Operand) {
John McCallf2538342012-07-31 05:14:30 +00006257 assert(Operand->getType()->isAnyPointerType() &&
6258 !Operand->getType()->isDependentType());
6259 QualType PointeeTy = Operand->getType()->getPointeeType();
6260 return S.RequireCompleteType(Loc, PointeeTy,
6261 diag::err_typecheck_arithmetic_incomplete_type,
6262 PointeeTy, Operand->getSourceRange());
Richard Trieuaba22802011-09-02 02:15:37 +00006263}
6264
Chandler Carruthc9332212011-06-27 08:02:19 +00006265/// \brief Check the validity of an arithmetic pointer operand.
6266///
6267/// If the operand has pointer type, this code will check for pointer types
6268/// which are invalid in arithmetic operations. These will be diagnosed
6269/// appropriately, including whether or not the use is supported as an
6270/// extension.
6271///
6272/// \returns True when the operand is valid to use (even if as an extension).
6273static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6274 Expr *Operand) {
6275 if (!Operand->getType()->isAnyPointerType()) return true;
6276
6277 QualType PointeeTy = Operand->getType()->getPointeeType();
6278 if (PointeeTy->isVoidType()) {
6279 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00006280 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006281 }
6282 if (PointeeTy->isFunctionType()) {
6283 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00006284 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006285 }
6286
Richard Trieuaba22802011-09-02 02:15:37 +00006287 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00006288
6289 return true;
6290}
6291
6292/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6293/// operands.
6294///
6295/// This routine will diagnose any invalid arithmetic on pointer operands much
6296/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6297/// for emitting a single diagnostic even for operations where both LHS and RHS
6298/// are (potentially problematic) pointers.
6299///
6300/// \returns True when the operand is valid to use (even if as an extension).
6301static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006302 Expr *LHSExpr, Expr *RHSExpr) {
6303 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6304 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006305 if (!isLHSPointer && !isRHSPointer) return true;
6306
6307 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00006308 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6309 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006310
6311 // Check for arithmetic on pointers to incomplete types.
6312 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6313 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6314 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006315 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6316 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6317 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006318
David Blaikiebbafb8a2012-03-11 07:00:24 +00006319 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006320 }
6321
6322 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6323 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6324 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006325 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6326 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6327 RHSExpr);
6328 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006329
David Blaikiebbafb8a2012-03-11 07:00:24 +00006330 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006331 }
6332
John McCallf2538342012-07-31 05:14:30 +00006333 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6334 return false;
6335 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6336 return false;
Richard Trieuaba22802011-09-02 02:15:37 +00006337
Chandler Carruthc9332212011-06-27 08:02:19 +00006338 return true;
6339}
6340
Nico Weberccec40d2012-03-02 22:01:22 +00006341/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6342/// literal.
6343static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6344 Expr *LHSExpr, Expr *RHSExpr) {
6345 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6346 Expr* IndexExpr = RHSExpr;
6347 if (!StrExpr) {
6348 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6349 IndexExpr = LHSExpr;
6350 }
6351
6352 bool IsStringPlusInt = StrExpr &&
6353 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6354 if (!IsStringPlusInt)
6355 return;
6356
6357 llvm::APSInt index;
6358 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6359 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6360 if (index.isNonNegative() &&
6361 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6362 index.isUnsigned()))
6363 return;
6364 }
6365
6366 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6367 Self.Diag(OpLoc, diag::warn_string_plus_int)
6368 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6369
6370 // Only print a fixit for "str" + int, not for int + "str".
6371 if (IndexExpr == RHSExpr) {
6372 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6373 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6374 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6375 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6376 << FixItHint::CreateInsertion(EndLoc, "]");
6377 } else
6378 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6379}
6380
Richard Trieu993f3ab2011-09-12 18:08:02 +00006381/// \brief Emit error when two pointers are incompatible.
Richard Trieub10c6312011-09-01 22:53:23 +00006382static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006383 Expr *LHSExpr, Expr *RHSExpr) {
6384 assert(LHSExpr->getType()->isAnyPointerType());
6385 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00006386 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006387 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6388 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00006389}
6390
Chris Lattnerfaa54172010-01-12 21:23:57 +00006391QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weberccec40d2012-03-02 22:01:22 +00006392 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6393 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006394 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6395
Richard Trieu4ae7e972011-09-06 21:13:51 +00006396 if (LHS.get()->getType()->isVectorType() ||
6397 RHS.get()->getType()->isVectorType()) {
6398 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006399 if (CompLHSTy) *CompLHSTy = compType;
6400 return compType;
6401 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006402
Richard Trieu4ae7e972011-09-06 21:13:51 +00006403 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6404 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006405 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006406
Nico Weberccec40d2012-03-02 22:01:22 +00006407 // Diagnose "string literal" '+' int.
6408 if (Opc == BO_Add)
6409 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6410
Steve Naroffe4718892007-04-27 18:30:00 +00006411 // handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006412 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006413 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006414 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006415 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006416
John McCallf2538342012-07-31 05:14:30 +00006417 // Type-checking. Ultimately the pointer's going to be in PExp;
6418 // note that we bias towards the LHS being the pointer.
6419 Expr *PExp = LHS.get(), *IExp = RHS.get();
Eli Friedman8e122982008-05-18 18:08:51 +00006420
John McCallf2538342012-07-31 05:14:30 +00006421 bool isObjCPointer;
6422 if (PExp->getType()->isPointerType()) {
6423 isObjCPointer = false;
6424 } else if (PExp->getType()->isObjCObjectPointerType()) {
6425 isObjCPointer = true;
6426 } else {
6427 std::swap(PExp, IExp);
6428 if (PExp->getType()->isPointerType()) {
6429 isObjCPointer = false;
6430 } else if (PExp->getType()->isObjCObjectPointerType()) {
6431 isObjCPointer = true;
6432 } else {
6433 return InvalidOperands(Loc, LHS, RHS);
6434 }
6435 }
6436 assert(PExp->getType()->isAnyPointerType());
Chandler Carruthc9332212011-06-27 08:02:19 +00006437
Richard Trieub420bca2011-09-12 18:37:54 +00006438 if (!IExp->getType()->isIntegerType())
6439 return InvalidOperands(Loc, LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006440
Richard Trieub420bca2011-09-12 18:37:54 +00006441 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6442 return QualType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006443
John McCallf2538342012-07-31 05:14:30 +00006444 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
Richard Trieub420bca2011-09-12 18:37:54 +00006445 return QualType();
6446
6447 // Check array bounds for pointer arithemtic
6448 CheckArrayAccess(PExp, IExp);
6449
6450 if (CompLHSTy) {
6451 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6452 if (LHSTy.isNull()) {
6453 LHSTy = LHS.get()->getType();
6454 if (LHSTy->isPromotableIntegerType())
6455 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006456 }
Richard Trieub420bca2011-09-12 18:37:54 +00006457 *CompLHSTy = LHSTy;
Eli Friedman8e122982008-05-18 18:08:51 +00006458 }
6459
Richard Trieub420bca2011-09-12 18:37:54 +00006460 return PExp->getType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00006461}
6462
Chris Lattner2a3569b2008-04-07 05:30:13 +00006463// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006464QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006465 SourceLocation Loc,
6466 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006467 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6468
Richard Trieu4ae7e972011-09-06 21:13:51 +00006469 if (LHS.get()->getType()->isVectorType() ||
6470 RHS.get()->getType()->isVectorType()) {
6471 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006472 if (CompLHSTy) *CompLHSTy = compType;
6473 return compType;
6474 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006475
Richard Trieu4ae7e972011-09-06 21:13:51 +00006476 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6477 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006478 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006479
Chris Lattner4d62f422007-12-09 21:53:25 +00006480 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006481
Chris Lattner4d62f422007-12-09 21:53:25 +00006482 // Handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006483 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006484 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006485 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006486 }
Mike Stump11289f42009-09-09 15:08:12 +00006487
Chris Lattner4d62f422007-12-09 21:53:25 +00006488 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006489 if (LHS.get()->getType()->isAnyPointerType()) {
6490 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006491
Chris Lattner12bdebb2009-04-24 23:50:08 +00006492 // Diagnose bad cases where we step over interface counts.
John McCallf2538342012-07-31 05:14:30 +00006493 if (LHS.get()->getType()->isObjCObjectPointerType() &&
6494 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00006495 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006496
Chris Lattner4d62f422007-12-09 21:53:25 +00006497 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006498 if (RHS.get()->getType()->isIntegerType()) {
6499 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006500 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006501
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006502 // Check array bounds for pointer arithemtic
Richard Smith13f67182011-12-16 19:31:14 +00006503 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6504 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006505
Richard Trieu4ae7e972011-09-06 21:13:51 +00006506 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6507 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006508 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006509
Chris Lattner4d62f422007-12-09 21:53:25 +00006510 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006511 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00006512 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006513 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006514
David Blaikiebbafb8a2012-03-11 07:00:24 +00006515 if (getLangOpts().CPlusPlus) {
Eli Friedman168fe152009-05-16 13:54:38 +00006516 // Pointee types must be the same: C++ [expr.add]
6517 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006518 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006519 }
6520 } else {
6521 // Pointee types must be compatible C99 6.5.6p3
6522 if (!Context.typesAreCompatible(
6523 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6524 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006525 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006526 return QualType();
6527 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006528 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006529
Chandler Carruthc9332212011-06-27 08:02:19 +00006530 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006531 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006532 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006533
Richard Trieu4ae7e972011-09-06 21:13:51 +00006534 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006535 return Context.getPointerDiffType();
6536 }
6537 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006538
Richard Trieu4ae7e972011-09-06 21:13:51 +00006539 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006540}
6541
Douglas Gregor0bf31402010-10-08 23:50:27 +00006542static bool isScopedEnumerationType(QualType T) {
6543 if (const EnumType *ET = dyn_cast<EnumType>(T))
6544 return ET->getDecl()->isScoped();
6545 return false;
6546}
6547
Richard Trieue4a19fb2011-09-06 21:21:28 +00006548static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006549 SourceLocation Loc, unsigned Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00006550 QualType LHSType) {
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006551 llvm::APSInt Right;
6552 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00006553 if (RHS.get()->isValueDependent() ||
6554 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006555 return;
6556
6557 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006558 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006559 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006560 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006561 return;
6562 }
6563 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00006564 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006565 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006566 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006567 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006568 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006569 return;
6570 }
6571 if (Opc != BO_Shl)
6572 return;
6573
6574 // When left shifting an ICE which is signed, we can check for overflow which
6575 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6576 // integers have defined behavior modulo one more than the maximum value
6577 // representable in the result type, so never warn for those.
6578 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00006579 if (LHS.get()->isValueDependent() ||
6580 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6581 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006582 return;
6583 llvm::APInt ResultBits =
6584 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6585 if (LeftBits.uge(ResultBits))
6586 return;
6587 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6588 Result = Result.shl(Right);
6589
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006590 // Print the bit representation of the signed integer as an unsigned
6591 // hexadecimal number.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006592 SmallString<40> HexResult;
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006593 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6594
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006595 // If we are only missing a sign bit, this is less likely to result in actual
6596 // bugs -- if the result is cast back to an unsigned type, it will have the
6597 // expected value. Thus we place this behind a different warning that can be
6598 // turned off separately if needed.
6599 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006600 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006601 << HexResult.str() << LHSType
6602 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006603 return;
6604 }
6605
6606 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006607 << HexResult.str() << Result.getMinSignedBits() << LHSType
6608 << Left.getBitWidth() << LHS.get()->getSourceRange()
6609 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006610}
6611
Chris Lattner2a3569b2008-04-07 05:30:13 +00006612// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00006613QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006614 SourceLocation Loc, unsigned Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006615 bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006616 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6617
Chris Lattner5c11c412007-12-12 05:47:28 +00006618 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006619 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6620 !RHS.get()->getType()->hasIntegerRepresentation())
6621 return InvalidOperands(Loc, LHS, RHS);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006622
Douglas Gregor0bf31402010-10-08 23:50:27 +00006623 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6624 // hasIntegerRepresentation() above instead of this.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006625 if (isScopedEnumerationType(LHS.get()->getType()) ||
6626 isScopedEnumerationType(RHS.get()->getType())) {
6627 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006628 }
6629
Nate Begemane46ee9a2009-10-25 02:26:48 +00006630 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006631 if (LHS.get()->getType()->isVectorType() ||
6632 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006633 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006634
Chris Lattner5c11c412007-12-12 05:47:28 +00006635 // Shifts don't perform usual arithmetic conversions, they just do integer
6636 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006637
John McCall57cdd882010-12-16 19:28:59 +00006638 // For the LHS, do usual unary conversions, but then reset them away
6639 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006640 ExprResult OldLHS = LHS;
6641 LHS = UsualUnaryConversions(LHS.take());
6642 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006643 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00006644 QualType LHSType = LHS.get()->getType();
Richard Trieuba63ce62011-09-09 01:45:06 +00006645 if (IsCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00006646
6647 // The RHS is simpler.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006648 RHS = UsualUnaryConversions(RHS.take());
6649 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006650 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006651
Ryan Flynnf53fab82009-08-07 16:20:20 +00006652 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00006653 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006654
Chris Lattner5c11c412007-12-12 05:47:28 +00006655 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00006656 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006657}
6658
Chandler Carruth17773fc2010-07-10 12:30:03 +00006659static bool IsWithinTemplateSpecialization(Decl *D) {
6660 if (DeclContext *DC = D->getDeclContext()) {
6661 if (isa<ClassTemplateSpecializationDecl>(DC))
6662 return true;
6663 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6664 return FD->isFunctionTemplateSpecialization();
6665 }
6666 return false;
6667}
6668
Richard Trieueea56f72011-09-02 03:48:46 +00006669/// If two different enums are compared, raise a warning.
Richard Trieu1762d7c2011-09-06 21:27:33 +00006670static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6671 ExprResult &RHS) {
6672 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6673 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00006674
6675 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6676 if (!LHSEnumType)
6677 return;
6678 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6679 if (!RHSEnumType)
6680 return;
6681
6682 // Ignore anonymous enums.
6683 if (!LHSEnumType->getDecl()->getIdentifier())
6684 return;
6685 if (!RHSEnumType->getDecl()->getIdentifier())
6686 return;
6687
6688 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6689 return;
6690
6691 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6692 << LHSStrippedType << RHSStrippedType
Richard Trieu1762d7c2011-09-06 21:27:33 +00006693 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00006694}
6695
Richard Trieudd82a5c2011-09-02 02:55:45 +00006696/// \brief Diagnose bad pointer comparisons.
6697static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006698 ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006699 bool IsError) {
6700 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieudd82a5c2011-09-02 02:55:45 +00006701 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006702 << LHS.get()->getType() << RHS.get()->getType()
6703 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006704}
6705
6706/// \brief Returns false if the pointers are converted to a composite type,
6707/// true otherwise.
6708static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006709 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006710 // C++ [expr.rel]p2:
6711 // [...] Pointer conversions (4.10) and qualification
6712 // conversions (4.4) are performed on pointer operands (or on
6713 // a pointer operand and a null pointer constant) to bring
6714 // them to their composite pointer type. [...]
6715 //
6716 // C++ [expr.eq]p1 uses the same notion for (in)equality
6717 // comparisons of pointers.
6718
6719 // C++ [expr.eq]p2:
6720 // In addition, pointers to members can be compared, or a pointer to
6721 // member and a null pointer constant. Pointer to member conversions
6722 // (4.11) and qualification conversions (4.4) are performed to bring
6723 // them to a common type. If one operand is a null pointer constant,
6724 // the common type is the type of the other operand. Otherwise, the
6725 // common type is a pointer to member type similar (4.4) to the type
6726 // of one of the operands, with a cv-qualification signature (4.4)
6727 // that is the union of the cv-qualification signatures of the operand
6728 // types.
6729
Richard Trieu1762d7c2011-09-06 21:27:33 +00006730 QualType LHSType = LHS.get()->getType();
6731 QualType RHSType = RHS.get()->getType();
6732 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6733 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieudd82a5c2011-09-02 02:55:45 +00006734
6735 bool NonStandardCompositeType = false;
Richard Trieu48277e52011-09-02 21:44:27 +00006736 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieu1762d7c2011-09-06 21:27:33 +00006737 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006738 if (T.isNull()) {
Richard Trieu1762d7c2011-09-06 21:27:33 +00006739 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006740 return true;
6741 }
6742
6743 if (NonStandardCompositeType)
6744 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006745 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6746 << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006747
Richard Trieu1762d7c2011-09-06 21:27:33 +00006748 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6749 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006750 return false;
6751}
6752
6753static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006754 ExprResult &LHS,
6755 ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006756 bool IsError) {
6757 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6758 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006759 << LHS.get()->getType() << RHS.get()->getType()
6760 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006761}
6762
Jordan Rosed49a33e2012-06-08 21:14:25 +00006763static bool isObjCObjectLiteral(ExprResult &E) {
6764 switch (E.get()->getStmtClass()) {
6765 case Stmt::ObjCArrayLiteralClass:
6766 case Stmt::ObjCDictionaryLiteralClass:
6767 case Stmt::ObjCStringLiteralClass:
6768 case Stmt::ObjCBoxedExprClass:
6769 return true;
6770 default:
6771 // Note that ObjCBoolLiteral is NOT an object literal!
6772 return false;
6773 }
6774}
6775
Jordan Rose7660f782012-07-17 17:46:40 +00006776static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6777 // Get the LHS object's interface type.
6778 QualType Type = LHS->getType();
6779 QualType InterfaceType;
6780 if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6781 InterfaceType = PTy->getPointeeType();
6782 if (const ObjCObjectType *iQFaceTy =
6783 InterfaceType->getAsObjCQualifiedInterfaceType())
6784 InterfaceType = iQFaceTy->getBaseType();
6785 } else {
6786 // If this is not actually an Objective-C object, bail out.
6787 return false;
6788 }
6789
6790 // If the RHS isn't an Objective-C object, bail out.
6791 if (!RHS->getType()->isObjCObjectPointerType())
6792 return false;
6793
6794 // Try to find the -isEqual: method.
6795 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6796 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6797 InterfaceType,
6798 /*instance=*/true);
6799 if (!Method) {
6800 if (Type->isObjCIdType()) {
6801 // For 'id', just check the global pool.
6802 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6803 /*receiverId=*/true,
6804 /*warn=*/false);
6805 } else {
6806 // Check protocols.
6807 Method = S.LookupMethodInQualifiedType(IsEqualSel,
6808 cast<ObjCObjectPointerType>(Type),
6809 /*instance=*/true);
6810 }
6811 }
6812
6813 if (!Method)
6814 return false;
6815
6816 QualType T = Method->param_begin()[0]->getType();
6817 if (!T->isObjCObjectPointerType())
6818 return false;
6819
6820 QualType R = Method->getResultType();
6821 if (!R->isScalarType())
6822 return false;
6823
6824 return true;
6825}
6826
6827static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
6828 ExprResult &LHS, ExprResult &RHS,
6829 BinaryOperator::Opcode Opc){
Jordan Rose63ffaa82012-07-17 17:46:48 +00006830 Expr *Literal;
6831 Expr *Other;
6832 if (isObjCObjectLiteral(LHS)) {
6833 Literal = LHS.get();
6834 Other = RHS.get();
6835 } else {
6836 Literal = RHS.get();
6837 Other = LHS.get();
6838 }
6839
6840 // Don't warn on comparisons against nil.
6841 Other = Other->IgnoreParenCasts();
6842 if (Other->isNullPointerConstant(S.getASTContext(),
6843 Expr::NPC_ValueDependentIsNotNull))
6844 return;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006845
Jordan Roseea70bf72012-07-17 17:46:44 +00006846 // This should be kept in sync with warn_objc_literal_comparison.
Jordan Rose63ffaa82012-07-17 17:46:48 +00006847 // LK_String should always be last, since it has its own warning flag.
Jordan Roseea70bf72012-07-17 17:46:44 +00006848 enum {
6849 LK_Array,
6850 LK_Dictionary,
6851 LK_Numeric,
6852 LK_Boxed,
6853 LK_String
6854 } LiteralKind;
6855
Jordan Rosed49a33e2012-06-08 21:14:25 +00006856 switch (Literal->getStmtClass()) {
6857 case Stmt::ObjCStringLiteralClass:
6858 // "string literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006859 LiteralKind = LK_String;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006860 break;
6861 case Stmt::ObjCArrayLiteralClass:
6862 // "array literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006863 LiteralKind = LK_Array;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006864 break;
6865 case Stmt::ObjCDictionaryLiteralClass:
6866 // "dictionary literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006867 LiteralKind = LK_Dictionary;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006868 break;
6869 case Stmt::ObjCBoxedExprClass: {
6870 Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6871 switch (Inner->getStmtClass()) {
6872 case Stmt::IntegerLiteralClass:
6873 case Stmt::FloatingLiteralClass:
6874 case Stmt::CharacterLiteralClass:
6875 case Stmt::ObjCBoolLiteralExprClass:
6876 case Stmt::CXXBoolLiteralExprClass:
6877 // "numeric literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006878 LiteralKind = LK_Numeric;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006879 break;
6880 case Stmt::ImplicitCastExprClass: {
6881 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6882 // Boolean literals can be represented by implicit casts.
6883 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
Jordan Roseea70bf72012-07-17 17:46:44 +00006884 LiteralKind = LK_Numeric;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006885 break;
6886 }
6887 // FALLTHROUGH
6888 }
6889 default:
6890 // "boxed expression"
Jordan Roseea70bf72012-07-17 17:46:44 +00006891 LiteralKind = LK_Boxed;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006892 break;
6893 }
6894 break;
6895 }
6896 default:
6897 llvm_unreachable("Unknown Objective-C object literal kind");
6898 }
6899
Jordan Roseea70bf72012-07-17 17:46:44 +00006900 if (LiteralKind == LK_String)
6901 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
6902 << Literal->getSourceRange();
6903 else
6904 S.Diag(Loc, diag::warn_objc_literal_comparison)
6905 << LiteralKind << Literal->getSourceRange();
Jordan Rosed49a33e2012-06-08 21:14:25 +00006906
Jordan Rose7660f782012-07-17 17:46:40 +00006907 if (BinaryOperator::isEqualityOp(Opc) &&
6908 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
6909 SourceLocation Start = LHS.get()->getLocStart();
6910 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
6911 SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc));
Jordan Rosef9198032012-07-09 16:54:44 +00006912
Jordan Rose7660f782012-07-17 17:46:40 +00006913 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
6914 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
6915 << FixItHint::CreateReplacement(OpRange, "isEqual:")
6916 << FixItHint::CreateInsertion(End, "]");
Jordan Rosed49a33e2012-06-08 21:14:25 +00006917 }
Jordan Rosed49a33e2012-06-08 21:14:25 +00006918}
6919
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006920// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00006921QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006922 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006923 bool IsRelational) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006924 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6925
John McCalle3027922010-08-25 11:45:40 +00006926 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006927
Chris Lattner9a152e22009-12-05 05:40:13 +00006928 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00006929 if (LHS.get()->getType()->isVectorType() ||
6930 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006931 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006932
Richard Trieub80728f2011-09-06 21:43:51 +00006933 QualType LHSType = LHS.get()->getType();
6934 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00006935
Richard Trieub80728f2011-09-06 21:43:51 +00006936 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6937 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006938
Richard Trieub80728f2011-09-06 21:43:51 +00006939 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth712563b2011-02-17 08:37:06 +00006940
Richard Trieub80728f2011-09-06 21:43:51 +00006941 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuba63ce62011-09-09 01:45:06 +00006942 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieub80728f2011-09-06 21:43:51 +00006943 !LHS.get()->getLocStart().isMacroID() &&
6944 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006945 // For non-floating point types, check for self-comparisons of the form
6946 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6947 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006948 //
6949 // NOTE: Don't warn about comparison expressions resulting from macro
6950 // expansion. Also don't warn about comparisons which are only self
6951 // comparisons within a template specialization. The warnings should catch
6952 // obvious cases in the definition of the template anyways. The idea is to
6953 // warn when the typed comparison operator will always evaluate to the same
6954 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006955 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006956 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006957 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006958 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006959 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006960 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006961 << (Opc == BO_EQ
6962 || Opc == BO_LE
6963 || Opc == BO_GE));
Richard Trieub80728f2011-09-06 21:43:51 +00006964 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregorec170db2010-06-08 19:50:34 +00006965 !DRL->getDecl()->getType()->isReferenceType() &&
6966 !DRR->getDecl()->getType()->isReferenceType()) {
6967 // what is it always going to eval to?
6968 char always_evals_to;
6969 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006970 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006971 always_evals_to = 0; // false
6972 break;
John McCalle3027922010-08-25 11:45:40 +00006973 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006974 always_evals_to = 1; // true
6975 break;
6976 default:
6977 // best we can say is 'a constant'
6978 always_evals_to = 2; // e.g. array1 <= array2
6979 break;
6980 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006981 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006982 << 1 // array
6983 << always_evals_to);
6984 }
6985 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006986 }
Mike Stump11289f42009-09-09 15:08:12 +00006987
Chris Lattner222b8bd2009-03-08 19:39:53 +00006988 if (isa<CastExpr>(LHSStripped))
6989 LHSStripped = LHSStripped->IgnoreParenCasts();
6990 if (isa<CastExpr>(RHSStripped))
6991 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006992
Chris Lattner222b8bd2009-03-08 19:39:53 +00006993 // Warn about comparisons against a string constant (unless the other
6994 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006995 Expr *literalString = 0;
6996 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006997 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006998 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006999 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00007000 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007001 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00007002 } else if ((isa<StringLiteral>(RHSStripped) ||
7003 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007004 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007005 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00007006 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007007 literalStringStripped = RHSStripped;
7008 }
7009
7010 if (literalString) {
7011 std::string resultComparison;
7012 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007013 case BO_LT: resultComparison = ") < 0"; break;
7014 case BO_GT: resultComparison = ") > 0"; break;
7015 case BO_LE: resultComparison = ") <= 0"; break;
7016 case BO_GE: resultComparison = ") >= 0"; break;
7017 case BO_EQ: resultComparison = ") == 0"; break;
7018 case BO_NE: resultComparison = ") != 0"; break;
David Blaikie83d382b2011-09-23 05:06:16 +00007019 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007020 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007021
Ted Kremenek3427fac2011-02-23 01:52:04 +00007022 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00007023 PDiag(diag::warn_stringcompare)
7024 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00007025 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007026 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00007027 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007028
Douglas Gregorec170db2010-06-08 19:50:34 +00007029 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieub80728f2011-09-06 21:43:51 +00007030 if (LHS.get()->getType()->isArithmeticType() &&
7031 RHS.get()->getType()->isArithmeticType()) {
7032 UsualArithmeticConversions(LHS, RHS);
7033 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007034 return QualType();
7035 }
Douglas Gregorec170db2010-06-08 19:50:34 +00007036 else {
Richard Trieub80728f2011-09-06 21:43:51 +00007037 LHS = UsualUnaryConversions(LHS.take());
7038 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007039 return QualType();
7040
Richard Trieub80728f2011-09-06 21:43:51 +00007041 RHS = UsualUnaryConversions(RHS.take());
7042 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007043 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007044 }
7045
Richard Trieub80728f2011-09-06 21:43:51 +00007046 LHSType = LHS.get()->getType();
7047 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007048
Douglas Gregorca63811b2008-11-19 03:25:36 +00007049 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007050 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00007051
Richard Trieuba63ce62011-09-09 01:45:06 +00007052 if (IsRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00007053 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007054 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007055 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00007056 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00007057 if (LHSType->hasFloatingRepresentation())
7058 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007059
Richard Trieub80728f2011-09-06 21:43:51 +00007060 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007061 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007062 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007063
Richard Trieub80728f2011-09-06 21:43:51 +00007064 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007065 Expr::NPC_ValueDependentIsNull);
Richard Trieub80728f2011-09-06 21:43:51 +00007066 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007067 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007068
Douglas Gregorf267edd2010-06-15 21:38:40 +00007069 // All of the following pointer-related warnings are GCC extensions, except
7070 // when handling null pointer constants.
Richard Trieub80728f2011-09-06 21:43:51 +00007071 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00007072 QualType LCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00007073 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattner3a0702e2008-04-03 05:07:25 +00007074 QualType RCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00007075 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007076
David Blaikiebbafb8a2012-03-11 07:00:24 +00007077 if (getLangOpts().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00007078 if (LCanPointeeTy == RCanPointeeTy)
7079 return ResultTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00007080 if (!IsRelational &&
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007081 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7082 // Valid unless comparison between non-null pointer and function pointer
7083 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00007084 // In a SFINAE context, we treat this as a hard error to maintain
7085 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007086 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7087 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00007088 diagnoseFunctionPointerToVoidComparison(
Richard Trieub80728f2011-09-06 21:43:51 +00007089 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00007090
7091 if (isSFINAEContext())
7092 return QualType();
7093
Richard Trieub80728f2011-09-06 21:43:51 +00007094 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007095 return ResultTy;
7096 }
7097 }
Anders Carlssona95069c2010-11-04 03:17:43 +00007098
Richard Trieub80728f2011-09-06 21:43:51 +00007099 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007100 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00007101 else
7102 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007103 }
Eli Friedman16c209612009-08-23 00:27:47 +00007104 // C99 6.5.9p2 and C99 6.5.8p2
7105 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7106 RCanPointeeTy.getUnqualifiedType())) {
7107 // Valid unless a relational comparison of function pointers
Richard Trieuba63ce62011-09-09 01:45:06 +00007108 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman16c209612009-08-23 00:27:47 +00007109 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00007110 << LHSType << RHSType << LHS.get()->getSourceRange()
7111 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00007112 }
Richard Trieuba63ce62011-09-09 01:45:06 +00007113 } else if (!IsRelational &&
Eli Friedman16c209612009-08-23 00:27:47 +00007114 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7115 // Valid unless comparison between non-null pointer and function pointer
7116 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00007117 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007118 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007119 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00007120 } else {
7121 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00007122 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00007123 }
John McCall7684dde2011-03-11 04:25:25 +00007124 if (LCanPointeeTy != RCanPointeeTy) {
7125 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007126 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007127 else
Richard Trieub80728f2011-09-06 21:43:51 +00007128 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007129 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00007130 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00007131 }
Mike Stump11289f42009-09-09 15:08:12 +00007132
David Blaikiebbafb8a2012-03-11 07:00:24 +00007133 if (getLangOpts().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00007134 // Comparison of nullptr_t with itself.
Richard Trieub80728f2011-09-06 21:43:51 +00007135 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlssona95069c2010-11-04 03:17:43 +00007136 return ResultTy;
7137
Mike Stump11289f42009-09-09 15:08:12 +00007138 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007139 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00007140 if (RHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00007141 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00007142 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00007143 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7144 RHS = ImpCastExprToType(RHS.take(), LHSType,
7145 LHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007146 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007147 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007148 return ResultTy;
7149 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007150 if (LHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00007151 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00007152 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00007153 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7154 LHS = ImpCastExprToType(LHS.take(), RHSType,
7155 RHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007156 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007157 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007158 return ResultTy;
7159 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007160
7161 // Comparison of member pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00007162 if (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00007163 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7164 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007165 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00007166 else
7167 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007168 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007169
7170 // Handle scoped enumeration types specifically, since they don't promote
7171 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00007172 if (LHS.get()->getType()->isEnumeralType() &&
7173 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7174 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007175 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00007176 }
Mike Stump11289f42009-09-09 15:08:12 +00007177
Steve Naroff081c7422008-09-04 15:10:53 +00007178 // Handle block pointer types.
Richard Trieuba63ce62011-09-09 01:45:06 +00007179 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieub80728f2011-09-06 21:43:51 +00007180 RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00007181 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7182 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007183
Steve Naroff081c7422008-09-04 15:10:53 +00007184 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00007185 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007186 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00007187 << LHSType << RHSType << LHS.get()->getSourceRange()
7188 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00007189 }
Richard Trieub80728f2011-09-06 21:43:51 +00007190 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007191 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00007192 }
John Wiegley01296292011-04-08 18:41:53 +00007193
Steve Naroffe18f94c2008-09-28 01:11:11 +00007194 // Allow block pointers to be compared with null pointer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00007195 if (!IsRelational
Richard Trieub80728f2011-09-06 21:43:51 +00007196 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7197 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00007198 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00007199 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007200 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00007201 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007202 ->getPointeeType()->isVoidType())))
7203 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00007204 << LHSType << RHSType << LHS.get()->getSourceRange()
7205 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00007206 }
John McCall7684dde2011-03-11 04:25:25 +00007207 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00007208 LHS = ImpCastExprToType(LHS.take(), RHSType,
7209 RHSType->isPointerType() ? CK_BitCast
7210 : CK_AnyPointerToBlockPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00007211 else
John McCall9320b872011-09-09 05:25:32 +00007212 RHS = ImpCastExprToType(RHS.take(), LHSType,
7213 LHSType->isPointerType() ? CK_BitCast
7214 : CK_AnyPointerToBlockPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007215 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00007216 }
Steve Naroff081c7422008-09-04 15:10:53 +00007217
Richard Trieub80728f2011-09-06 21:43:51 +00007218 if (LHSType->isObjCObjectPointerType() ||
7219 RHSType->isObjCObjectPointerType()) {
7220 const PointerType *LPT = LHSType->getAs<PointerType>();
7221 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00007222 if (LPT || RPT) {
7223 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7224 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007225
Steve Naroff753567f2008-11-17 19:49:16 +00007226 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00007227 !Context.typesAreCompatible(LHSType, RHSType)) {
7228 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007229 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007230 }
John McCall7684dde2011-03-11 04:25:25 +00007231 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00007232 LHS = ImpCastExprToType(LHS.take(), RHSType,
7233 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00007234 else
John McCall9320b872011-09-09 05:25:32 +00007235 RHS = ImpCastExprToType(RHS.take(), LHSType,
7236 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007237 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00007238 }
Richard Trieub80728f2011-09-06 21:43:51 +00007239 if (LHSType->isObjCObjectPointerType() &&
7240 RHSType->isObjCObjectPointerType()) {
7241 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7242 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007243 /*isError*/false);
Jordan Rosed49a33e2012-06-08 21:14:25 +00007244 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
Jordan Rose7660f782012-07-17 17:46:40 +00007245 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
Jordan Rosed49a33e2012-06-08 21:14:25 +00007246
John McCall7684dde2011-03-11 04:25:25 +00007247 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007248 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007249 else
Richard Trieub80728f2011-09-06 21:43:51 +00007250 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007251 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00007252 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00007253 }
Richard Trieub80728f2011-09-06 21:43:51 +00007254 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7255 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00007256 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007257 bool isError = false;
Douglas Gregor0064c592012-09-14 04:35:37 +00007258 if (LangOpts.DebuggerSupport) {
7259 // Under a debugger, allow the comparison of pointers to integers,
7260 // since users tend to want to compare addresses.
7261 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
Richard Trieub80728f2011-09-06 21:43:51 +00007262 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007263 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007264 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007265 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007266 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007267 else if (getLangOpts().CPlusPlus) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00007268 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7269 isError = true;
7270 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00007271 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00007272
Chris Lattnerd99bd522009-08-23 00:03:44 +00007273 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007274 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00007275 << LHSType << RHSType << LHS.get()->getSourceRange()
7276 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007277 if (isError)
7278 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00007279 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007280
Richard Trieub80728f2011-09-06 21:43:51 +00007281 if (LHSType->isIntegerType())
7282 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00007283 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00007284 else
Richard Trieub80728f2011-09-06 21:43:51 +00007285 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00007286 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007287 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00007288 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007289
Steve Naroff4b191572008-09-04 16:56:14 +00007290 // Handle block pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00007291 if (!IsRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00007292 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7293 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007294 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007295 }
Richard Trieuba63ce62011-09-09 01:45:06 +00007296 if (!IsRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00007297 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7298 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007299 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007300 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007301
Richard Trieub80728f2011-09-06 21:43:51 +00007302 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007303}
7304
Tanya Lattner20248222012-01-16 21:02:28 +00007305
7306// Return a signed type that is of identical size and number of elements.
7307// For floating point vectors, return an integer type of identical size
7308// and number of elements.
7309QualType Sema::GetSignedVectorType(QualType V) {
7310 const VectorType *VTy = V->getAs<VectorType>();
7311 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7312 if (TypeSize == Context.getTypeSize(Context.CharTy))
7313 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7314 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7315 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7316 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7317 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7318 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7319 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7320 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7321 "Unhandled vector element size in vector compare");
7322 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7323}
7324
Nate Begeman191a6b12008-07-14 18:02:46 +00007325/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00007326/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00007327/// like a scalar comparison, a vector comparison produces a vector of integer
7328/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00007329QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007330 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007331 bool IsRelational) {
Nate Begeman191a6b12008-07-14 18:02:46 +00007332 // Check to make sure we're operating on vectors of the same type and width,
7333 // Allowing one side to be a scalar of element type.
Richard Trieubcce2f72011-09-07 01:19:57 +00007334 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00007335 if (vType.isNull())
7336 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007337
Richard Trieubcce2f72011-09-07 01:19:57 +00007338 QualType LHSType = LHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007339
Anton Yartsev530deb92011-03-27 15:36:07 +00007340 // If AltiVec, the comparison results in a numeric type, i.e.
7341 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00007342 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00007343 return Context.getLogicalOperationType();
7344
Nate Begeman191a6b12008-07-14 18:02:46 +00007345 // For non-floating point types, check for self-comparisons of the form
7346 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7347 // often indicate logic errors in the program.
Richard Trieubcce2f72011-09-07 01:19:57 +00007348 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith508ebf32011-10-28 03:31:48 +00007349 if (DeclRefExpr* DRL
7350 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7351 if (DeclRefExpr* DRR
7352 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begeman191a6b12008-07-14 18:02:46 +00007353 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007354 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007355 PDiag(diag::warn_comparison_always)
7356 << 0 // self-
7357 << 2 // "a constant"
7358 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007359 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007360
Nate Begeman191a6b12008-07-14 18:02:46 +00007361 // Check for comparisons of floating point operands using != and ==.
Richard Trieuba63ce62011-09-09 01:45:06 +00007362 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikieca043222012-01-16 05:16:03 +00007363 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieubcce2f72011-09-07 01:19:57 +00007364 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00007365 }
Tanya Lattner20248222012-01-16 21:02:28 +00007366
7367 // Return a signed type for the vector.
7368 return GetSignedVectorType(LHSType);
7369}
Mike Stump4e1f26a2009-02-19 03:04:26 +00007370
Tanya Lattner3dd33b22012-01-19 01:16:16 +00007371QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7372 SourceLocation Loc) {
Tanya Lattner20248222012-01-16 21:02:28 +00007373 // Ensure that either both operands are of the same vector type, or
7374 // one operand is of a vector type and the other is of its element type.
7375 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7376 if (vType.isNull() || vType->isFloatingType())
7377 return InvalidOperands(Loc, LHS, RHS);
7378
7379 return GetSignedVectorType(LHS.get()->getType());
Nate Begeman191a6b12008-07-14 18:02:46 +00007380}
7381
Steve Naroff218bc2b2007-05-04 21:54:46 +00007382inline QualType Sema::CheckBitwiseOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00007383 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00007384 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7385
Richard Trieubcce2f72011-09-07 01:19:57 +00007386 if (LHS.get()->getType()->isVectorType() ||
7387 RHS.get()->getType()->isVectorType()) {
7388 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7389 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00007390 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007391
Richard Trieubcce2f72011-09-07 01:19:57 +00007392 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007393 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007394
Richard Trieubcce2f72011-09-07 01:19:57 +00007395 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7396 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuba63ce62011-09-09 01:45:06 +00007397 IsCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00007398 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007399 return QualType();
Richard Trieubcce2f72011-09-07 01:19:57 +00007400 LHS = LHSResult.take();
7401 RHS = RHSResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007402
Eli Friedman93ee5ca2012-06-16 02:19:17 +00007403 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007404 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00007405 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007406}
7407
Steve Naroff218bc2b2007-05-04 21:54:46 +00007408inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieubcce2f72011-09-07 01:19:57 +00007409 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00007410
Tanya Lattner20248222012-01-16 21:02:28 +00007411 // Check vector operands differently.
7412 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7413 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7414
Chris Lattner8406c512010-07-13 19:41:32 +00007415 // Diagnose cases where the user write a logical and/or but probably meant a
7416 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7417 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00007418 if (LHS.get()->getType()->isIntegerType() &&
7419 !LHS.get()->getType()->isBooleanType() &&
7420 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00007421 // Don't warn in macros or template instantiations.
7422 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00007423 // If the RHS can be constant folded, and if it constant folds to something
7424 // that isn't 0 or 1 (which indicate a potential logical operation that
7425 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007426 // Parens on the RHS are ignored.
Richard Smith00ab3ae2011-10-16 23:01:09 +00007427 llvm::APSInt Result;
7428 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikiebbafb8a2012-03-11 07:00:24 +00007429 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith00ab3ae2011-10-16 23:01:09 +00007430 (Result != 0 && Result != 1)) {
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007431 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00007432 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007433 << (Opc == BO_LAnd ? "&&" : "||");
7434 // Suggest replacing the logical operator with the bitwise version
7435 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7436 << (Opc == BO_LAnd ? "&" : "|")
7437 << FixItHint::CreateReplacement(SourceRange(
7438 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00007439 getLangOpts())),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007440 Opc == BO_LAnd ? "&" : "|");
7441 if (Opc == BO_LAnd)
7442 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7443 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7444 << FixItHint::CreateRemoval(
7445 SourceRange(
Richard Trieubcce2f72011-09-07 01:19:57 +00007446 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007447 0, getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00007448 getLangOpts()),
Richard Trieubcce2f72011-09-07 01:19:57 +00007449 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007450 }
Chris Lattner938533d2010-07-24 01:10:11 +00007451 }
Chris Lattner8406c512010-07-13 19:41:32 +00007452
David Blaikiebbafb8a2012-03-11 07:00:24 +00007453 if (!Context.getLangOpts().CPlusPlus) {
Richard Trieubcce2f72011-09-07 01:19:57 +00007454 LHS = UsualUnaryConversions(LHS.take());
7455 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007456 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007457
Richard Trieubcce2f72011-09-07 01:19:57 +00007458 RHS = UsualUnaryConversions(RHS.take());
7459 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007460 return QualType();
7461
Richard Trieubcce2f72011-09-07 01:19:57 +00007462 if (!LHS.get()->getType()->isScalarType() ||
7463 !RHS.get()->getType()->isScalarType())
7464 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007465
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007466 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007467 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007468
John McCall4a2429a2010-06-04 00:29:51 +00007469 // The following is safe because we only use this method for
7470 // non-overloadable operands.
7471
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007472 // C++ [expr.log.and]p1
7473 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007474 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00007475 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7476 if (LHSRes.isInvalid())
7477 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007478 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00007479
Richard Trieubcce2f72011-09-07 01:19:57 +00007480 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7481 if (RHSRes.isInvalid())
7482 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007483 RHS = RHSRes;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007484
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007485 // C++ [expr.log.and]p2
7486 // C++ [expr.log.or]p2
7487 // The result is a bool.
7488 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007489}
7490
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007491/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7492/// is a read-only property; return true if so. A readonly property expression
7493/// depends on various declarations and thus must be treated specially.
7494///
Mike Stump11289f42009-09-09 15:08:12 +00007495static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007496 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7497 if (!PropExpr) return false;
7498 if (PropExpr->isImplicitProperty()) return false;
John McCallb7bd14f2010-12-02 01:19:52 +00007499
John McCall526ab472011-10-25 17:37:35 +00007500 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7501 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCallb7bd14f2010-12-02 01:19:52 +00007502 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007503 PropExpr->getBase()->getType();
7504
John McCall526ab472011-10-25 17:37:35 +00007505 if (const ObjCObjectPointerType *OPT =
7506 BaseType->getAsObjCInterfacePointerType())
7507 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7508 if (S.isPropertyReadonly(PDecl, IFace))
7509 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007510 return false;
7511}
7512
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007513static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007514 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7515 if (!ME) return false;
7516 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7517 ObjCMessageExpr *Base =
7518 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7519 if (!Base) return false;
7520 return Base->getMethodDecl() != 0;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007521}
7522
John McCall5fa2ef42012-03-13 00:37:01 +00007523/// Is the given expression (which must be 'const') a reference to a
7524/// variable which was originally non-const, but which has become
7525/// 'const' due to being captured within a block?
7526enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7527static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7528 assert(E->isLValue() && E->getType().isConstQualified());
7529 E = E->IgnoreParens();
7530
7531 // Must be a reference to a declaration from an enclosing scope.
7532 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7533 if (!DRE) return NCCK_None;
7534 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7535
7536 // The declaration must be a variable which is not declared 'const'.
7537 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7538 if (!var) return NCCK_None;
7539 if (var->getType().isConstQualified()) return NCCK_None;
7540 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7541
7542 // Decide whether the first capture was for a block or a lambda.
7543 DeclContext *DC = S.CurContext;
7544 while (DC->getParent() != var->getDeclContext())
7545 DC = DC->getParent();
7546 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7547}
7548
Chris Lattner30bd3272008-11-18 01:22:49 +00007549/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7550/// emit an error and return true. If so, return false.
7551static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianca5c5972012-04-10 17:30:10 +00007552 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007553 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007554 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007555 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007556 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7557 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007558 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7559 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007560 if (IsLV == Expr::MLV_Valid)
7561 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007562
Chris Lattner30bd3272008-11-18 01:22:49 +00007563 unsigned Diag = 0;
7564 bool NeedType = false;
7565 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00007566 case Expr::MLV_ConstQualified:
7567 Diag = diag::err_typecheck_assign_const;
7568
John McCall5fa2ef42012-03-13 00:37:01 +00007569 // Use a specialized diagnostic when we're assigning to an object
7570 // from an enclosing function or block.
7571 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7572 if (NCCK == NCCK_Block)
7573 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7574 else
7575 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7576 break;
7577 }
7578
John McCalld4631322011-06-17 06:42:21 +00007579 // In ARC, use some specialized diagnostics for occasions where we
7580 // infer 'const'. These are always pseudo-strong variables.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007581 if (S.getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00007582 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7583 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7584 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7585
John McCalld4631322011-06-17 06:42:21 +00007586 // Use the normal diagnostic if it's pseudo-__strong but the
7587 // user actually wrote 'const'.
7588 if (var->isARCPseudoStrong() &&
7589 (!var->getTypeSourceInfo() ||
7590 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7591 // There are two pseudo-strong cases:
7592 // - self
John McCall31168b02011-06-15 23:02:42 +00007593 ObjCMethodDecl *method = S.getCurMethodDecl();
7594 if (method && var == method->getSelfDecl())
Ted Kremenek1fcdaa92011-11-14 21:59:25 +00007595 Diag = method->isClassMethod()
7596 ? diag::err_typecheck_arc_assign_self_class_method
7597 : diag::err_typecheck_arc_assign_self;
John McCalld4631322011-06-17 06:42:21 +00007598
7599 // - fast enumeration variables
7600 else
John McCall31168b02011-06-15 23:02:42 +00007601 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00007602
John McCall31168b02011-06-15 23:02:42 +00007603 SourceRange Assign;
7604 if (Loc != OrigLoc)
7605 Assign = SourceRange(OrigLoc, OrigLoc);
7606 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7607 // We need to preserve the AST regardless, so migration tool
7608 // can do its job.
7609 return false;
7610 }
7611 }
7612 }
7613
7614 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007615 case Expr::MLV_ArrayType:
Richard Smitheb3cad52012-06-04 22:27:30 +00007616 case Expr::MLV_ArrayTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007617 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7618 NeedType = true;
7619 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007620 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007621 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7622 NeedType = true;
7623 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007624 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007625 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7626 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007627 case Expr::MLV_Valid:
7628 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007629 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007630 case Expr::MLV_MemberFunction:
7631 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007632 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7633 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007634 case Expr::MLV_IncompleteType:
7635 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007636 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007637 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner9bad62c2008-01-04 18:04:52 +00007638 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007639 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7640 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007641 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007642 case Expr::MLV_NoSetterProperty:
John McCall526ab472011-10-25 17:37:35 +00007643 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007644 case Expr::MLV_InvalidMessageExpression:
7645 Diag = diag::error_readonly_message_assignment;
7646 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007647 case Expr::MLV_SubObjCPropertySetting:
7648 Diag = diag::error_no_subobject_property_setting;
7649 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007650 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007651
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007652 SourceRange Assign;
7653 if (Loc != OrigLoc)
7654 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007655 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007656 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007657 else
Mike Stump11289f42009-09-09 15:08:12 +00007658 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007659 return true;
7660}
7661
Nico Weberb8124d12012-07-03 02:03:06 +00007662static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7663 SourceLocation Loc,
7664 Sema &Sema) {
7665 // C / C++ fields
Nico Weber33fd5232012-06-28 23:53:12 +00007666 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7667 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7668 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7669 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
Nico Weberb8124d12012-07-03 02:03:06 +00007670 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
Nico Weber33fd5232012-06-28 23:53:12 +00007671 }
Chris Lattner30bd3272008-11-18 01:22:49 +00007672
Nico Weberb8124d12012-07-03 02:03:06 +00007673 // Objective-C instance variables
Nico Weber33fd5232012-06-28 23:53:12 +00007674 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7675 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7676 if (OL && OR && OL->getDecl() == OR->getDecl()) {
7677 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7678 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7679 if (RL && RR && RL->getDecl() == RR->getDecl())
Nico Weberb8124d12012-07-03 02:03:06 +00007680 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
Nico Weber33fd5232012-06-28 23:53:12 +00007681 }
7682}
Chris Lattner30bd3272008-11-18 01:22:49 +00007683
7684// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +00007685QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007686 SourceLocation Loc,
7687 QualType CompoundType) {
John McCall526ab472011-10-25 17:37:35 +00007688 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7689
Chris Lattner326f7572008-11-18 01:30:42 +00007690 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007691 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007692 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007693
Richard Trieuda4f43a62011-09-07 01:33:52 +00007694 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00007695 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7696 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007697 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007698 if (CompoundType.isNull()) {
Nico Weber33fd5232012-06-28 23:53:12 +00007699 Expr *RHSCheck = RHS.get();
7700
Nico Weberb8124d12012-07-03 02:03:06 +00007701 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
Nico Weber33fd5232012-06-28 23:53:12 +00007702
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007703 QualType LHSTy(LHSType);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007704 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007705 if (RHS.isInvalid())
7706 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007707 // Special case of NSObject attributes on c-style pointer types.
7708 if (ConvTy == IncompatiblePointer &&
7709 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007710 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007711 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007712 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007713 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007714
John McCall7decc9e2010-11-18 06:31:45 +00007715 if (ConvTy == Compatible &&
Fariborz Jahaniane2a77762012-01-24 19:40:13 +00007716 LHSType->isObjCObjectType())
Fariborz Jahanian3c4225a2012-01-24 18:05:45 +00007717 Diag(Loc, diag::err_objc_object_assignment)
7718 << LHSType;
John McCall7decc9e2010-11-18 06:31:45 +00007719
Chris Lattnerea714382008-08-21 18:04:13 +00007720 // If the RHS is a unary plus or minus, check to see if they = and + are
7721 // right next to each other. If so, the user may have typo'd "x =+ 4"
7722 // instead of "x += 4".
Chris Lattnerea714382008-08-21 18:04:13 +00007723 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7724 RHSCheck = ICE->getSubExpr();
7725 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007726 if ((UO->getOpcode() == UO_Plus ||
7727 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007728 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007729 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007730 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner36c39c92009-03-08 06:51:10 +00007731 // And there is a space or other character before the subexpr of the
7732 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007733 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattnered9f14c2009-03-09 07:11:10 +00007734 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007735 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007736 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007737 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007738 }
Chris Lattnerea714382008-08-21 18:04:13 +00007739 }
John McCall31168b02011-06-15 23:02:42 +00007740
7741 if (ConvTy == Compatible) {
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007742 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
7743 // Warn about retain cycles where a block captures the LHS, but
7744 // not if the LHS is a simple variable into which the block is
7745 // being stored...unless that variable can be captured by reference!
7746 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
7747 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
7748 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
7749 checkRetainCycles(LHSExpr, RHS.get());
7750
Jordan Rosed3934582012-09-28 22:21:30 +00007751 // It is safe to assign a weak reference into a strong variable.
7752 // Although this code can still have problems:
7753 // id x = self.weakProp;
7754 // id y = self.weakProp;
7755 // we do not warn to warn spuriously when 'x' and 'y' are on separate
7756 // paths through the function. This should be revisited if
7757 // -Wrepeated-use-of-weak is made flow-sensitive.
7758 DiagnosticsEngine::Level Level =
7759 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
7760 RHS.get()->getLocStart());
7761 if (Level != DiagnosticsEngine::Ignored)
7762 getCurFunction()->markSafeWeakUse(RHS.get());
7763
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007764 } else if (getLangOpts().ObjCAutoRefCount) {
Richard Trieuda4f43a62011-09-07 01:33:52 +00007765 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007766 }
John McCall31168b02011-06-15 23:02:42 +00007767 }
Chris Lattnerea714382008-08-21 18:04:13 +00007768 } else {
7769 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007770 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007771 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007772
Chris Lattner326f7572008-11-18 01:30:42 +00007773 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007774 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007775 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007776
Richard Trieuda4f43a62011-09-07 01:33:52 +00007777 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007778
Steve Naroff98cf3e92007-06-06 18:38:38 +00007779 // C99 6.5.16p3: The type of an assignment expression is the type of the
7780 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007781 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007782 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7783 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007784 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007785 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007786 return (getLangOpts().CPlusPlus
John McCall01cbf2d2010-10-12 02:19:57 +00007787 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007788}
7789
Chris Lattner326f7572008-11-18 01:30:42 +00007790// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007791static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007792 SourceLocation Loc) {
John McCall3aef3d82011-04-10 19:13:55 +00007793 LHS = S.CheckPlaceholderExpr(LHS.take());
7794 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007795 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007796 return QualType();
7797
John McCall73d36182010-10-12 07:14:40 +00007798 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7799 // operands, but not unary promotions.
7800 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007801
John McCall34376a62010-12-04 03:47:34 +00007802 // So we treat the LHS as a ignored value, and in C++ we allow the
7803 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007804 LHS = S.IgnoredValueConversions(LHS.take());
7805 if (LHS.isInvalid())
7806 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007807
Eli Friedmanc11535c2012-05-24 00:47:05 +00007808 S.DiagnoseUnusedExprResult(LHS.get());
7809
David Blaikiebbafb8a2012-03-11 07:00:24 +00007810 if (!S.getLangOpts().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007811 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7812 if (RHS.isInvalid())
7813 return QualType();
7814 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007815 S.RequireCompleteType(Loc, RHS.get()->getType(),
7816 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007817 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007818
John Wiegley01296292011-04-08 18:41:53 +00007819 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007820}
7821
Steve Naroff7a5af782007-07-13 16:58:59 +00007822/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7823/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007824static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7825 ExprValueKind &VK,
7826 SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007827 bool IsInc, bool IsPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007828 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007829 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007830
Chris Lattner6b0cf142008-11-21 07:05:48 +00007831 QualType ResType = Op->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00007832 // Atomic types can be used for increment / decrement where the non-atomic
7833 // versions can, so ignore the _Atomic() specifier for the purpose of
7834 // checking.
7835 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7836 ResType = ResAtomicType->getValueType();
7837
Chris Lattner6b0cf142008-11-21 07:05:48 +00007838 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007839
David Blaikiebbafb8a2012-03-11 07:00:24 +00007840 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007841 // Decrement of bool is not allowed.
Richard Trieuba63ce62011-09-09 01:45:06 +00007842 if (!IsInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007843 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007844 return QualType();
7845 }
7846 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007847 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007848 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007849 // OK!
John McCallf2538342012-07-31 05:14:30 +00007850 } else if (ResType->isPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007851 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007852 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007853 return QualType();
John McCallf2538342012-07-31 05:14:30 +00007854 } else if (ResType->isObjCObjectPointerType()) {
7855 // On modern runtimes, ObjC pointer arithmetic is forbidden.
7856 // Otherwise, we just need a complete type.
7857 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7858 checkArithmeticOnObjCPointer(S, OpLoc, Op))
7859 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +00007860 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007861 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007862 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007863 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007864 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007865 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007866 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007867 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007868 IsInc, IsPrefix);
David Blaikiebbafb8a2012-03-11 07:00:24 +00007869 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev85129b82011-02-07 02:17:30 +00007870 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007871 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007872 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuba63ce62011-09-09 01:45:06 +00007873 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007874 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007875 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007876 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007877 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007878 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007879 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007880 // In C++, a prefix increment is the same type as the operand. Otherwise
7881 // (in C or with postfix), the increment is the unqualified type of the
7882 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007883 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007884 VK = VK_LValue;
7885 return ResType;
7886 } else {
7887 VK = VK_RValue;
7888 return ResType.getUnqualifiedType();
7889 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007890}
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007891
7892
Anders Carlsson806700f2008-02-01 07:15:58 +00007893/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007894/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007895/// where the declaration is needed for type checking. We only need to
7896/// handle cases when the expression references a function designator
7897/// or is an lvalue. Here are some examples:
7898/// - &(x) => x
7899/// - &*****f => f for f a function designator.
7900/// - &s.xx => s
7901/// - &s.zz[1].yy -> s, if zz is an array
7902/// - *(x + 1) -> x, if x is an array
7903/// - &"123"[2] -> 0
7904/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007905static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007906 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007907 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007908 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007909 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007910 // If this is an arrow operator, the address is an offset from
7911 // the base's value, so the object the base refers to is
7912 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007913 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007914 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007915 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007916 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007917 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007918 // FIXME: This code shouldn't be necessary! We should catch the implicit
7919 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007920 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7921 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7922 if (ICE->getSubExpr()->getType()->isArrayType())
7923 return getPrimaryDecl(ICE->getSubExpr());
7924 }
7925 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007926 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007927 case Stmt::UnaryOperatorClass: {
7928 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007929
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007930 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007931 case UO_Real:
7932 case UO_Imag:
7933 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007934 return getPrimaryDecl(UO->getSubExpr());
7935 default:
7936 return 0;
7937 }
7938 }
Steve Naroff47500512007-04-19 23:00:49 +00007939 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007940 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007941 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007942 // If the result of an implicit cast is an l-value, we care about
7943 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007944 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007945 default:
7946 return 0;
7947 }
7948}
7949
Richard Trieu5f376f62011-09-07 21:46:33 +00007950namespace {
7951 enum {
7952 AO_Bit_Field = 0,
7953 AO_Vector_Element = 1,
7954 AO_Property_Expansion = 2,
7955 AO_Register_Variable = 3,
7956 AO_No_Error = 4
7957 };
7958}
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007959/// \brief Diagnose invalid operand for address of operations.
7960///
7961/// \param Type The type of operand which cannot have its address taken.
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007962static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7963 Expr *E, unsigned Type) {
7964 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7965}
7966
Steve Naroff47500512007-04-19 23:00:49 +00007967/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007968/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007969/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007970/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007971/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007972/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007973/// we allow the '&' but retain the overloaded-function type.
John McCall526ab472011-10-25 17:37:35 +00007974static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall4bc41ae2010-11-18 19:01:18 +00007975 SourceLocation OpLoc) {
John McCall526ab472011-10-25 17:37:35 +00007976 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7977 if (PTy->getKind() == BuiltinType::Overload) {
7978 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7979 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7980 << OrigOp.get()->getSourceRange();
7981 return QualType();
7982 }
7983
7984 return S.Context.OverloadTy;
7985 }
7986
7987 if (PTy->getKind() == BuiltinType::UnknownAny)
7988 return S.Context.UnknownAnyTy;
7989
7990 if (PTy->getKind() == BuiltinType::BoundMember) {
7991 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7992 << OrigOp.get()->getSourceRange();
Douglas Gregor668d3622011-10-09 19:10:41 +00007993 return QualType();
7994 }
John McCall526ab472011-10-25 17:37:35 +00007995
7996 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7997 if (OrigOp.isInvalid()) return QualType();
John McCall0009fcc2011-04-26 20:42:42 +00007998 }
John McCall8d08b9b2010-08-27 09:08:28 +00007999
John McCall526ab472011-10-25 17:37:35 +00008000 if (OrigOp.get()->isTypeDependent())
8001 return S.Context.DependentTy;
8002
8003 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00008004
John McCall8d08b9b2010-08-27 09:08:28 +00008005 // Make sure to ignore parentheses in subsequent checks
John McCall526ab472011-10-25 17:37:35 +00008006 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00008007
David Blaikiebbafb8a2012-03-11 07:00:24 +00008008 if (S.getLangOpts().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00008009 // Implement C99-only parts of addressof rules.
8010 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00008011 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00008012 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8013 // (assuming the deref expression is valid).
8014 return uOp->getSubExpr()->getType();
8015 }
8016 // Technically, there should be a check for array subscript
8017 // expressions here, but the result of one is always an lvalue anyway.
8018 }
John McCallf3a88602011-02-03 08:15:49 +00008019 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00008020 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5f376f62011-09-07 21:46:33 +00008021 unsigned AddressOfError = AO_No_Error;
Nuno Lopes17f345f2008-12-16 22:59:47 +00008022
Fariborz Jahanian071caef2011-03-26 19:48:30 +00008023 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00008024 bool sfinae = S.isSFINAEContext();
8025 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8026 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008027 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00008028 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008029 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00008030 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008031 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00008032 } else if (lval == Expr::LV_MemberFunction) {
8033 // If it's an instance method, make a member pointer.
8034 // The expression must have exactly the form &A::foo.
8035
8036 // If the underlying expression isn't a decl ref, give up.
8037 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008038 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00008039 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00008040 return QualType();
8041 }
8042 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8043 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8044
8045 // The id-expression was parenthesized.
John McCall526ab472011-10-25 17:37:35 +00008046 if (OrigOp.get() != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00008047 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00008048 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00008049
8050 // The method was named without a qualifier.
8051 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008052 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008053 << op->getSourceRange();
8054 }
8055
John McCall4bc41ae2010-11-18 19:01:18 +00008056 return S.Context.getMemberPointerType(op->getType(),
8057 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00008058 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00008059 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008060 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00008061 if (!op->getType()->isFunctionType()) {
John McCall526ab472011-10-25 17:37:35 +00008062 // Use a special diagnostic for loads from property references.
John McCallfe96e0b2011-11-06 09:01:30 +00008063 if (isa<PseudoObjectExpr>(op)) {
John McCall526ab472011-10-25 17:37:35 +00008064 AddressOfError = AO_Property_Expansion;
8065 } else {
8066 // FIXME: emit more specific diag...
8067 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8068 << op->getSourceRange();
8069 return QualType();
8070 }
Steve Naroff35d85152007-05-07 00:24:15 +00008071 }
John McCall086a4642010-11-24 05:12:34 +00008072 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008073 // The operand cannot be a bit-field
Richard Trieu5f376f62011-09-07 21:46:33 +00008074 AddressOfError = AO_Bit_Field;
John McCall086a4642010-11-24 05:12:34 +00008075 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00008076 // The operand cannot be an element of a vector
Richard Trieu5f376f62011-09-07 21:46:33 +00008077 AddressOfError = AO_Vector_Element;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00008078 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00008079 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00008080 // with the register storage-class specifier.
8081 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00008082 // in C++ it is not error to take address of a register
8083 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00008084 if (vd->getStorageClass() == SC_Register &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008085 !S.getLangOpts().CPlusPlus) {
Richard Trieu5f376f62011-09-07 21:46:33 +00008086 AddressOfError = AO_Register_Variable;
Steve Naroff35d85152007-05-07 00:24:15 +00008087 }
John McCalld14a8642009-11-21 08:51:07 +00008088 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008089 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00008090 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00008091 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008092 // Could be a pointer to member, though, if there is an explicit
8093 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00008094 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008095 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008096 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00008097 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008098 S.Diag(OpLoc,
8099 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00008100 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008101 return QualType();
8102 }
Mike Stump11289f42009-09-09 15:08:12 +00008103
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00008104 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8105 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00008106 return S.Context.getMemberPointerType(op->getType(),
8107 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00008108 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008109 }
Eli Friedman755c0c92011-08-26 20:28:17 +00008110 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikie83d382b2011-09-23 05:06:16 +00008111 llvm_unreachable("Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00008112 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008113
Richard Trieu5f376f62011-09-07 21:46:33 +00008114 if (AddressOfError != AO_No_Error) {
8115 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8116 return QualType();
8117 }
8118
Eli Friedmance7f9002009-05-16 23:27:50 +00008119 if (lval == Expr::LV_IncompleteVoidType) {
8120 // Taking the address of a void variable is technically illegal, but we
8121 // allow it in cases which are otherwise valid.
8122 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00008123 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00008124 }
8125
Steve Naroff47500512007-04-19 23:00:49 +00008126 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00008127 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00008128 return S.Context.getObjCObjectPointerType(op->getType());
8129 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00008130}
8131
Chris Lattner9156f1b2010-07-05 19:17:26 +00008132/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00008133static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8134 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008135 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008136 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008137
John Wiegley01296292011-04-08 18:41:53 +00008138 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8139 if (ConvResult.isInvalid())
8140 return QualType();
8141 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00008142 QualType OpTy = Op->getType();
8143 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00008144
8145 if (isa<CXXReinterpretCastExpr>(Op)) {
8146 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8147 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8148 Op->getSourceRange());
8149 }
8150
Chris Lattner9156f1b2010-07-05 19:17:26 +00008151 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8152 // is an incomplete type or void. It would be possible to warn about
8153 // dereferencing a void pointer, but it's completely well-defined, and such a
8154 // warning is unlikely to catch any mistakes.
8155 if (const PointerType *PT = OpTy->getAs<PointerType>())
8156 Result = PT->getPointeeType();
8157 else if (const ObjCObjectPointerType *OPT =
8158 OpTy->getAs<ObjCObjectPointerType>())
8159 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00008160 else {
John McCall3aef3d82011-04-10 19:13:55 +00008161 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00008162 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008163 if (PR.take() != Op)
8164 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00008165 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008166
Chris Lattner9156f1b2010-07-05 19:17:26 +00008167 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008168 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00008169 << OpTy << Op->getSourceRange();
8170 return QualType();
8171 }
John McCall4bc41ae2010-11-18 19:01:18 +00008172
8173 // Dereferences are usually l-values...
8174 VK = VK_LValue;
8175
8176 // ...except that certain expressions are never l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008177 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00008178 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00008179
8180 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00008181}
Steve Naroff218bc2b2007-05-04 21:54:46 +00008182
John McCalle3027922010-08-25 11:45:40 +00008183static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00008184 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008185 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008186 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00008187 default: llvm_unreachable("Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00008188 case tok::periodstar: Opc = BO_PtrMemD; break;
8189 case tok::arrowstar: Opc = BO_PtrMemI; break;
8190 case tok::star: Opc = BO_Mul; break;
8191 case tok::slash: Opc = BO_Div; break;
8192 case tok::percent: Opc = BO_Rem; break;
8193 case tok::plus: Opc = BO_Add; break;
8194 case tok::minus: Opc = BO_Sub; break;
8195 case tok::lessless: Opc = BO_Shl; break;
8196 case tok::greatergreater: Opc = BO_Shr; break;
8197 case tok::lessequal: Opc = BO_LE; break;
8198 case tok::less: Opc = BO_LT; break;
8199 case tok::greaterequal: Opc = BO_GE; break;
8200 case tok::greater: Opc = BO_GT; break;
8201 case tok::exclaimequal: Opc = BO_NE; break;
8202 case tok::equalequal: Opc = BO_EQ; break;
8203 case tok::amp: Opc = BO_And; break;
8204 case tok::caret: Opc = BO_Xor; break;
8205 case tok::pipe: Opc = BO_Or; break;
8206 case tok::ampamp: Opc = BO_LAnd; break;
8207 case tok::pipepipe: Opc = BO_LOr; break;
8208 case tok::equal: Opc = BO_Assign; break;
8209 case tok::starequal: Opc = BO_MulAssign; break;
8210 case tok::slashequal: Opc = BO_DivAssign; break;
8211 case tok::percentequal: Opc = BO_RemAssign; break;
8212 case tok::plusequal: Opc = BO_AddAssign; break;
8213 case tok::minusequal: Opc = BO_SubAssign; break;
8214 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8215 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8216 case tok::ampequal: Opc = BO_AndAssign; break;
8217 case tok::caretequal: Opc = BO_XorAssign; break;
8218 case tok::pipeequal: Opc = BO_OrAssign; break;
8219 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008220 }
8221 return Opc;
8222}
8223
John McCalle3027922010-08-25 11:45:40 +00008224static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00008225 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008226 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00008227 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00008228 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00008229 case tok::plusplus: Opc = UO_PreInc; break;
8230 case tok::minusminus: Opc = UO_PreDec; break;
8231 case tok::amp: Opc = UO_AddrOf; break;
8232 case tok::star: Opc = UO_Deref; break;
8233 case tok::plus: Opc = UO_Plus; break;
8234 case tok::minus: Opc = UO_Minus; break;
8235 case tok::tilde: Opc = UO_Not; break;
8236 case tok::exclaim: Opc = UO_LNot; break;
8237 case tok::kw___real: Opc = UO_Real; break;
8238 case tok::kw___imag: Opc = UO_Imag; break;
8239 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00008240 }
8241 return Opc;
8242}
8243
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008244/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8245/// This warning is only emitted for builtin assignment operations. It is also
8246/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +00008247static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008248 SourceLocation OpLoc) {
8249 if (!S.ActiveTemplateInstantiations.empty())
8250 return;
8251 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8252 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008253 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8254 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8255 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8256 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8257 if (!LHSDeclRef || !RHSDeclRef ||
8258 LHSDeclRef->getLocation().isMacroID() ||
8259 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008260 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008261 const ValueDecl *LHSDecl =
8262 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8263 const ValueDecl *RHSDecl =
8264 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8265 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008266 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008267 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008268 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008269 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008270 if (RefTy->getPointeeType().isVolatileQualified())
8271 return;
8272
8273 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +00008274 << LHSDeclRef->getType()
8275 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008276}
8277
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008278/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8279/// operator @p Opc at location @c TokLoc. This routine only supports
8280/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00008281ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008282 BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008283 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008284 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl67766732012-02-27 20:34:02 +00008285 // The syntax only allows initializer lists on the RHS of assignment,
8286 // so we don't need to worry about accepting invalid code for
8287 // non-assignment operators.
8288 // C++11 5.17p9:
8289 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8290 // of x = {} is x = T().
8291 InitializationKind Kind =
8292 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8293 InitializedEntity Entity =
8294 InitializedEntity::InitializeTemporary(LHSExpr->getType());
8295 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00008296 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
Sebastian Redl67766732012-02-27 20:34:02 +00008297 if (Init.isInvalid())
8298 return Init;
8299 RHSExpr = Init.take();
8300 }
8301
Richard Trieu4a287fb2011-09-07 01:49:20 +00008302 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008303 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008304 // The following two variables are used for compound assignment operators
8305 QualType CompLHSTy; // Type of LHS after promotions for computation
8306 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00008307 ExprValueKind VK = VK_RValue;
8308 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008309
8310 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008311 case BO_Assign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008312 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008313 if (getLangOpts().CPlusPlus &&
Richard Trieu4a287fb2011-09-07 01:49:20 +00008314 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8315 VK = LHS.get()->getValueKind();
8316 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008317 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008318 if (!ResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00008319 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008320 break;
John McCalle3027922010-08-25 11:45:40 +00008321 case BO_PtrMemD:
8322 case BO_PtrMemI:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008323 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008324 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00008325 break;
John McCalle3027922010-08-25 11:45:40 +00008326 case BO_Mul:
8327 case BO_Div:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008328 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00008329 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008330 break;
John McCalle3027922010-08-25 11:45:40 +00008331 case BO_Rem:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008332 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008333 break;
John McCalle3027922010-08-25 11:45:40 +00008334 case BO_Add:
Nico Weberccec40d2012-03-02 22:01:22 +00008335 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008336 break;
John McCalle3027922010-08-25 11:45:40 +00008337 case BO_Sub:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008338 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008339 break;
John McCalle3027922010-08-25 11:45:40 +00008340 case BO_Shl:
8341 case BO_Shr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008342 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008343 break;
John McCalle3027922010-08-25 11:45:40 +00008344 case BO_LE:
8345 case BO_LT:
8346 case BO_GE:
8347 case BO_GT:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008348 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008349 break;
John McCalle3027922010-08-25 11:45:40 +00008350 case BO_EQ:
8351 case BO_NE:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008352 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008353 break;
John McCalle3027922010-08-25 11:45:40 +00008354 case BO_And:
8355 case BO_Xor:
8356 case BO_Or:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008357 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008358 break;
John McCalle3027922010-08-25 11:45:40 +00008359 case BO_LAnd:
8360 case BO_LOr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008361 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008362 break;
John McCalle3027922010-08-25 11:45:40 +00008363 case BO_MulAssign:
8364 case BO_DivAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008365 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00008366 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008367 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008368 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8369 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008370 break;
John McCalle3027922010-08-25 11:45:40 +00008371 case BO_RemAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008372 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008373 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008374 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8375 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008376 break;
John McCalle3027922010-08-25 11:45:40 +00008377 case BO_AddAssign:
Nico Weberccec40d2012-03-02 22:01:22 +00008378 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu4a287fb2011-09-07 01:49:20 +00008379 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8380 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008381 break;
John McCalle3027922010-08-25 11:45:40 +00008382 case BO_SubAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008383 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8384 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8385 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008386 break;
John McCalle3027922010-08-25 11:45:40 +00008387 case BO_ShlAssign:
8388 case BO_ShrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008389 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008390 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008391 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8392 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008393 break;
John McCalle3027922010-08-25 11:45:40 +00008394 case BO_AndAssign:
8395 case BO_XorAssign:
8396 case BO_OrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008397 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008398 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008399 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8400 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008401 break;
John McCalle3027922010-08-25 11:45:40 +00008402 case BO_Comma:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008403 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikiebbafb8a2012-03-11 07:00:24 +00008404 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu4a287fb2011-09-07 01:49:20 +00008405 VK = RHS.get()->getValueKind();
8406 OK = RHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008407 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008408 break;
8409 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008410 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00008411 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008412
8413 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu4a287fb2011-09-07 01:49:20 +00008414 CheckArrayAccess(LHS.get());
8415 CheckArrayAccess(RHS.get());
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008416
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008417 if (CompResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00008418 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00008419 ResultTy, VK, OK, OpLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00008420 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieucfc491d2011-08-02 04:35:43 +00008421 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00008422 VK = VK_LValue;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008423 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008424 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008425 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00008426 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00008427 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008428}
8429
Sebastian Redl44615072009-10-27 12:10:02 +00008430/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8431/// operators are mixed in a way that suggests that the programmer forgot that
8432/// comparison operators have higher precedence. The most typical example of
8433/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00008434static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008435 SourceLocation OpLoc, Expr *LHSExpr,
8436 Expr *RHSExpr) {
Sebastian Redl44615072009-10-27 12:10:02 +00008437 typedef BinaryOperator BinOp;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008438 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8439 RHSopc = static_cast<BinOp::Opcode>(-1);
8440 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8441 LHSopc = BO->getOpcode();
8442 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8443 RHSopc = BO->getOpcode();
Sebastian Redl43028242009-10-26 15:24:15 +00008444
8445 // Subs are not binary operators.
Richard Trieu4a287fb2011-09-07 01:49:20 +00008446 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl43028242009-10-26 15:24:15 +00008447 return;
8448
8449 // Bitwise operations are sometimes used as eager logical ops.
8450 // Don't diagnose this.
Richard Trieu4a287fb2011-09-07 01:49:20 +00008451 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8452 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00008453 return;
8454
Richard Trieu4a287fb2011-09-07 01:49:20 +00008455 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8456 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00008457 if (!isLeftComp && !isRightComp) return;
8458
Richard Trieu4a287fb2011-09-07 01:49:20 +00008459 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8460 OpLoc)
8461 : SourceRange(OpLoc, RHSExpr->getLocEnd());
8462 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8463 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00008464 SourceRange ParensRange = isLeftComp ?
Richard Trieu4a287fb2011-09-07 01:49:20 +00008465 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8466 RHSExpr->getLocEnd())
8467 : SourceRange(LHSExpr->getLocStart(),
8468 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu73088052011-08-10 22:41:34 +00008469
8470 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8471 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8472 SuggestParentheses(Self, OpLoc,
8473 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Nico Webercdfb1ae2012-06-03 07:07:00 +00008474 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu73088052011-08-10 22:41:34 +00008475 SuggestParentheses(Self, OpLoc,
8476 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8477 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00008478}
8479
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008480/// \brief It accepts a '&' expr that is inside a '|' one.
8481/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8482/// in parentheses.
8483static void
8484EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8485 BinaryOperator *Bop) {
8486 assert(Bop->getOpcode() == BO_And);
8487 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8488 << Bop->getSourceRange() << OpLoc;
8489 SuggestParentheses(Self, Bop->getOperatorLoc(),
8490 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8491 Bop->getSourceRange());
8492}
8493
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008494/// \brief It accepts a '&&' expr that is inside a '||' one.
8495/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8496/// in parentheses.
8497static void
8498EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008499 BinaryOperator *Bop) {
8500 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008501 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8502 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008503 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008504 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008505 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008506}
8507
8508/// \brief Returns true if the given expression can be evaluated as a constant
8509/// 'true'.
8510static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8511 bool Res;
8512 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8513}
8514
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008515/// \brief Returns true if the given expression can be evaluated as a constant
8516/// 'false'.
8517static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8518 bool Res;
8519 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8520}
8521
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008522/// \brief Look for '&&' in the left hand of a '||' expr.
8523static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008524 Expr *LHSExpr, Expr *RHSExpr) {
8525 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008526 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008527 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008528 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008529 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008530 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8531 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8532 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8533 } else if (Bop->getOpcode() == BO_LOr) {
8534 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8535 // If it's "a || b && 1 || c" we didn't warn earlier for
8536 // "a || b && 1", but warn now.
8537 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8538 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8539 }
8540 }
8541 }
8542}
8543
8544/// \brief Look for '&&' in the right hand of a '||' expr.
8545static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008546 Expr *LHSExpr, Expr *RHSExpr) {
8547 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008548 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008549 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008550 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008551 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008552 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8553 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8554 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008555 }
8556 }
8557}
8558
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008559/// \brief Look for '&' in the left or right hand of a '|' expr.
8560static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8561 Expr *OrArg) {
8562 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8563 if (Bop->getOpcode() == BO_And)
8564 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8565 }
8566}
8567
Sebastian Redl43028242009-10-26 15:24:15 +00008568/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008569/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008570static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008571 SourceLocation OpLoc, Expr *LHSExpr,
8572 Expr *RHSExpr){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008573 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008574 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008575 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008576
8577 // Diagnose "arg1 & arg2 | arg3"
8578 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008579 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8580 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008581 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008582
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008583 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8584 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008585 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008586 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8587 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008588 }
Sebastian Redl43028242009-10-26 15:24:15 +00008589}
8590
Steve Naroff218bc2b2007-05-04 21:54:46 +00008591// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008592ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008593 tok::TokenKind Kind,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008594 Expr *LHSExpr, Expr *RHSExpr) {
John McCalle3027922010-08-25 11:45:40 +00008595 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008596 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8597 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008598
Sebastian Redl43028242009-10-26 15:24:15 +00008599 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008600 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +00008601
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008602 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor5287f092009-11-05 00:51:44 +00008603}
8604
John McCall526ab472011-10-25 17:37:35 +00008605/// Build an overloaded binary operator expression in the given scope.
8606static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8607 BinaryOperatorKind Opc,
8608 Expr *LHS, Expr *RHS) {
8609 // Find all of the overloaded operators visible from this
8610 // point. We perform both an operator-name lookup from the local
8611 // scope and an argument-dependent lookup based on the types of
8612 // the arguments.
8613 UnresolvedSet<16> Functions;
8614 OverloadedOperatorKind OverOp
8615 = BinaryOperator::getOverloadedOperator(Opc);
8616 if (Sc && OverOp != OO_None)
8617 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8618 RHS->getType(), Functions);
8619
8620 // Build the (potentially-overloaded, potentially-dependent)
8621 // binary operation.
8622 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8623}
8624
John McCalldadc5752010-08-24 06:29:42 +00008625ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008626 BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008627 Expr *LHSExpr, Expr *RHSExpr) {
John McCall9a43e122011-10-28 01:04:34 +00008628 // We want to end up calling one of checkPseudoObjectAssignment
8629 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8630 // both expressions are overloadable or either is type-dependent),
8631 // or CreateBuiltinBinOp (in any other case). We also want to get
8632 // any placeholder types out of the way.
8633
John McCall526ab472011-10-25 17:37:35 +00008634 // Handle pseudo-objects in the LHS.
8635 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8636 // Assignments with a pseudo-object l-value need special analysis.
8637 if (pty->getKind() == BuiltinType::PseudoObject &&
8638 BinaryOperator::isAssignmentOp(Opc))
8639 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8640
8641 // Don't resolve overloads if the other type is overloadable.
8642 if (pty->getKind() == BuiltinType::Overload) {
8643 // We can't actually test that if we still have a placeholder,
8644 // though. Fortunately, none of the exceptions we see in that
John McCall9a43e122011-10-28 01:04:34 +00008645 // code below are valid when the LHS is an overload set. Note
8646 // that an overload set can be dependently-typed, but it never
8647 // instantiates to having an overloadable type.
John McCall526ab472011-10-25 17:37:35 +00008648 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8649 if (resolvedRHS.isInvalid()) return ExprError();
8650 RHSExpr = resolvedRHS.take();
8651
John McCall9a43e122011-10-28 01:04:34 +00008652 if (RHSExpr->isTypeDependent() ||
8653 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008654 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8655 }
8656
8657 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8658 if (LHS.isInvalid()) return ExprError();
8659 LHSExpr = LHS.take();
8660 }
8661
8662 // Handle pseudo-objects in the RHS.
8663 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8664 // An overload in the RHS can potentially be resolved by the type
8665 // being assigned to.
John McCall9a43e122011-10-28 01:04:34 +00008666 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8667 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8668 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8669
Eli Friedman419b1ff2012-01-17 21:27:43 +00008670 if (LHSExpr->getType()->isOverloadableType())
8671 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8672
John McCall526ab472011-10-25 17:37:35 +00008673 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCall9a43e122011-10-28 01:04:34 +00008674 }
John McCall526ab472011-10-25 17:37:35 +00008675
8676 // Don't resolve overloads if the other type is overloadable.
8677 if (pty->getKind() == BuiltinType::Overload &&
8678 LHSExpr->getType()->isOverloadableType())
8679 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8680
8681 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8682 if (!resolvedRHS.isUsable()) return ExprError();
8683 RHSExpr = resolvedRHS.take();
8684 }
8685
David Blaikiebbafb8a2012-03-11 07:00:24 +00008686 if (getLangOpts().CPlusPlus) {
John McCall9a43e122011-10-28 01:04:34 +00008687 // If either expression is type-dependent, always build an
8688 // overloaded op.
8689 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8690 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008691
John McCall9a43e122011-10-28 01:04:34 +00008692 // Otherwise, build an overloaded op if either expression has an
8693 // overloadable type.
8694 if (LHSExpr->getType()->isOverloadableType() ||
8695 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008696 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb5d49352009-01-19 22:31:54 +00008697 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008698
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008699 // Build a built-in binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008700 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008701}
8702
John McCalldadc5752010-08-24 06:29:42 +00008703ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008704 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008705 Expr *InputExpr) {
8706 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008707 ExprValueKind VK = VK_RValue;
8708 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008709 QualType resultType;
8710 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008711 case UO_PreInc:
8712 case UO_PreDec:
8713 case UO_PostInc:
8714 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008715 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008716 Opc == UO_PreInc ||
8717 Opc == UO_PostInc,
8718 Opc == UO_PreInc ||
8719 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008720 break;
John McCalle3027922010-08-25 11:45:40 +00008721 case UO_AddrOf:
John McCall526ab472011-10-25 17:37:35 +00008722 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008723 break;
John McCall31996342011-04-07 08:22:57 +00008724 case UO_Deref: {
John Wiegley01296292011-04-08 18:41:53 +00008725 Input = DefaultFunctionArrayLvalueConversion(Input.take());
Eli Friedman34866c72012-08-31 00:14:07 +00008726 if (Input.isInvalid()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008727 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008728 break;
John McCall31996342011-04-07 08:22:57 +00008729 }
John McCalle3027922010-08-25 11:45:40 +00008730 case UO_Plus:
8731 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008732 Input = UsualUnaryConversions(Input.take());
8733 if (Input.isInvalid()) return ExprError();
8734 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008735 if (resultType->isDependentType())
8736 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008737 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8738 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008739 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008740 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregord08452f2008-11-19 15:42:04 +00008741 resultType->isEnumeralType())
8742 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008743 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008744 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008745 resultType->isPointerType())
8746 break;
8747
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008748 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008749 << resultType << Input.get()->getSourceRange());
8750
John McCalle3027922010-08-25 11:45:40 +00008751 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008752 Input = UsualUnaryConversions(Input.take());
8753 if (Input.isInvalid()) return ExprError();
8754 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008755 if (resultType->isDependentType())
8756 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008757 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8758 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8759 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008760 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008761 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008762 else if (resultType->hasIntegerRepresentation())
8763 break;
John McCall526ab472011-10-25 17:37:35 +00008764 else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008765 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008766 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008767 }
Steve Naroff35d85152007-05-07 00:24:15 +00008768 break;
John Wiegley01296292011-04-08 18:41:53 +00008769
John McCalle3027922010-08-25 11:45:40 +00008770 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008771 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008772 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8773 if (Input.isInvalid()) return ExprError();
8774 resultType = Input.get()->getType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00008775
8776 // Though we still have to promote half FP to float...
8777 if (resultType->isHalfType()) {
8778 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8779 resultType = Context.FloatTy;
8780 }
8781
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008782 if (resultType->isDependentType())
8783 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008784 if (resultType->isScalarType()) {
8785 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008786 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008787 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8788 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008789 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8790 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008791 }
Tanya Lattner3dd33b22012-01-19 01:16:16 +00008792 } else if (resultType->isExtVectorType()) {
Tanya Lattner20248222012-01-16 21:02:28 +00008793 // Vector logical not returns the signed variant of the operand type.
8794 resultType = GetSignedVectorType(resultType);
8795 break;
John McCall36226622010-10-12 02:09:17 +00008796 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008797 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008798 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008799 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008800
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008801 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008802 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008803 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008804 break;
John McCalle3027922010-08-25 11:45:40 +00008805 case UO_Real:
8806 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008807 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smith0b6b8e42012-02-18 20:53:32 +00008808 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8809 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley01296292011-04-08 18:41:53 +00008810 if (Input.isInvalid()) return ExprError();
Richard Smith0b6b8e42012-02-18 20:53:32 +00008811 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8812 if (Input.get()->getValueKind() != VK_RValue &&
8813 Input.get()->getObjectKind() == OK_Ordinary)
8814 VK = Input.get()->getValueKind();
David Blaikiebbafb8a2012-03-11 07:00:24 +00008815 } else if (!getLangOpts().CPlusPlus) {
Richard Smith0b6b8e42012-02-18 20:53:32 +00008816 // In C, a volatile scalar is read by __imag. In C++, it is not.
8817 Input = DefaultLvalueConversion(Input.take());
8818 }
Chris Lattner30b5dd02007-08-24 21:16:53 +00008819 break;
John McCalle3027922010-08-25 11:45:40 +00008820 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008821 resultType = Input.get()->getType();
8822 VK = Input.get()->getValueKind();
8823 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008824 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008825 }
John Wiegley01296292011-04-08 18:41:53 +00008826 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008827 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008828
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008829 // Check for array bounds violations in the operand of the UnaryOperator,
8830 // except for the '*' and '&' operators that have to be handled specially
8831 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8832 // that are explicitly defined as valid by the standard).
8833 if (Opc != UO_AddrOf && Opc != UO_Deref)
8834 CheckArrayAccess(Input.get());
8835
John Wiegley01296292011-04-08 18:41:53 +00008836 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008837 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008838}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008839
Douglas Gregor72341032011-12-14 21:23:13 +00008840/// \brief Determine whether the given expression is a qualified member
8841/// access expression, of a form that could be turned into a pointer to member
8842/// with the address-of operator.
8843static bool isQualifiedMemberAccess(Expr *E) {
8844 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8845 if (!DRE->getQualifier())
8846 return false;
8847
8848 ValueDecl *VD = DRE->getDecl();
8849 if (!VD->isCXXClassMember())
8850 return false;
8851
8852 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8853 return true;
8854 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8855 return Method->isInstance();
8856
8857 return false;
8858 }
8859
8860 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8861 if (!ULE->getQualifier())
8862 return false;
8863
8864 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8865 DEnd = ULE->decls_end();
8866 D != DEnd; ++D) {
8867 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8868 if (Method->isInstance())
8869 return true;
8870 } else {
8871 // Overload set does not contain methods.
8872 break;
8873 }
8874 }
8875
8876 return false;
8877 }
8878
8879 return false;
8880}
8881
John McCalldadc5752010-08-24 06:29:42 +00008882ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008883 UnaryOperatorKind Opc, Expr *Input) {
John McCall526ab472011-10-25 17:37:35 +00008884 // First things first: handle placeholders so that the
8885 // overloaded-operator check considers the right type.
8886 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8887 // Increment and decrement of pseudo-object references.
8888 if (pty->getKind() == BuiltinType::PseudoObject &&
8889 UnaryOperator::isIncrementDecrementOp(Opc))
8890 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8891
8892 // extension is always a builtin operator.
8893 if (Opc == UO_Extension)
8894 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8895
8896 // & gets special logic for several kinds of placeholder.
8897 // The builtin code knows what to do.
8898 if (Opc == UO_AddrOf &&
8899 (pty->getKind() == BuiltinType::Overload ||
8900 pty->getKind() == BuiltinType::UnknownAny ||
8901 pty->getKind() == BuiltinType::BoundMember))
8902 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8903
8904 // Anything else needs to be handled now.
8905 ExprResult Result = CheckPlaceholderExpr(Input);
8906 if (Result.isInvalid()) return ExprError();
8907 Input = Result.take();
8908 }
8909
David Blaikiebbafb8a2012-03-11 07:00:24 +00008910 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregor72341032011-12-14 21:23:13 +00008911 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8912 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008913 // Find all of the overloaded operators visible from this
8914 // point. We perform both an operator-name lookup from the local
8915 // scope and an argument-dependent lookup based on the types of
8916 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008917 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008918 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008919 if (S && OverOp != OO_None)
8920 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8921 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008922
John McCallb268a282010-08-23 23:25:46 +00008923 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008924 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008925
John McCallb268a282010-08-23 23:25:46 +00008926 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008927}
8928
Douglas Gregor5287f092009-11-05 00:51:44 +00008929// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008930ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008931 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008932 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008933}
8934
Steve Naroff66356bd2007-09-16 14:56:35 +00008935/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008936ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008937 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008938 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008939 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008940 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008941 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008942}
8943
John McCall31168b02011-06-15 23:02:42 +00008944/// Given the last statement in a statement-expression, check whether
8945/// the result is a producing expression (like a call to an
8946/// ns_returns_retained function) and, if so, rebuild it to hoist the
8947/// release out of the full-expression. Otherwise, return null.
8948/// Cannot fail.
Richard Trieuba63ce62011-09-09 01:45:06 +00008949static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCall31168b02011-06-15 23:02:42 +00008950 // Should always be wrapped with one of these.
Richard Trieuba63ce62011-09-09 01:45:06 +00008951 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCall31168b02011-06-15 23:02:42 +00008952 if (!cleanups) return 0;
8953
8954 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall2d637d22011-09-10 06:18:15 +00008955 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCall31168b02011-06-15 23:02:42 +00008956 return 0;
8957
8958 // Splice out the cast. This shouldn't modify any interesting
8959 // features of the statement.
8960 Expr *producer = cast->getSubExpr();
8961 assert(producer->getType() == cast->getType());
8962 assert(producer->getValueKind() == cast->getValueKind());
8963 cleanups->setSubExpr(producer);
8964 return cleanups;
8965}
8966
John McCall3abee492012-04-04 01:27:53 +00008967void Sema::ActOnStartStmtExpr() {
8968 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
8969}
8970
8971void Sema::ActOnStmtExprError() {
John McCalled7b2782012-04-06 18:20:53 +00008972 // Note that function is also called by TreeTransform when leaving a
8973 // StmtExpr scope without rebuilding anything.
8974
John McCall3abee492012-04-04 01:27:53 +00008975 DiscardCleanupsInEvaluationContext();
8976 PopExpressionEvaluationContext();
8977}
8978
John McCalldadc5752010-08-24 06:29:42 +00008979ExprResult
John McCallb268a282010-08-23 23:25:46 +00008980Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008981 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008982 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8983 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8984
John McCall3abee492012-04-04 01:27:53 +00008985 if (hasAnyUnrecoverableErrorsInThisFunction())
8986 DiscardCleanupsInEvaluationContext();
8987 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
8988 PopExpressionEvaluationContext();
8989
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008990 bool isFileScope
8991 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008992 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008993 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008994
Chris Lattner366727f2007-07-24 16:58:17 +00008995 // FIXME: there are a variety of strange constraints to enforce here, for
8996 // example, it is not possible to goto into a stmt expression apparently.
8997 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008998
Chris Lattner366727f2007-07-24 16:58:17 +00008999 // If there are sub stmts in the compound stmt, take the type of the last one
9000 // as the type of the stmtexpr.
9001 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009002 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00009003 if (!Compound->body_empty()) {
9004 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009005 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00009006 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009007 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9008 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00009009 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009010 }
John McCall31168b02011-06-15 23:02:42 +00009011
John Wiegley01296292011-04-08 18:41:53 +00009012 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00009013 // Do function/array conversion on the last expression, but not
9014 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00009015 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9016 if (LastExpr.isInvalid())
9017 return ExprError();
9018 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00009019
John Wiegley01296292011-04-08 18:41:53 +00009020 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00009021 // In ARC, if the final expression ends in a consume, splice
9022 // the consume out and bind it later. In the alternate case
9023 // (when dealing with a retainable type), the result
9024 // initialization will create a produce. In both cases the
9025 // result will be +1, and we'll need to balance that out with
9026 // a bind.
9027 if (Expr *rebuiltLastStmt
9028 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9029 LastExpr = rebuiltLastStmt;
9030 } else {
9031 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009032 InitializedEntity::InitializeResult(LPLoc,
9033 Ty,
9034 false),
9035 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00009036 LastExpr);
9037 }
9038
John Wiegley01296292011-04-08 18:41:53 +00009039 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009040 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009041 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009042 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00009043 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009044 else
John Wiegley01296292011-04-08 18:41:53 +00009045 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009046 StmtExprMayBindToTemp = true;
9047 }
9048 }
9049 }
Chris Lattner944d3062008-07-26 19:51:01 +00009050 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009051
Eli Friedmanba961a92009-03-23 00:24:07 +00009052 // FIXME: Check that expression type is complete/non-abstract; statement
9053 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009054 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9055 if (StmtExprMayBindToTemp)
9056 return MaybeBindToTemporary(ResStmtExpr);
9057 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00009058}
Steve Naroff78864672007-08-01 22:05:33 +00009059
John McCalldadc5752010-08-24 06:29:42 +00009060ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009061 TypeSourceInfo *TInfo,
9062 OffsetOfComponent *CompPtr,
9063 unsigned NumComponents,
9064 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00009065 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009066 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00009067 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00009068
Chris Lattnerf17bd422007-08-30 17:45:32 +00009069 // We must have at least one component that refers to the type, and the first
9070 // one is known to be a field designator. Verify that the ArgTy represents
9071 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009072 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00009073 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9074 << ArgTy << TypeRange);
9075
9076 // Type must be complete per C99 7.17p3 because a declaring a variable
9077 // with an incomplete type would be ill-formed.
9078 if (!Dependent
9079 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009080 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor882211c2010-04-28 22:16:22 +00009081 return ExprError();
9082
Chris Lattner78502cf2007-08-31 21:49:13 +00009083 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9084 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00009085 // FIXME: This diagnostic isn't actually visible because the location is in
9086 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00009087 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00009088 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9089 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00009090
9091 bool DidWarnAboutNonPOD = false;
9092 QualType CurrentType = ArgTy;
9093 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009094 SmallVector<OffsetOfNode, 4> Comps;
9095 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00009096 for (unsigned i = 0; i != NumComponents; ++i) {
9097 const OffsetOfComponent &OC = CompPtr[i];
9098 if (OC.isBrackets) {
9099 // Offset of an array sub-field. TODO: Should we allow vector elements?
9100 if (!CurrentType->isDependentType()) {
9101 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9102 if(!AT)
9103 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9104 << CurrentType);
9105 CurrentType = AT->getElementType();
9106 } else
9107 CurrentType = Context.DependentTy;
9108
Richard Smith9fcc5c32011-10-17 23:29:39 +00009109 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9110 if (IdxRval.isInvalid())
9111 return ExprError();
9112 Expr *Idx = IdxRval.take();
9113
Douglas Gregor882211c2010-04-28 22:16:22 +00009114 // The expression must be an integral expression.
9115 // FIXME: An integral constant expression?
Douglas Gregor882211c2010-04-28 22:16:22 +00009116 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9117 !Idx->getType()->isIntegerType())
9118 return ExprError(Diag(Idx->getLocStart(),
9119 diag::err_typecheck_subscript_not_integer)
9120 << Idx->getSourceRange());
Richard Smitheda612882011-10-17 05:48:07 +00009121
Douglas Gregor882211c2010-04-28 22:16:22 +00009122 // Record this array index.
9123 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smith9fcc5c32011-10-17 23:29:39 +00009124 Exprs.push_back(Idx);
Douglas Gregor882211c2010-04-28 22:16:22 +00009125 continue;
9126 }
9127
9128 // Offset of a field.
9129 if (CurrentType->isDependentType()) {
9130 // We have the offset of a field, but we can't look into the dependent
9131 // type. Just record the identifier of the field.
9132 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9133 CurrentType = Context.DependentTy;
9134 continue;
9135 }
9136
9137 // We need to have a complete type to look into.
9138 if (RequireCompleteType(OC.LocStart, CurrentType,
9139 diag::err_offsetof_incomplete_type))
9140 return ExprError();
9141
9142 // Look for the designated field.
9143 const RecordType *RC = CurrentType->getAs<RecordType>();
9144 if (!RC)
9145 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9146 << CurrentType);
9147 RecordDecl *RD = RC->getDecl();
9148
9149 // C++ [lib.support.types]p5:
9150 // The macro offsetof accepts a restricted set of type arguments in this
9151 // International Standard. type shall be a POD structure or a POD union
9152 // (clause 9).
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009153 // C++11 [support.types]p4:
9154 // If type is not a standard-layout class (Clause 9), the results are
9155 // undefined.
Douglas Gregor882211c2010-04-28 22:16:22 +00009156 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009157 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9158 unsigned DiagID =
9159 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9160 : diag::warn_offsetof_non_pod_type;
9161
9162 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00009163 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009164 PDiag(DiagID)
Douglas Gregor882211c2010-04-28 22:16:22 +00009165 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9166 << CurrentType))
9167 DidWarnAboutNonPOD = true;
9168 }
9169
9170 // Look for the field.
9171 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9172 LookupQualifiedName(R, RD);
9173 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009174 IndirectFieldDecl *IndirectMemberDecl = 0;
9175 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00009176 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00009177 MemberDecl = IndirectMemberDecl->getAnonField();
9178 }
9179
Douglas Gregor882211c2010-04-28 22:16:22 +00009180 if (!MemberDecl)
9181 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9182 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9183 OC.LocEnd));
9184
Douglas Gregor10982ea2010-04-28 22:36:06 +00009185 // C99 7.17p3:
9186 // (If the specified member is a bit-field, the behavior is undefined.)
9187 //
9188 // We diagnose this as an error.
Richard Smithcaf33902011-10-10 18:28:20 +00009189 if (MemberDecl->isBitField()) {
Douglas Gregor10982ea2010-04-28 22:36:06 +00009190 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9191 << MemberDecl->getDeclName()
9192 << SourceRange(BuiltinLoc, RParenLoc);
9193 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9194 return ExprError();
9195 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009196
9197 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009198 if (IndirectMemberDecl)
9199 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009200
Douglas Gregord1702062010-04-29 00:18:15 +00009201 // If the member was found in a base class, introduce OffsetOfNodes for
9202 // the base class indirections.
9203 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9204 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009205 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00009206 CXXBasePath &Path = Paths.front();
9207 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9208 B != BEnd; ++B)
9209 Comps.push_back(OffsetOfNode(B->Base));
9210 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009211
Francois Pichet783dd6e2010-11-21 06:08:52 +00009212 if (IndirectMemberDecl) {
9213 for (IndirectFieldDecl::chain_iterator FI =
9214 IndirectMemberDecl->chain_begin(),
9215 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9216 assert(isa<FieldDecl>(*FI));
9217 Comps.push_back(OffsetOfNode(OC.LocStart,
9218 cast<FieldDecl>(*FI), OC.LocEnd));
9219 }
9220 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00009221 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00009222
Douglas Gregor882211c2010-04-28 22:16:22 +00009223 CurrentType = MemberDecl->getType().getNonReferenceType();
9224 }
9225
9226 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00009227 TInfo, Comps, Exprs, RParenLoc));
Douglas Gregor882211c2010-04-28 22:16:22 +00009228}
Mike Stump4e1f26a2009-02-19 03:04:26 +00009229
John McCalldadc5752010-08-24 06:29:42 +00009230ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00009231 SourceLocation BuiltinLoc,
9232 SourceLocation TypeLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009233 ParsedType ParsedArgTy,
John McCall36226622010-10-12 02:09:17 +00009234 OffsetOfComponent *CompPtr,
9235 unsigned NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00009236 SourceLocation RParenLoc) {
John McCall36226622010-10-12 02:09:17 +00009237
Douglas Gregor882211c2010-04-28 22:16:22 +00009238 TypeSourceInfo *ArgTInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00009239 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor882211c2010-04-28 22:16:22 +00009240 if (ArgTy.isNull())
9241 return ExprError();
9242
Eli Friedman06dcfd92010-08-05 10:15:45 +00009243 if (!ArgTInfo)
9244 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9245
9246 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00009247 RParenLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00009248}
9249
9250
John McCalldadc5752010-08-24 06:29:42 +00009251ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009252 Expr *CondExpr,
9253 Expr *LHSExpr, Expr *RHSExpr,
9254 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00009255 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9256
John McCall7decc9e2010-11-18 06:31:45 +00009257 ExprValueKind VK = VK_RValue;
9258 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009259 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00009260 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00009261 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009262 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00009263 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009264 } else {
9265 // The conditional expression is required to be a constant expression.
9266 llvm::APSInt condEval(32);
Douglas Gregore2b37442012-05-04 22:38:52 +00009267 ExprResult CondICE
9268 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9269 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009270 if (CondICE.isInvalid())
9271 return ExprError();
9272 CondExpr = CondICE.take();
Steve Naroff9efdabc2007-08-03 21:21:27 +00009273
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009274 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00009275 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9276
9277 resType = ActiveExpr->getType();
9278 ValueDependent = ActiveExpr->isValueDependent();
9279 VK = ActiveExpr->getValueKind();
9280 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009281 }
9282
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009283 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00009284 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00009285 resType->isDependentType(),
9286 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00009287}
9288
Steve Naroffc540d662008-09-03 18:15:37 +00009289//===----------------------------------------------------------------------===//
9290// Clang Extensions.
9291//===----------------------------------------------------------------------===//
9292
9293/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuba63ce62011-09-09 01:45:06 +00009294void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009295 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuba63ce62011-09-09 01:45:06 +00009296 PushBlockScope(CurScope, Block);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009297 CurContext->addDecl(Block);
Richard Trieuba63ce62011-09-09 01:45:06 +00009298 if (CurScope)
9299 PushDeclContext(CurScope, Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009300 else
9301 CurContext = Block;
John McCallf1a3c2a2011-11-11 03:19:12 +00009302
Eli Friedman34b49062012-01-26 03:00:14 +00009303 getCurBlock()->HasImplicitReturnType = true;
9304
John McCallf1a3c2a2011-11-11 03:19:12 +00009305 // Enter a new evaluation context to insulate the block from any
9306 // cleanups from the enclosing full-expression.
9307 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009308}
9309
Douglas Gregor7efd007c2012-06-15 16:59:29 +00009310void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9311 Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00009312 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00009313 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009314 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009315
John McCall8cb7bdf2010-06-04 23:28:52 +00009316 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00009317 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00009318
Douglas Gregor7efd007c2012-06-15 16:59:29 +00009319 // FIXME: We should allow unexpanded parameter packs here, but that would,
9320 // in turn, make the block expression contain unexpanded parameter packs.
9321 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9322 // Drop the parameters.
9323 FunctionProtoType::ExtProtoInfo EPI;
9324 EPI.HasTrailingReturn = false;
9325 EPI.TypeQuals |= DeclSpec::TQ_const;
9326 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9327 EPI);
9328 Sig = Context.getTrivialTypeSourceInfo(T);
9329 }
9330
John McCall3882ace2011-01-05 12:14:39 +00009331 // GetTypeForDeclarator always produces a function type for a block
9332 // literal signature. Furthermore, it is always a FunctionProtoType
9333 // unless the function was written with a typedef.
9334 assert(T->isFunctionType() &&
9335 "GetTypeForDeclarator made a non-function block signature");
9336
9337 // Look for an explicit signature in that function type.
9338 FunctionProtoTypeLoc ExplicitSignature;
9339
9340 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9341 if (isa<FunctionProtoTypeLoc>(tmp)) {
9342 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9343
9344 // Check whether that explicit signature was synthesized by
9345 // GetTypeForDeclarator. If so, don't save that as part of the
9346 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00009347 if (ExplicitSignature.getLocalRangeBegin() ==
9348 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00009349 // This would be much cheaper if we stored TypeLocs instead of
9350 // TypeSourceInfos.
9351 TypeLoc Result = ExplicitSignature.getResultLoc();
9352 unsigned Size = Result.getFullDataSize();
9353 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9354 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9355
9356 ExplicitSignature = FunctionProtoTypeLoc();
9357 }
John McCalla3ccba02010-06-04 11:21:44 +00009358 }
Mike Stump11289f42009-09-09 15:08:12 +00009359
John McCall3882ace2011-01-05 12:14:39 +00009360 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9361 CurBlock->FunctionType = T;
9362
9363 const FunctionType *Fn = T->getAs<FunctionType>();
9364 QualType RetTy = Fn->getResultType();
9365 bool isVariadic =
9366 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9367
John McCall8e346702010-06-04 19:02:56 +00009368 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00009369
John McCalla3ccba02010-06-04 11:21:44 +00009370 // Don't allow returning a objc interface by value.
9371 if (RetTy->isObjCObjectType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009372 Diag(ParamInfo.getLocStart(),
John McCalla3ccba02010-06-04 11:21:44 +00009373 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9374 return;
9375 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009376
John McCalla3ccba02010-06-04 11:21:44 +00009377 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00009378 // return type. TODO: what should we do with declarators like:
9379 // ^ * { ... }
9380 // If the answer is "apply template argument deduction"....
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009381 if (RetTy != Context.DependentTy) {
John McCalla3ccba02010-06-04 11:21:44 +00009382 CurBlock->ReturnType = RetTy;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009383 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman34b49062012-01-26 03:00:14 +00009384 CurBlock->HasImplicitReturnType = false;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009385 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009386
John McCalla3ccba02010-06-04 11:21:44 +00009387 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009388 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00009389 if (ExplicitSignature) {
9390 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9391 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009392 if (Param->getIdentifier() == 0 &&
9393 !Param->isImplicit() &&
9394 !Param->isInvalidDecl() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00009395 !getLangOpts().CPlusPlus)
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009396 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00009397 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009398 }
John McCalla3ccba02010-06-04 11:21:44 +00009399
9400 // Fake up parameter variables if we have a typedef, like
9401 // ^ fntype { ... }
9402 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9403 for (FunctionProtoType::arg_type_iterator
9404 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9405 ParmVarDecl *Param =
9406 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009407 ParamInfo.getLocStart(),
John McCalla3ccba02010-06-04 11:21:44 +00009408 *I);
John McCall8e346702010-06-04 19:02:56 +00009409 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00009410 }
Steve Naroffc540d662008-09-03 18:15:37 +00009411 }
John McCalla3ccba02010-06-04 11:21:44 +00009412
John McCall8e346702010-06-04 19:02:56 +00009413 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00009414 if (!Params.empty()) {
David Blaikie9c70e042011-09-21 18:16:56 +00009415 CurBlock->TheDecl->setParams(Params);
Douglas Gregorb524d902010-11-01 18:37:59 +00009416 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9417 CurBlock->TheDecl->param_end(),
9418 /*CheckParameterNames=*/false);
9419 }
9420
John McCalla3ccba02010-06-04 11:21:44 +00009421 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00009422 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00009423
John McCalla3ccba02010-06-04 11:21:44 +00009424 // Put the parameter variables in scope. We can bail out immediately
9425 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00009426 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00009427 return;
9428
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009429 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00009430 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9431 (*AI)->setOwningFunction(CurBlock->TheDecl);
9432
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009433 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009434 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009435 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00009436
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009437 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009438 }
John McCallf7b2fb52010-01-22 00:28:27 +00009439 }
Steve Naroffc540d662008-09-03 18:15:37 +00009440}
9441
9442/// ActOnBlockError - If there is an error parsing a block, this callback
9443/// is invoked to pop the information about the block from the action impl.
9444void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCallf1a3c2a2011-11-11 03:19:12 +00009445 // Leave the expression-evaluation context.
9446 DiscardCleanupsInEvaluationContext();
9447 PopExpressionEvaluationContext();
9448
Steve Naroffc540d662008-09-03 18:15:37 +00009449 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00009450 PopDeclContext();
Eli Friedman71c80552012-01-05 03:35:19 +00009451 PopFunctionScopeInfo();
Steve Naroffc540d662008-09-03 18:15:37 +00009452}
9453
9454/// ActOnBlockStmtExpr - This is called when the body of a block statement
9455/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00009456ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00009457 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00009458 // If blocks are disabled, emit an error.
9459 if (!LangOpts.Blocks)
9460 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00009461
John McCallf1a3c2a2011-11-11 03:19:12 +00009462 // Leave the expression-evaluation context.
John McCall85110b42012-03-08 22:00:17 +00009463 if (hasAnyUnrecoverableErrorsInThisFunction())
9464 DiscardCleanupsInEvaluationContext();
John McCallf1a3c2a2011-11-11 03:19:12 +00009465 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9466 PopExpressionEvaluationContext();
9467
Douglas Gregor9a28e842010-03-01 23:15:13 +00009468 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Jordan Rosed39e5f12012-07-02 21:19:23 +00009469
9470 if (BSI->HasImplicitReturnType)
9471 deduceClosureReturnType(*BSI);
9472
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009473 PopDeclContext();
9474
Steve Naroffc540d662008-09-03 18:15:37 +00009475 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00009476 if (!BSI->ReturnType.isNull())
9477 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009478
Mike Stump3bf1ab42009-07-28 22:04:01 +00009479 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00009480 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00009481
John McCallc63de662011-02-02 13:00:07 +00009482 // Set the captured variables on the block.
Eli Friedman20139d32012-01-11 02:36:31 +00009483 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9484 SmallVector<BlockDecl::Capture, 4> Captures;
9485 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9486 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9487 if (Cap.isThisCapture())
9488 continue;
Eli Friedman24af8502012-02-03 22:47:37 +00009489 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedman20139d32012-01-11 02:36:31 +00009490 Cap.isNested(), Cap.getCopyExpr());
9491 Captures.push_back(NewCap);
9492 }
9493 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9494 BSI->CXXThisCaptureIndex != 0);
John McCallc63de662011-02-02 13:00:07 +00009495
John McCall8e346702010-06-04 19:02:56 +00009496 // If the user wrote a function type in some form, try to use that.
9497 if (!BSI->FunctionType.isNull()) {
9498 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9499
9500 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9501 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9502
9503 // Turn protoless block types into nullary block types.
9504 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009505 FunctionProtoType::ExtProtoInfo EPI;
9506 EPI.ExtInfo = Ext;
9507 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009508
9509 // Otherwise, if we don't need to change anything about the function type,
9510 // preserve its sugar structure.
9511 } else if (FTy->getResultType() == RetTy &&
9512 (!NoReturn || FTy->getNoReturnAttr())) {
9513 BlockTy = BSI->FunctionType;
9514
9515 // Otherwise, make the minimal modifications to the function type.
9516 } else {
9517 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00009518 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9519 EPI.TypeQuals = 0; // FIXME: silently?
9520 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00009521 BlockTy = Context.getFunctionType(RetTy,
9522 FPT->arg_type_begin(),
9523 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00009524 EPI);
John McCall8e346702010-06-04 19:02:56 +00009525 }
9526
9527 // If we don't have a function type, just build one from nothing.
9528 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00009529 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00009530 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00009531 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009532 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009533
John McCall8e346702010-06-04 19:02:56 +00009534 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9535 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00009536 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009537
Chris Lattner45542ea2009-04-19 05:28:12 +00009538 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00009539 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor5d944db2012-08-17 05:12:08 +00009540 !hasAnyUnrecoverableErrorsInThisFunction() &&
9541 !PP.isCodeCompletionEnabled())
John McCallb268a282010-08-23 23:25:46 +00009542 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00009543
Chris Lattner60f84492011-02-17 23:58:47 +00009544 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009545
Jordan Rosed39e5f12012-07-02 21:19:23 +00009546 // Try to apply the named return value optimization. We have to check again
9547 // if we can do this, though, because blocks keep return statements around
9548 // to deduce an implicit return type.
9549 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9550 !BSI->TheDecl->isDependentContext())
9551 computeNRVO(Body, getCurBlock());
Douglas Gregor49695f02011-09-06 20:46:03 +00009552
Benjamin Kramera4fb8362011-07-12 14:11:05 +00009553 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9554 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedman71c80552012-01-05 03:35:19 +00009555 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramera4fb8362011-07-12 14:11:05 +00009556
John McCall28fc7092011-11-10 05:35:25 +00009557 // If the block isn't obviously global, i.e. it captures anything at
John McCalld2393872012-04-13 01:08:17 +00009558 // all, then we need to do a few things in the surrounding context:
John McCall28fc7092011-11-10 05:35:25 +00009559 if (Result->getBlockDecl()->hasCaptures()) {
John McCalld2393872012-04-13 01:08:17 +00009560 // First, this expression has a new cleanup object.
John McCall28fc7092011-11-10 05:35:25 +00009561 ExprCleanupObjects.push_back(Result->getBlockDecl());
9562 ExprNeedsCleanups = true;
John McCalld2393872012-04-13 01:08:17 +00009563
9564 // It also gets a branch-protected scope if any of the captured
9565 // variables needs destruction.
9566 for (BlockDecl::capture_const_iterator
9567 ci = Result->getBlockDecl()->capture_begin(),
9568 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9569 const VarDecl *var = ci->getVariable();
9570 if (var->getType().isDestructedType() != QualType::DK_none) {
9571 getCurFunction()->setHasBranchProtectedScope();
9572 break;
9573 }
9574 }
John McCall28fc7092011-11-10 05:35:25 +00009575 }
Fariborz Jahanian197c68c2012-03-06 18:41:35 +00009576
Douglas Gregor9a28e842010-03-01 23:15:13 +00009577 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00009578}
9579
John McCalldadc5752010-08-24 06:29:42 +00009580ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009581 Expr *E, ParsedType Ty,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009582 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00009583 TypeSourceInfo *TInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00009584 GetTypeFromParser(Ty, &TInfo);
9585 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00009586}
9587
John McCalldadc5752010-08-24 06:29:42 +00009588ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00009589 Expr *E, TypeSourceInfo *TInfo,
9590 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00009591 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00009592
Eli Friedman121ba0c2008-08-09 23:32:40 +00009593 // Get the va_list type
9594 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00009595 if (VaListType->isArrayType()) {
9596 // Deal with implicit array decay; for example, on x86-64,
9597 // va_list is an array, but it's supposed to decay to
9598 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00009599 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00009600 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00009601 ExprResult Result = UsualUnaryConversions(E);
9602 if (Result.isInvalid())
9603 return ExprError();
9604 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00009605 } else {
9606 // Otherwise, the va_list argument must be an l-value because
9607 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00009608 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00009609 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00009610 return ExprError();
9611 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00009612
Douglas Gregorad3150c2009-05-19 23:10:31 +00009613 if (!E->isTypeDependent() &&
9614 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009615 return ExprError(Diag(E->getLocStart(),
9616 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00009617 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00009618 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009619
David Majnemerc75d1a12011-06-14 05:17:32 +00009620 if (!TInfo->getType()->isDependentType()) {
9621 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009622 diag::err_second_parameter_to_va_arg_incomplete,
9623 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +00009624 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00009625
David Majnemerc75d1a12011-06-14 05:17:32 +00009626 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregorae298422012-05-04 17:09:59 +00009627 TInfo->getType(),
9628 diag::err_second_parameter_to_va_arg_abstract,
9629 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +00009630 return ExprError();
9631
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009632 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00009633 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009634 TInfo->getType()->isObjCLifetimeType()
9635 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9636 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00009637 << TInfo->getType()
9638 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009639 }
Eli Friedman6290ae42011-07-11 21:45:59 +00009640
9641 // Check for va_arg where arguments of the given type will be promoted
9642 // (i.e. this va_arg is guaranteed to have undefined behavior).
9643 QualType PromoteType;
9644 if (TInfo->getType()->isPromotableIntegerType()) {
9645 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9646 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9647 PromoteType = QualType();
9648 }
9649 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9650 PromoteType = Context.DoubleTy;
9651 if (!PromoteType.isNull())
9652 Diag(TInfo->getTypeLoc().getBeginLoc(),
9653 diag::warn_second_parameter_to_va_arg_never_compatible)
9654 << TInfo->getType()
9655 << PromoteType
9656 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00009657 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009658
Abramo Bagnara27db2392010-08-10 10:06:15 +00009659 QualType T = TInfo->getType().getNonLValueExprType(Context);
9660 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009661}
9662
John McCalldadc5752010-08-24 06:29:42 +00009663ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009664 // The type of __null will be int or long, depending on the size of
9665 // pointers on the target.
9666 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009667 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9668 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009669 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009670 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009671 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009672 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009673 Ty = Context.LongLongTy;
9674 else {
David Blaikie83d382b2011-09-23 05:06:16 +00009675 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009676 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009677
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009678 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009679}
9680
Alexis Huntc46382e2010-04-28 23:02:27 +00009681static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009682 Expr *SrcExpr, FixItHint &Hint) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009683 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonace5d072009-11-10 04:46:30 +00009684 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009685
Anders Carlssonace5d072009-11-10 04:46:30 +00009686 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9687 if (!PT)
9688 return;
9689
9690 // Check if the destination is of type 'id'.
9691 if (!PT->isObjCIdType()) {
9692 // Check if the destination is the 'NSString' interface.
9693 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9694 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9695 return;
9696 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009697
John McCallfe96e0b2011-11-06 09:01:30 +00009698 // Ignore any parens, implicit casts (should only be
9699 // array-to-pointer decays), and not-so-opaque values. The last is
9700 // important for making this trigger for property assignments.
9701 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9702 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9703 if (OV->getSourceExpr())
9704 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9705
9706 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregorfb65e592011-07-27 05:40:30 +00009707 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00009708 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009709
Douglas Gregora771f462010-03-31 17:46:05 +00009710 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009711}
9712
Chris Lattner9bad62c2008-01-04 18:04:52 +00009713bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9714 SourceLocation Loc,
9715 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009716 Expr *SrcExpr, AssignmentAction Action,
9717 bool *Complained) {
9718 if (Complained)
9719 *Complained = false;
9720
Chris Lattner9bad62c2008-01-04 18:04:52 +00009721 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00009722 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009723 bool isInvalid = false;
Eli Friedman381f4312012-02-29 20:59:56 +00009724 unsigned DiagKind = 0;
Douglas Gregora771f462010-03-31 17:46:05 +00009725 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00009726 ConversionFixItGenerator ConvHints;
9727 bool MayHaveConvFixit = false;
Richard Trieucaff2472011-11-23 22:32:32 +00009728 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009729
Chris Lattner9bad62c2008-01-04 18:04:52 +00009730 switch (ConvTy) {
Fariborz Jahanian268fec12012-07-17 18:00:08 +00009731 case Compatible:
9732 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
9733 return false;
9734
Chris Lattner940cfeb2008-01-04 18:22:42 +00009735 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009736 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00009737 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9738 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009739 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009740 case IntToPointer:
9741 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00009742 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9743 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009744 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009745 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009746 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009747 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00009748 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9749 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00009750 if (Hint.isNull() && !CheckInferredResultType) {
9751 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9752 }
9753 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009754 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009755 case IncompatiblePointerSign:
9756 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9757 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009758 case FunctionVoidPointer:
9759 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9760 break;
John McCall4fff8f62011-02-01 00:10:29 +00009761 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009762 // Perform array-to-pointer decay if necessary.
9763 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9764
John McCall4fff8f62011-02-01 00:10:29 +00009765 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9766 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9767 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9768 DiagKind = diag::err_typecheck_incompatible_address_space;
9769 break;
John McCall31168b02011-06-15 23:02:42 +00009770
9771
9772 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009773 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00009774 break;
John McCall4fff8f62011-02-01 00:10:29 +00009775 }
9776
9777 llvm_unreachable("unknown error case for discarding qualifiers!");
9778 // fallthrough
9779 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009780 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009781 // If the qualifiers lost were because we were applying the
9782 // (deprecated) C++ conversion from a string literal to a char*
9783 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9784 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009785 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009786 // bit of refactoring (so that the second argument is an
9787 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009788 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009789 // C++ semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009790 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009791 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9792 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009793 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9794 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009795 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009796 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009797 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009798 case IntToBlockPointer:
9799 DiagKind = diag::err_int_to_block_pointer;
9800 break;
9801 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009802 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009803 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009804 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009805 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009806 // it can give a more specific diagnostic.
9807 DiagKind = diag::warn_incompatible_qualified_id;
9808 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009809 case IncompatibleVectors:
9810 DiagKind = diag::warn_incompatible_vectors;
9811 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00009812 case IncompatibleObjCWeakRef:
9813 DiagKind = diag::err_arc_weak_unavailable_assign;
9814 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009815 case Incompatible:
9816 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00009817 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9818 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009819 isInvalid = true;
Richard Trieucaff2472011-11-23 22:32:32 +00009820 MayHaveFunctionDiff = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009821 break;
9822 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009823
Douglas Gregorc68e1402010-04-09 00:35:39 +00009824 QualType FirstType, SecondType;
9825 switch (Action) {
9826 case AA_Assigning:
9827 case AA_Initializing:
9828 // The destination type comes first.
9829 FirstType = DstType;
9830 SecondType = SrcType;
9831 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009832
Douglas Gregorc68e1402010-04-09 00:35:39 +00009833 case AA_Returning:
9834 case AA_Passing:
9835 case AA_Converting:
9836 case AA_Sending:
9837 case AA_Casting:
9838 // The source type comes first.
9839 FirstType = SrcType;
9840 SecondType = DstType;
9841 break;
9842 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009843
Anna Zaks3b402712011-07-28 19:51:27 +00009844 PartialDiagnostic FDiag = PDiag(DiagKind);
9845 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9846
9847 // If we can fix the conversion, suggest the FixIts.
9848 assert(ConvHints.isNull() || Hint.isNull());
9849 if (!ConvHints.isNull()) {
Benjamin Kramer490afa62012-01-14 21:05:10 +00009850 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9851 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks3b402712011-07-28 19:51:27 +00009852 FDiag << *HI;
9853 } else {
9854 FDiag << Hint;
9855 }
9856 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9857
Richard Trieucaff2472011-11-23 22:32:32 +00009858 if (MayHaveFunctionDiff)
9859 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9860
Anna Zaks3b402712011-07-28 19:51:27 +00009861 Diag(Loc, FDiag);
9862
Richard Trieucaff2472011-11-23 22:32:32 +00009863 if (SecondType == Context.OverloadTy)
9864 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9865 FirstType);
9866
Douglas Gregor33823722011-06-11 01:09:30 +00009867 if (CheckInferredResultType)
9868 EmitRelatedResultTypeNote(SrcExpr);
9869
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009870 if (Complained)
9871 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009872 return isInvalid;
9873}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009874
Richard Smithf4c51d92012-02-04 09:53:13 +00009875ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9876 llvm::APSInt *Result) {
Douglas Gregore2b37442012-05-04 22:38:52 +00009877 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9878 public:
9879 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9880 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9881 }
9882 } Diagnoser;
9883
9884 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9885}
9886
9887ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9888 llvm::APSInt *Result,
9889 unsigned DiagID,
9890 bool AllowFold) {
9891 class IDDiagnoser : public VerifyICEDiagnoser {
9892 unsigned DiagID;
9893
9894 public:
9895 IDDiagnoser(unsigned DiagID)
9896 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9897
9898 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9899 S.Diag(Loc, DiagID) << SR;
9900 }
9901 } Diagnoser(DiagID);
9902
9903 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9904}
9905
9906void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9907 SourceRange SR) {
9908 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smithf4c51d92012-02-04 09:53:13 +00009909}
9910
Benjamin Kramer33adaae2012-04-18 14:22:41 +00009911ExprResult
9912Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregore2b37442012-05-04 22:38:52 +00009913 VerifyICEDiagnoser &Diagnoser,
9914 bool AllowFold) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009915 SourceLocation DiagLoc = E->getLocStart();
Richard Smithf4c51d92012-02-04 09:53:13 +00009916
David Blaikiebbafb8a2012-03-11 07:00:24 +00009917 if (getLangOpts().CPlusPlus0x) {
Richard Smithf4c51d92012-02-04 09:53:13 +00009918 // C++11 [expr.const]p5:
9919 // If an expression of literal class type is used in a context where an
9920 // integral constant expression is required, then that class type shall
9921 // have a single non-explicit conversion function to an integral or
9922 // unscoped enumeration type
9923 ExprResult Converted;
Douglas Gregore2b37442012-05-04 22:38:52 +00009924 if (!Diagnoser.Suppress) {
9925 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9926 public:
9927 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9928
9929 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9930 QualType T) {
9931 return S.Diag(Loc, diag::err_ice_not_integral) << T;
9932 }
9933
9934 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9935 SourceLocation Loc,
9936 QualType T) {
9937 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
9938 }
9939
9940 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9941 SourceLocation Loc,
9942 QualType T,
9943 QualType ConvTy) {
9944 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
9945 }
9946
9947 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9948 CXXConversionDecl *Conv,
9949 QualType ConvTy) {
9950 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9951 << ConvTy->isEnumeralType() << ConvTy;
9952 }
9953
9954 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9955 QualType T) {
9956 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
9957 }
9958
9959 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9960 CXXConversionDecl *Conv,
9961 QualType ConvTy) {
9962 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9963 << ConvTy->isEnumeralType() << ConvTy;
9964 }
9965
9966 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9967 SourceLocation Loc,
9968 QualType T,
9969 QualType ConvTy) {
9970 return DiagnosticBuilder::getEmpty();
9971 }
9972 } ConvertDiagnoser;
9973
9974 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9975 ConvertDiagnoser,
9976 /*AllowScopedEnumerations*/ false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009977 } else {
9978 // The caller wants to silently enquire whether this is an ICE. Don't
9979 // produce any diagnostics if it isn't.
Douglas Gregore2b37442012-05-04 22:38:52 +00009980 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
9981 public:
9982 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
9983
9984 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9985 QualType T) {
9986 return DiagnosticBuilder::getEmpty();
9987 }
9988
9989 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9990 SourceLocation Loc,
9991 QualType T) {
9992 return DiagnosticBuilder::getEmpty();
9993 }
9994
9995 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9996 SourceLocation Loc,
9997 QualType T,
9998 QualType ConvTy) {
9999 return DiagnosticBuilder::getEmpty();
10000 }
10001
10002 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10003 CXXConversionDecl *Conv,
10004 QualType ConvTy) {
10005 return DiagnosticBuilder::getEmpty();
10006 }
10007
10008 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10009 QualType T) {
10010 return DiagnosticBuilder::getEmpty();
10011 }
10012
10013 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10014 CXXConversionDecl *Conv,
10015 QualType ConvTy) {
10016 return DiagnosticBuilder::getEmpty();
10017 }
10018
10019 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10020 SourceLocation Loc,
10021 QualType T,
10022 QualType ConvTy) {
10023 return DiagnosticBuilder::getEmpty();
10024 }
10025 } ConvertDiagnoser;
10026
10027 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10028 ConvertDiagnoser, false);
Richard Smithf4c51d92012-02-04 09:53:13 +000010029 }
10030 if (Converted.isInvalid())
10031 return Converted;
10032 E = Converted.take();
10033 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
10034 return ExprError();
10035 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10036 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregore2b37442012-05-04 22:38:52 +000010037 if (!Diagnoser.Suppress)
10038 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithf4c51d92012-02-04 09:53:13 +000010039 return ExprError();
10040 }
10041
Richard Smith902ca212011-12-14 23:32:26 +000010042 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10043 // in the non-ICE case.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010044 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
Richard Smithf4c51d92012-02-04 09:53:13 +000010045 if (Result)
10046 *Result = E->EvaluateKnownConstInt(Context);
10047 return Owned(E);
Eli Friedmanbb967cc2009-04-25 22:26:58 +000010048 }
10049
Anders Carlssone54e8a12008-11-30 19:50:32 +000010050 Expr::EvalResult EvalResult;
Richard Smith92b1ce02011-12-12 09:28:41 +000010051 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
10052 EvalResult.Diag = &Notes;
Anders Carlssone54e8a12008-11-30 19:50:32 +000010053
Richard Smith902ca212011-12-14 23:32:26 +000010054 // Try to evaluate the expression, and produce diagnostics explaining why it's
10055 // not a constant expression as a side-effect.
10056 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10057 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10058
10059 // In C++11, we can rely on diagnostics being produced for any expression
10060 // which is not a constant expression. If no diagnostics were produced, then
10061 // this is a constant expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010062 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
Richard Smith902ca212011-12-14 23:32:26 +000010063 if (Result)
10064 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +000010065 return Owned(E);
10066 }
10067
10068 // If our only note is the usual "invalid subexpression" note, just point
10069 // the caret at its location rather than producing an essentially
10070 // redundant note.
10071 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10072 diag::note_invalid_subexpr_in_const_expr) {
10073 DiagLoc = Notes[0].first;
10074 Notes.clear();
Richard Smith902ca212011-12-14 23:32:26 +000010075 }
10076
10077 if (!Folded || !AllowFold) {
Douglas Gregore2b37442012-05-04 22:38:52 +000010078 if (!Diagnoser.Suppress) {
10079 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith92b1ce02011-12-12 09:28:41 +000010080 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10081 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone54e8a12008-11-30 19:50:32 +000010082 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000010083
Richard Smithf4c51d92012-02-04 09:53:13 +000010084 return ExprError();
Anders Carlssone54e8a12008-11-30 19:50:32 +000010085 }
10086
Douglas Gregore2b37442012-05-04 22:38:52 +000010087 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith2ec40612012-01-15 03:51:30 +000010088 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10089 Diag(Notes[I].first, Notes[I].second);
Mike Stump4e1f26a2009-02-19 03:04:26 +000010090
Anders Carlssone54e8a12008-11-30 19:50:32 +000010091 if (Result)
10092 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +000010093 return Owned(E);
Anders Carlssone54e8a12008-11-30 19:50:32 +000010094}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010095
Eli Friedman456f0182012-01-20 01:26:23 +000010096namespace {
10097 // Handle the case where we conclude a expression which we speculatively
10098 // considered to be unevaluated is actually evaluated.
10099 class TransformToPE : public TreeTransform<TransformToPE> {
10100 typedef TreeTransform<TransformToPE> BaseTransform;
10101
10102 public:
10103 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10104
10105 // Make sure we redo semantic analysis
10106 bool AlwaysRebuild() { return true; }
10107
Eli Friedman5f0ca242012-02-06 23:29:57 +000010108 // Make sure we handle LabelStmts correctly.
10109 // FIXME: This does the right thing, but maybe we need a more general
10110 // fix to TreeTransform?
10111 StmtResult TransformLabelStmt(LabelStmt *S) {
10112 S->getDecl()->setStmt(0);
10113 return BaseTransform::TransformLabelStmt(S);
10114 }
10115
Eli Friedman456f0182012-01-20 01:26:23 +000010116 // We need to special-case DeclRefExprs referring to FieldDecls which
10117 // are not part of a member pointer formation; normal TreeTransforming
10118 // doesn't catch this case because of the way we represent them in the AST.
10119 // FIXME: This is a bit ugly; is it really the best way to handle this
10120 // case?
10121 //
10122 // Error on DeclRefExprs referring to FieldDecls.
10123 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10124 if (isa<FieldDecl>(E->getDecl()) &&
David Blaikie131fcb42012-08-06 22:47:24 +000010125 !SemaRef.isUnevaluatedContext())
Eli Friedman456f0182012-01-20 01:26:23 +000010126 return SemaRef.Diag(E->getLocation(),
10127 diag::err_invalid_non_static_member_use)
10128 << E->getDecl() << E->getSourceRange();
10129
10130 return BaseTransform::TransformDeclRefExpr(E);
10131 }
10132
10133 // Exception: filter out member pointer formation
10134 ExprResult TransformUnaryOperator(UnaryOperator *E) {
10135 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10136 return E;
10137
10138 return BaseTransform::TransformUnaryOperator(E);
10139 }
10140
Douglas Gregor89625492012-02-09 08:14:43 +000010141 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10142 // Lambdas never need to be transformed.
10143 return E;
10144 }
Eli Friedman456f0182012-01-20 01:26:23 +000010145 };
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000010146}
10147
Eli Friedman456f0182012-01-20 01:26:23 +000010148ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
Eli Friedmane4f22df2012-02-29 04:03:55 +000010149 assert(ExprEvalContexts.back().Context == Unevaluated &&
10150 "Should only transform unevaluated expressions");
Eli Friedman456f0182012-01-20 01:26:23 +000010151 ExprEvalContexts.back().Context =
10152 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10153 if (ExprEvalContexts.back().Context == Unevaluated)
10154 return E;
10155 return TransformToPE(*this).TransformExpr(E);
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000010156}
10157
Douglas Gregorff790f12009-11-26 00:44:06 +000010158void
Douglas Gregor7fcbd902012-02-21 00:37:24 +000010159Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smithfd555f62012-02-22 02:04:18 +000010160 Decl *LambdaContextDecl,
10161 bool IsDecltype) {
Douglas Gregorff790f12009-11-26 00:44:06 +000010162 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +000010163 ExpressionEvaluationContextRecord(NewContext,
John McCall28fc7092011-11-10 05:35:25 +000010164 ExprCleanupObjects.size(),
Douglas Gregor7fcbd902012-02-21 00:37:24 +000010165 ExprNeedsCleanups,
Richard Smithfd555f62012-02-22 02:04:18 +000010166 LambdaContextDecl,
10167 IsDecltype));
John McCall31168b02011-06-15 23:02:42 +000010168 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010169 if (!MaybeODRUseExprs.empty())
10170 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010171}
10172
Eli Friedman15681d62012-09-26 04:34:21 +000010173void
10174Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10175 ReuseLambdaContextDecl_t,
10176 bool IsDecltype) {
10177 Decl *LambdaContextDecl = ExprEvalContexts.back().LambdaContextDecl;
10178 PushExpressionEvaluationContext(NewContext, LambdaContextDecl, IsDecltype);
10179}
10180
Richard Trieucfc491d2011-08-02 04:35:43 +000010181void Sema::PopExpressionEvaluationContext() {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010182 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010183
Douglas Gregor89625492012-02-09 08:14:43 +000010184 if (!Rec.Lambdas.empty()) {
10185 if (Rec.Context == Unevaluated) {
10186 // C++11 [expr.prim.lambda]p2:
10187 // A lambda-expression shall not appear in an unevaluated operand
10188 // (Clause 5).
10189 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10190 Diag(Rec.Lambdas[I]->getLocStart(),
10191 diag::err_lambda_unevaluated_operand);
10192 } else {
10193 // Mark the capture expressions odr-used. This was deferred
10194 // during lambda expression creation.
10195 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10196 LambdaExpr *Lambda = Rec.Lambdas[I];
10197 for (LambdaExpr::capture_init_iterator
10198 C = Lambda->capture_init_begin(),
10199 CEnd = Lambda->capture_init_end();
10200 C != CEnd; ++C) {
10201 MarkDeclarationsReferencedInExpr(*C);
10202 }
10203 }
10204 }
10205 }
10206
Douglas Gregorff790f12009-11-26 00:44:06 +000010207 // When are coming out of an unevaluated context, clear out any
10208 // temporaries that we may have created as part of the evaluation of
10209 // the expression in that context: they aren't relevant because they
10210 // will never be constructed.
Richard Smith764d2fe2011-12-20 02:08:33 +000010211 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall28fc7092011-11-10 05:35:25 +000010212 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10213 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +000010214 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010215 CleanupVarDeclMarking();
10216 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCall31168b02011-06-15 23:02:42 +000010217 // Otherwise, merge the contexts together.
10218 } else {
10219 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010220 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10221 Rec.SavedMaybeODRUseExprs.end());
John McCall31168b02011-06-15 23:02:42 +000010222 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010223
10224 // Pop the current expression evaluation context off the stack.
10225 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010226}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010227
John McCall31168b02011-06-15 23:02:42 +000010228void Sema::DiscardCleanupsInEvaluationContext() {
John McCall28fc7092011-11-10 05:35:25 +000010229 ExprCleanupObjects.erase(
10230 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10231 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +000010232 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010233 MaybeODRUseExprs.clear();
John McCall31168b02011-06-15 23:02:42 +000010234}
10235
Eli Friedmane0afc982012-01-21 01:01:51 +000010236ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10237 if (!E->getType()->isVariablyModifiedType())
10238 return E;
10239 return TranformToPotentiallyEvaluated(E);
10240}
10241
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +000010242static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010243 // Do not mark anything as "used" within a dependent context; wait for
10244 // an instantiation.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010245 if (SemaRef.CurContext->isDependentContext())
10246 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010247
Eli Friedmanfa0df832012-02-02 03:46:19 +000010248 switch (SemaRef.ExprEvalContexts.back().Context) {
10249 case Sema::Unevaluated:
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010250 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman02b58512012-01-21 04:44:06 +000010251 // (Depending on how you read the standard, we actually do need to do
10252 // something here for null pointer constants, but the standard's
10253 // definition of a null pointer constant is completely crazy.)
Eli Friedmanfa0df832012-02-02 03:46:19 +000010254 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010255
Eli Friedmanfa0df832012-02-02 03:46:19 +000010256 case Sema::ConstantEvaluated:
10257 case Sema::PotentiallyEvaluated:
Eli Friedman02b58512012-01-21 04:44:06 +000010258 // We are in a potentially evaluated expression (or a constant-expression
10259 // in C++03); we need to do implicit template instantiation, implicitly
10260 // define class members, and mark most declarations as used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010261 return true;
Mike Stump11289f42009-09-09 15:08:12 +000010262
Eli Friedmanfa0df832012-02-02 03:46:19 +000010263 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010264 // Referenced declarations will only be used if the construct in the
10265 // containing expression is used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010266 return false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010267 }
Matt Beaumont-Gay248bc722012-02-02 18:35:35 +000010268 llvm_unreachable("Invalid context");
Eli Friedmanfa0df832012-02-02 03:46:19 +000010269}
10270
10271/// \brief Mark a function referenced, and check whether it is odr-used
10272/// (C++ [basic.def.odr]p2, C99 6.9p3)
10273void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10274 assert(Func && "No function?");
10275
10276 Func->setReferenced();
10277
Richard Smith4a941e22012-02-14 22:25:15 +000010278 // Don't mark this function as used multiple times, unless it's a constexpr
10279 // function which we need to instantiate.
10280 if (Func->isUsed(false) &&
10281 !(Func->isConstexpr() && !Func->getBody() &&
10282 Func->isImplicitlyInstantiable()))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010283 return;
10284
10285 if (!IsPotentiallyEvaluatedContext(*this))
10286 return;
Mike Stump11289f42009-09-09 15:08:12 +000010287
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010288 // Note that this declaration has been used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010289 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010290 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010291 if (Constructor->isDefaultConstructor()) {
10292 if (Constructor->isTrivial())
10293 return;
10294 if (!Constructor->isUsed(false))
10295 DefineImplicitDefaultConstructor(Loc, Constructor);
10296 } else if (Constructor->isCopyConstructor()) {
10297 if (!Constructor->isUsed(false))
10298 DefineImplicitCopyConstructor(Loc, Constructor);
10299 } else if (Constructor->isMoveConstructor()) {
10300 if (!Constructor->isUsed(false))
10301 DefineImplicitMoveConstructor(Loc, Constructor);
10302 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010303 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010304
Douglas Gregor88d292c2010-05-13 16:44:06 +000010305 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010306 } else if (CXXDestructorDecl *Destructor =
10307 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010308 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10309 !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010310 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010311 if (Destructor->isVirtual())
10312 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010313 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010314 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10315 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010316 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010317 if (!MethodDecl->isUsed(false)) {
10318 if (MethodDecl->isCopyAssignmentOperator())
10319 DefineImplicitCopyAssignment(Loc, MethodDecl);
10320 else
10321 DefineImplicitMoveAssignment(Loc, MethodDecl);
10322 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010323 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10324 MethodDecl->getParent()->isLambda()) {
10325 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10326 if (Conversion->isLambdaToBlockPointerConversion())
10327 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10328 else
10329 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010330 } else if (MethodDecl->isVirtual())
10331 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010332 }
John McCall83779672011-02-19 02:53:41 +000010333
Eli Friedmanfa0df832012-02-02 03:46:19 +000010334 // Recursive functions should be marked when used from another function.
10335 // FIXME: Is this really right?
10336 if (CurContext == Func) return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010337
Richard Smithd3b5c9082012-07-27 04:22:15 +000010338 // Resolve the exception specification for any function which is
Richard Smithf623c962012-04-17 00:58:00 +000010339 // used: CodeGen will need it.
Richard Smithd3729422012-04-19 00:08:28 +000010340 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010341 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10342 ResolveExceptionSpec(Loc, FPT);
Richard Smithf623c962012-04-17 00:58:00 +000010343
Eli Friedmanfa0df832012-02-02 03:46:19 +000010344 // Implicit instantiation of function templates and member functions of
10345 // class templates.
10346 if (Func->isImplicitlyInstantiable()) {
10347 bool AlreadyInstantiated = false;
Richard Smith4a941e22012-02-14 22:25:15 +000010348 SourceLocation PointOfInstantiation = Loc;
Eli Friedmanfa0df832012-02-02 03:46:19 +000010349 if (FunctionTemplateSpecializationInfo *SpecInfo
10350 = Func->getTemplateSpecializationInfo()) {
10351 if (SpecInfo->getPointOfInstantiation().isInvalid())
10352 SpecInfo->setPointOfInstantiation(Loc);
10353 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000010354 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010355 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000010356 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10357 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010358 } else if (MemberSpecializationInfo *MSInfo
10359 = Func->getMemberSpecializationInfo()) {
10360 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregor06db9f52009-10-12 20:18:28 +000010361 MSInfo->setPointOfInstantiation(Loc);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010362 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000010363 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010364 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000010365 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10366 }
Douglas Gregor06db9f52009-10-12 20:18:28 +000010367 }
Mike Stump11289f42009-09-09 15:08:12 +000010368
Richard Smith4a941e22012-02-14 22:25:15 +000010369 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010370 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10371 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith4a941e22012-02-14 22:25:15 +000010372 PendingLocalImplicitInstantiations.push_back(
10373 std::make_pair(Func, PointOfInstantiation));
10374 else if (Func->isConstexpr())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010375 // Do not defer instantiations of constexpr functions, to avoid the
10376 // expression evaluator needing to call back into Sema if it sees a
10377 // call to such a function.
Richard Smith4a941e22012-02-14 22:25:15 +000010378 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000010379 else {
Richard Smith4a941e22012-02-14 22:25:15 +000010380 PendingInstantiations.push_back(std::make_pair(Func,
10381 PointOfInstantiation));
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000010382 // Notify the consumer that a function was implicitly instantiated.
10383 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10384 }
John McCall83779672011-02-19 02:53:41 +000010385 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010386 } else {
10387 // Walk redefinitions, as some of them may be instantiable.
10388 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10389 e(Func->redecls_end()); i != e; ++i) {
10390 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10391 MarkFunctionReferenced(Loc, *i);
10392 }
Sam Weinigbae69142009-09-11 03:29:30 +000010393 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010394
10395 // Keep track of used but undefined functions.
10396 if (!Func->isPure() && !Func->hasBody() &&
10397 Func->getLinkage() != ExternalLinkage) {
10398 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10399 if (old.isInvalid()) old = Loc;
10400 }
10401
10402 Func->setUsed(true);
10403}
10404
Eli Friedman9bb33f52012-02-03 02:04:35 +000010405static void
10406diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10407 VarDecl *var, DeclContext *DC) {
Eli Friedmandd053f62012-02-07 00:15:00 +000010408 DeclContext *VarDC = var->getDeclContext();
10409
Eli Friedman9bb33f52012-02-03 02:04:35 +000010410 // If the parameter still belongs to the translation unit, then
10411 // we're actually just using one parameter in the declaration of
10412 // the next.
10413 if (isa<ParmVarDecl>(var) &&
Eli Friedmandd053f62012-02-07 00:15:00 +000010414 isa<TranslationUnitDecl>(VarDC))
Eli Friedman9bb33f52012-02-03 02:04:35 +000010415 return;
10416
Eli Friedmandd053f62012-02-07 00:15:00 +000010417 // For C code, don't diagnose about capture if we're not actually in code
10418 // right now; it's impossible to write a non-constant expression outside of
10419 // function context, so we'll get other (more useful) diagnostics later.
10420 //
10421 // For C++, things get a bit more nasty... it would be nice to suppress this
10422 // diagnostic for certain cases like using a local variable in an array bound
10423 // for a member of a local class, but the correct predicate is not obvious.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010424 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman9bb33f52012-02-03 02:04:35 +000010425 return;
10426
Eli Friedmandd053f62012-02-07 00:15:00 +000010427 if (isa<CXXMethodDecl>(VarDC) &&
10428 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10429 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10430 << var->getIdentifier();
10431 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10432 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10433 << var->getIdentifier() << fn->getDeclName();
10434 } else if (isa<BlockDecl>(VarDC)) {
10435 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10436 << var->getIdentifier();
10437 } else {
10438 // FIXME: Is there any other context where a local variable can be
10439 // declared?
10440 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10441 << var->getIdentifier();
10442 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010443
Eli Friedman9bb33f52012-02-03 02:04:35 +000010444 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10445 << var->getIdentifier();
Eli Friedmandd053f62012-02-07 00:15:00 +000010446
10447 // FIXME: Add additional diagnostic info about class etc. which prevents
10448 // capture.
Eli Friedman9bb33f52012-02-03 02:04:35 +000010449}
10450
Douglas Gregor81495f32012-02-12 18:42:33 +000010451/// \brief Capture the given variable in the given lambda expression.
10452static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010453 VarDecl *Var, QualType FieldType,
10454 QualType DeclRefType,
Douglas Gregora8182f92012-05-16 17:01:33 +000010455 SourceLocation Loc,
10456 bool RefersToEnclosingLocal) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010457 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregor81495f32012-02-12 18:42:33 +000010458
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010459 // Build the non-static data member.
10460 FieldDecl *Field
10461 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10462 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Richard Smith2b013182012-06-10 03:12:00 +000010463 0, false, ICIS_NoInit);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010464 Field->setImplicit(true);
10465 Field->setAccess(AS_private);
Douglas Gregor3d23f7882012-02-09 02:12:34 +000010466 Lambda->addDecl(Field);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010467
10468 // C++11 [expr.prim.lambda]p21:
10469 // When the lambda-expression is evaluated, the entities that
10470 // are captured by copy are used to direct-initialize each
10471 // corresponding non-static data member of the resulting closure
10472 // object. (For array members, the array elements are
10473 // direct-initialized in increasing subscript order.) These
10474 // initializations are performed in the (unspecified) order in
10475 // which the non-static data members are declared.
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010476
Douglas Gregor89625492012-02-09 08:14:43 +000010477 // Introduce a new evaluation context for the initialization, so
10478 // that temporaries introduced as part of the capture are retained
10479 // to be re-"exported" from the lambda expression itself.
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010480 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10481
Douglas Gregorf02455e2012-02-10 09:26:04 +000010482 // C++ [expr.prim.labda]p12:
10483 // An entity captured by a lambda-expression is odr-used (3.2) in
10484 // the scope containing the lambda-expression.
Douglas Gregora8182f92012-05-16 17:01:33 +000010485 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10486 DeclRefType, VK_LValue, Loc);
Eli Friedman23b1be92012-03-01 21:32:56 +000010487 Var->setReferenced(true);
Douglas Gregorf02455e2012-02-10 09:26:04 +000010488 Var->setUsed(true);
Douglas Gregor199cec72012-02-09 02:45:47 +000010489
10490 // When the field has array type, create index variables for each
10491 // dimension of the array. We use these index variables to subscript
10492 // the source array, and other clients (e.g., CodeGen) will perform
10493 // the necessary iteration with these index variables.
10494 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor199cec72012-02-09 02:45:47 +000010495 QualType BaseType = FieldType;
10496 QualType SizeType = S.Context.getSizeType();
Douglas Gregor54fcea62012-02-13 16:35:30 +000010497 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor199cec72012-02-09 02:45:47 +000010498 while (const ConstantArrayType *Array
10499 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor199cec72012-02-09 02:45:47 +000010500 // Create the iteration variable for this array index.
10501 IdentifierInfo *IterationVarName = 0;
10502 {
10503 SmallString<8> Str;
10504 llvm::raw_svector_ostream OS(Str);
10505 OS << "__i" << IndexVariables.size();
10506 IterationVarName = &S.Context.Idents.get(OS.str());
10507 }
10508 VarDecl *IterationVar
10509 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10510 IterationVarName, SizeType,
10511 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10512 SC_None, SC_None);
10513 IndexVariables.push_back(IterationVar);
Douglas Gregor54fcea62012-02-13 16:35:30 +000010514 LSI->ArrayIndexVars.push_back(IterationVar);
10515
Douglas Gregor199cec72012-02-09 02:45:47 +000010516 // Create a reference to the iteration variable.
10517 ExprResult IterationVarRef
10518 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10519 assert(!IterationVarRef.isInvalid() &&
10520 "Reference to invented variable cannot fail!");
10521 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10522 assert(!IterationVarRef.isInvalid() &&
10523 "Conversion of invented variable cannot fail!");
10524
10525 // Subscript the array with this iteration variable.
10526 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10527 Ref, Loc, IterationVarRef.take(), Loc);
10528 if (Subscript.isInvalid()) {
10529 S.CleanupVarDeclMarking();
10530 S.DiscardCleanupsInEvaluationContext();
10531 S.PopExpressionEvaluationContext();
10532 return ExprError();
10533 }
10534
10535 Ref = Subscript.take();
10536 BaseType = Array->getElementType();
10537 }
10538
10539 // Construct the entity that we will be initializing. For an array, this
10540 // will be first element in the array, which may require several levels
10541 // of array-subscript entities.
10542 SmallVector<InitializedEntity, 4> Entities;
10543 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor19666fb2012-02-15 16:57:26 +000010544 Entities.push_back(
10545 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor199cec72012-02-09 02:45:47 +000010546 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10547 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10548 0,
10549 Entities.back()));
10550
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010551 InitializationKind InitKind
10552 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor199cec72012-02-09 02:45:47 +000010553 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010554 ExprResult Result(true);
Douglas Gregor199cec72012-02-09 02:45:47 +000010555 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010556 Result = Init.Perform(S, Entities.back(), InitKind, Ref);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010557
10558 // If this initialization requires any cleanups (e.g., due to a
10559 // default argument to a copy constructor), note that for the
10560 // lambda.
10561 if (S.ExprNeedsCleanups)
10562 LSI->ExprNeedsCleanups = true;
10563
10564 // Exit the expression evaluation context used for the capture.
10565 S.CleanupVarDeclMarking();
10566 S.DiscardCleanupsInEvaluationContext();
10567 S.PopExpressionEvaluationContext();
10568 return Result;
Douglas Gregor199cec72012-02-09 02:45:47 +000010569}
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010570
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010571bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10572 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10573 bool BuildAndDiagnose,
10574 QualType &CaptureType,
10575 QualType &DeclRefType) {
10576 bool Nested = false;
Douglas Gregor81495f32012-02-12 18:42:33 +000010577
Eli Friedman24af8502012-02-03 22:47:37 +000010578 DeclContext *DC = CurContext;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010579 if (Var->getDeclContext() == DC) return true;
10580 if (!Var->hasLocalStorage()) return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010581
Douglas Gregor81495f32012-02-12 18:42:33 +000010582 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010583
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010584 // Walk up the stack to determine whether we can capture the variable,
10585 // performing the "simple" checks that don't depend on type. We stop when
10586 // we've either hit the declared scope of the variable or find an existing
10587 // capture of that variable.
10588 CaptureType = Var->getType();
10589 DeclRefType = CaptureType.getNonReferenceType();
10590 bool Explicit = (Kind != TryCapture_Implicit);
10591 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010592 do {
Eli Friedman24af8502012-02-03 22:47:37 +000010593 // Only block literals and lambda expressions can capture; other
Eli Friedman9bb33f52012-02-03 02:04:35 +000010594 // scopes don't work.
Eli Friedman24af8502012-02-03 22:47:37 +000010595 DeclContext *ParentDC;
10596 if (isa<BlockDecl>(DC))
10597 ParentDC = DC->getParent();
10598 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregor81495f32012-02-12 18:42:33 +000010599 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedman24af8502012-02-03 22:47:37 +000010600 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10601 ParentDC = DC->getParent()->getParent();
Douglas Gregor81495f32012-02-12 18:42:33 +000010602 else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010603 if (BuildAndDiagnose)
Douglas Gregor81495f32012-02-12 18:42:33 +000010604 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010605 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000010606 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010607
Eli Friedman24af8502012-02-03 22:47:37 +000010608 CapturingScopeInfo *CSI =
Douglas Gregor81495f32012-02-12 18:42:33 +000010609 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010610
Eli Friedman24af8502012-02-03 22:47:37 +000010611 // Check whether we've already captured it.
Douglas Gregor81495f32012-02-12 18:42:33 +000010612 if (CSI->CaptureMap.count(Var)) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010613 // If we found a capture, any subcaptures are nested.
Eli Friedman9bb33f52012-02-03 02:04:35 +000010614 Nested = true;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010615
10616 // Retrieve the capture type for this variable.
10617 CaptureType = CSI->getCapture(Var).getCaptureType();
10618
10619 // Compute the type of an expression that refers to this variable.
10620 DeclRefType = CaptureType.getNonReferenceType();
10621
10622 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10623 if (Cap.isCopyCapture() &&
10624 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10625 DeclRefType.addConst();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010626 break;
10627 }
10628
Douglas Gregor81495f32012-02-12 18:42:33 +000010629 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010630 bool IsLambda = !IsBlock;
Eli Friedman24af8502012-02-03 22:47:37 +000010631
10632 // Lambdas are not allowed to capture unnamed variables
10633 // (e.g. anonymous unions).
10634 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10635 // assuming that's the intent.
Douglas Gregor81495f32012-02-12 18:42:33 +000010636 if (IsLambda && !Var->getDeclName()) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010637 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010638 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10639 Diag(Var->getLocation(), diag::note_declared_at);
10640 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010641 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000010642 }
10643
10644 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010645 if (Var->getType()->isVariablyModifiedType()) {
10646 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010647 if (IsBlock)
10648 Diag(Loc, diag::err_ref_vm_type);
10649 else
10650 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10651 Diag(Var->getLocation(), diag::note_previous_decl)
10652 << Var->getDeclName();
10653 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010654 return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010655 }
10656
Eli Friedman24af8502012-02-03 22:47:37 +000010657 // Lambdas are not allowed to capture __block variables; they don't
10658 // support the expected semantics.
Douglas Gregor81495f32012-02-12 18:42:33 +000010659 if (IsLambda && HasBlocksAttr) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010660 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010661 Diag(Loc, diag::err_lambda_capture_block)
10662 << Var->getDeclName();
10663 Diag(Var->getLocation(), diag::note_previous_decl)
10664 << Var->getDeclName();
10665 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010666 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000010667 }
10668
Douglas Gregor81495f32012-02-12 18:42:33 +000010669 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10670 // No capture-default
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010671 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010672 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10673 Diag(Var->getLocation(), diag::note_previous_decl)
10674 << Var->getDeclName();
10675 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10676 diag::note_lambda_decl);
10677 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010678 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000010679 }
10680
10681 FunctionScopesIndex--;
10682 DC = ParentDC;
10683 Explicit = false;
10684 } while (!Var->getDeclContext()->Equals(DC));
10685
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010686 // Walk back down the scope stack, computing the type of the capture at
10687 // each step, checking type-specific requirements, and adding captures if
10688 // requested.
10689 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10690 ++I) {
10691 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor812d8f62012-02-18 05:51:20 +000010692
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010693 // Compute the type of the capture and of a reference to the capture within
10694 // this scope.
10695 if (isa<BlockScopeInfo>(CSI)) {
10696 Expr *CopyExpr = 0;
10697 bool ByRef = false;
10698
10699 // Blocks are not allowed to capture arrays.
10700 if (CaptureType->isArrayType()) {
10701 if (BuildAndDiagnose) {
10702 Diag(Loc, diag::err_ref_array_type);
10703 Diag(Var->getLocation(), diag::note_previous_decl)
10704 << Var->getDeclName();
10705 }
10706 return true;
10707 }
10708
John McCall67cd5e02012-03-30 05:23:48 +000010709 // Forbid the block-capture of autoreleasing variables.
10710 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10711 if (BuildAndDiagnose) {
10712 Diag(Loc, diag::err_arc_autoreleasing_capture)
10713 << /*block*/ 0;
10714 Diag(Var->getLocation(), diag::note_previous_decl)
10715 << Var->getDeclName();
10716 }
10717 return true;
10718 }
10719
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010720 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10721 // Block capture by reference does not change the capture or
10722 // declaration reference types.
10723 ByRef = true;
10724 } else {
10725 // Block capture by copy introduces 'const'.
10726 CaptureType = CaptureType.getNonReferenceType().withConst();
10727 DeclRefType = CaptureType;
10728
David Blaikiebbafb8a2012-03-11 07:00:24 +000010729 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010730 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10731 // The capture logic needs the destructor, so make sure we mark it.
10732 // Usually this is unnecessary because most local variables have
10733 // their destructors marked at declaration time, but parameters are
10734 // an exception because it's technically only the call site that
10735 // actually requires the destructor.
10736 if (isa<ParmVarDecl>(Var))
10737 FinalizeVarWithDestructor(Var, Record);
10738
10739 // According to the blocks spec, the capture of a variable from
10740 // the stack requires a const copy constructor. This is not true
10741 // of the copy/move done to move a __block variable to the heap.
John McCall113bee02012-03-10 09:33:50 +000010742 Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010743 DeclRefType.withConst(),
10744 VK_LValue, Loc);
10745 ExprResult Result
10746 = PerformCopyInitialization(
10747 InitializedEntity::InitializeBlock(Var->getLocation(),
10748 CaptureType, false),
10749 Loc, Owned(DeclRef));
10750
10751 // Build a full-expression copy expression if initialization
10752 // succeeded and used a non-trivial constructor. Recover from
10753 // errors by pretending that the copy isn't necessary.
10754 if (!Result.isInvalid() &&
10755 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10756 ->isTrivial()) {
10757 Result = MaybeCreateExprWithCleanups(Result);
10758 CopyExpr = Result.take();
10759 }
10760 }
10761 }
10762 }
10763
10764 // Actually capture the variable.
10765 if (BuildAndDiagnose)
10766 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10767 SourceLocation(), CaptureType, CopyExpr);
10768 Nested = true;
10769 continue;
10770 }
Douglas Gregor812d8f62012-02-18 05:51:20 +000010771
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010772 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10773
10774 // Determine whether we are capturing by reference or by value.
10775 bool ByRef = false;
10776 if (I == N - 1 && Kind != TryCapture_Implicit) {
10777 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedman24af8502012-02-03 22:47:37 +000010778 } else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010779 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedman24af8502012-02-03 22:47:37 +000010780 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010781
10782 // Compute the type of the field that will capture this variable.
10783 if (ByRef) {
10784 // C++11 [expr.prim.lambda]p15:
10785 // An entity is captured by reference if it is implicitly or
10786 // explicitly captured but not captured by copy. It is
10787 // unspecified whether additional unnamed non-static data
10788 // members are declared in the closure type for entities
10789 // captured by reference.
10790 //
10791 // FIXME: It is not clear whether we want to build an lvalue reference
10792 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10793 // to do the former, while EDG does the latter. Core issue 1249 will
10794 // clarify, but for now we follow GCC because it's a more permissive and
10795 // easily defensible position.
10796 CaptureType = Context.getLValueReferenceType(DeclRefType);
10797 } else {
10798 // C++11 [expr.prim.lambda]p14:
10799 // For each entity captured by copy, an unnamed non-static
10800 // data member is declared in the closure type. The
10801 // declaration order of these members is unspecified. The type
10802 // of such a data member is the type of the corresponding
10803 // captured entity if the entity is not a reference to an
10804 // object, or the referenced type otherwise. [Note: If the
10805 // captured entity is a reference to a function, the
10806 // corresponding data member is also a reference to a
10807 // function. - end note ]
10808 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10809 if (!RefType->getPointeeType()->isFunctionType())
10810 CaptureType = RefType->getPointeeType();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010811 }
John McCall67cd5e02012-03-30 05:23:48 +000010812
10813 // Forbid the lambda copy-capture of autoreleasing variables.
10814 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10815 if (BuildAndDiagnose) {
10816 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10817 Diag(Var->getLocation(), diag::note_previous_decl)
10818 << Var->getDeclName();
10819 }
10820 return true;
10821 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010822 }
10823
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010824 // Capture this variable in the lambda.
10825 Expr *CopyExpr = 0;
10826 if (BuildAndDiagnose) {
10827 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
Douglas Gregora8182f92012-05-16 17:01:33 +000010828 DeclRefType, Loc,
10829 I == N-1);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010830 if (!Result.isInvalid())
10831 CopyExpr = Result.take();
10832 }
10833
10834 // Compute the type of a reference to this captured variable.
10835 if (ByRef)
10836 DeclRefType = CaptureType.getNonReferenceType();
10837 else {
10838 // C++ [expr.prim.lambda]p5:
10839 // The closure type for a lambda-expression has a public inline
10840 // function call operator [...]. This function call operator is
10841 // declared const (9.3.1) if and only if the lambda-expression’s
10842 // parameter-declaration-clause is not followed by mutable.
10843 DeclRefType = CaptureType.getNonReferenceType();
10844 if (!LSI->Mutable && !CaptureType->isReferenceType())
10845 DeclRefType.addConst();
10846 }
10847
10848 // Add the capture.
10849 if (BuildAndDiagnose)
10850 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10851 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010852 Nested = true;
10853 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010854
10855 return false;
10856}
10857
10858bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10859 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10860 QualType CaptureType;
10861 QualType DeclRefType;
10862 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10863 /*BuildAndDiagnose=*/true, CaptureType,
10864 DeclRefType);
10865}
10866
10867QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10868 QualType CaptureType;
10869 QualType DeclRefType;
10870
10871 // Determine whether we can capture this variable.
10872 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10873 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10874 return QualType();
10875
10876 return DeclRefType;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010877}
10878
Eli Friedman3bda6b12012-02-02 23:15:15 +000010879static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10880 SourceLocation Loc) {
10881 // Keep track of used but undefined variables.
Eli Friedman130bbd02012-02-04 00:54:05 +000010882 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar9d355812012-03-09 01:51:51 +000010883 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman130bbd02012-02-04 00:54:05 +000010884 Var->getLinkage() != ExternalLinkage &&
10885 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010886 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10887 if (old.isInvalid()) old = Loc;
10888 }
10889
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010890 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010891
Eli Friedman3bda6b12012-02-02 23:15:15 +000010892 Var->setUsed(true);
10893}
10894
10895void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10896 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10897 // an object that satisfies the requirements for appearing in a
10898 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10899 // is immediately applied." This function handles the lvalue-to-rvalue
10900 // conversion part.
10901 MaybeODRUseExprs.erase(E->IgnoreParens());
10902}
10903
Eli Friedmanc6237c62012-02-29 03:16:56 +000010904ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10905 if (!Res.isUsable())
10906 return Res;
10907
10908 // If a constant-expression is a reference to a variable where we delay
10909 // deciding whether it is an odr-use, just assume we will apply the
10910 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
10911 // (a non-type template argument), we have special handling anyway.
10912 UpdateMarkingForLValueToRValue(Res.get());
10913 return Res;
10914}
10915
Eli Friedman3bda6b12012-02-02 23:15:15 +000010916void Sema::CleanupVarDeclMarking() {
10917 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10918 e = MaybeODRUseExprs.end();
10919 i != e; ++i) {
10920 VarDecl *Var;
10921 SourceLocation Loc;
John McCall113bee02012-03-10 09:33:50 +000010922 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010923 Var = cast<VarDecl>(DRE->getDecl());
10924 Loc = DRE->getLocation();
10925 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10926 Var = cast<VarDecl>(ME->getMemberDecl());
10927 Loc = ME->getMemberLoc();
10928 } else {
10929 llvm_unreachable("Unexpcted expression");
10930 }
10931
10932 MarkVarDeclODRUsed(*this, Var, Loc);
10933 }
10934
10935 MaybeODRUseExprs.clear();
10936}
10937
10938// Mark a VarDecl referenced, and perform the necessary handling to compute
10939// odr-uses.
10940static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10941 VarDecl *Var, Expr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010942 Var->setReferenced();
10943
Eli Friedman3bda6b12012-02-02 23:15:15 +000010944 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010945 return;
10946
10947 // Implicit instantiation of static data members of class templates.
Richard Smithd3cf2382012-02-15 02:42:50 +000010948 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010949 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10950 assert(MSInfo && "Missing member specialization information?");
Richard Smithd3cf2382012-02-15 02:42:50 +000010951 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10952 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000010953 (!AlreadyInstantiated ||
10954 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smithd3cf2382012-02-15 02:42:50 +000010955 if (!AlreadyInstantiated) {
10956 // This is a modification of an existing AST node. Notify listeners.
10957 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10958 L->StaticDataMemberInstantiated(Var);
10959 MSInfo->setPointOfInstantiation(Loc);
10960 }
10961 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar9d355812012-03-09 01:51:51 +000010962 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010963 // Do not defer instantiations of variables which could be used in a
10964 // constant expression.
Richard Smithd3cf2382012-02-15 02:42:50 +000010965 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010966 else
Richard Smithd3cf2382012-02-15 02:42:50 +000010967 SemaRef.PendingInstantiations.push_back(
10968 std::make_pair(Var, PointOfInstantiation));
Eli Friedmanfa0df832012-02-02 03:46:19 +000010969 }
10970 }
10971
Eli Friedman3bda6b12012-02-02 23:15:15 +000010972 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10973 // an object that satisfies the requirements for appearing in a
10974 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10975 // is immediately applied." We check the first part here, and
10976 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
10977 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith35ecb362012-03-02 04:14:40 +000010978 // C++03 depends on whether we get the C++03 version correct. This does not
10979 // apply to references, since they are not objects.
Eli Friedman3bda6b12012-02-02 23:15:15 +000010980 const VarDecl *DefVD;
Richard Smith35ecb362012-03-02 04:14:40 +000010981 if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000010982 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Eli Friedman3bda6b12012-02-02 23:15:15 +000010983 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
10984 SemaRef.MaybeODRUseExprs.insert(E);
10985 else
10986 MarkVarDeclODRUsed(SemaRef, Var, Loc);
10987}
Eli Friedmanfa0df832012-02-02 03:46:19 +000010988
Eli Friedman3bda6b12012-02-02 23:15:15 +000010989/// \brief Mark a variable referenced, and check whether it is odr-used
10990/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
10991/// used directly for normal expressions referring to VarDecl.
10992void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
10993 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010994}
10995
10996static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
10997 Decl *D, Expr *E) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010998 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
10999 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
11000 return;
11001 }
11002
Eli Friedmanfa0df832012-02-02 03:46:19 +000011003 SemaRef.MarkAnyDeclReferenced(Loc, D);
Rafael Espindola49e860b2012-06-26 17:45:31 +000011004
11005 // If this is a call to a method via a cast, also mark the method in the
11006 // derived class used in case codegen can devirtualize the call.
11007 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11008 if (!ME)
11009 return;
11010 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
11011 if (!MD)
11012 return;
11013 const Expr *Base = ME->getBase();
Rafael Espindolab7f5a9c2012-06-27 18:18:05 +000011014 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Rafael Espindola49e860b2012-06-26 17:45:31 +000011015 if (!MostDerivedClassDecl)
11016 return;
11017 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
Rafael Espindolaa245edc2012-06-27 17:44:39 +000011018 if (!DM)
11019 return;
Rafael Espindola49e860b2012-06-26 17:45:31 +000011020 SemaRef.MarkAnyDeclReferenced(Loc, DM);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011021}
Eli Friedmanfa0df832012-02-02 03:46:19 +000011022
Eli Friedmanfa0df832012-02-02 03:46:19 +000011023/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
11024void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
11025 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
11026}
11027
11028/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
11029void Sema::MarkMemberReferenced(MemberExpr *E) {
11030 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
11031}
11032
Douglas Gregorf02455e2012-02-10 09:26:04 +000011033/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedmanfa0df832012-02-02 03:46:19 +000011034/// marks the declaration referenced, and performs odr-use checking for functions
11035/// and variables. This method should not be used when building an normal
11036/// expression which refers to a variable.
11037void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
11038 if (VarDecl *VD = dyn_cast<VarDecl>(D))
11039 MarkVariableReferenced(Loc, VD);
11040 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
11041 MarkFunctionReferenced(Loc, FD);
11042 else
11043 D->setReferenced();
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000011044}
Anders Carlsson7f84ed92009-10-09 23:51:55 +000011045
Douglas Gregor5597ab42010-05-07 23:12:07 +000011046namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +000011047 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +000011048 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +000011049 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +000011050 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
11051 Sema &S;
11052 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +000011053
Douglas Gregor5597ab42010-05-07 23:12:07 +000011054 public:
11055 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +000011056
Douglas Gregor5597ab42010-05-07 23:12:07 +000011057 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +000011058
11059 bool TraverseTemplateArgument(const TemplateArgument &Arg);
11060 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +000011061 };
11062}
11063
Chandler Carruthaf80f662010-06-09 08:17:30 +000011064bool MarkReferencedDecls::TraverseTemplateArgument(
11065 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000011066 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +000011067 if (Decl *D = Arg.getAsDecl())
11068 S.MarkAnyDeclReferenced(Loc, D);
Douglas Gregor5597ab42010-05-07 23:12:07 +000011069 }
Chandler Carruthaf80f662010-06-09 08:17:30 +000011070
11071 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +000011072}
11073
Chandler Carruthaf80f662010-06-09 08:17:30 +000011074bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000011075 if (ClassTemplateSpecializationDecl *Spec
11076 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11077 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +000011078 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +000011079 }
11080
Chandler Carruthc65667c2010-06-10 10:31:57 +000011081 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +000011082}
11083
11084void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11085 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +000011086 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +000011087}
11088
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011089namespace {
11090 /// \brief Helper class that marks all of the declarations referenced by
11091 /// potentially-evaluated subexpressions as "referenced".
11092 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11093 Sema &S;
Douglas Gregor680e9e02012-02-21 19:11:17 +000011094 bool SkipLocalVariables;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011095
11096 public:
11097 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11098
Douglas Gregor680e9e02012-02-21 19:11:17 +000011099 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11100 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011101
11102 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregor680e9e02012-02-21 19:11:17 +000011103 // If we were asked not to visit local variables, don't.
11104 if (SkipLocalVariables) {
11105 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11106 if (VD->hasLocalStorage())
11107 return;
11108 }
11109
Eli Friedmanfa0df832012-02-02 03:46:19 +000011110 S.MarkDeclRefReferenced(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011111 }
11112
11113 void VisitMemberExpr(MemberExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011114 S.MarkMemberReferenced(E);
Douglas Gregor32b3de52010-09-11 23:32:50 +000011115 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011116 }
11117
John McCall28fc7092011-11-10 05:35:25 +000011118 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011119 S.MarkFunctionReferenced(E->getLocStart(),
John McCall28fc7092011-11-10 05:35:25 +000011120 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11121 Visit(E->getSubExpr());
11122 }
11123
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011124 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011125 if (E->getOperatorNew())
Eli Friedmanfa0df832012-02-02 03:46:19 +000011126 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011127 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000011128 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +000011129 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011130 }
Sebastian Redl6047f072012-02-16 12:22:20 +000011131
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011132 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11133 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000011134 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000011135 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11136 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11137 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedmanfa0df832012-02-02 03:46:19 +000011138 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000011139 S.LookupDestructor(Record));
11140 }
11141
Douglas Gregor32b3de52010-09-11 23:32:50 +000011142 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011143 }
11144
11145 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011146 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +000011147 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011148 }
11149
Douglas Gregorf0873f42010-10-19 17:17:35 +000011150 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11151 Visit(E->getExpr());
11152 }
Eli Friedman3bda6b12012-02-02 23:15:15 +000011153
11154 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11155 Inherited::VisitImplicitCastExpr(E);
11156
11157 if (E->getCastKind() == CK_LValueToRValue)
11158 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11159 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011160 };
11161}
11162
11163/// \brief Mark any declarations that appear within this expression or any
11164/// potentially-evaluated subexpressions as "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +000011165///
11166/// \param SkipLocalVariables If true, don't mark local variables as
11167/// 'referenced'.
11168void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11169 bool SkipLocalVariables) {
11170 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011171}
11172
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011173/// \brief Emit a diagnostic that describes an effect on the run-time behavior
11174/// of the program being compiled.
11175///
11176/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011177/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011178/// possibility that the code will actually be executable. Code in sizeof()
11179/// expressions, code used only during overload resolution, etc., are not
11180/// potentially evaluated. This routine will suppress such diagnostics or,
11181/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011182/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011183/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011184///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011185/// This routine should be used for all diagnostics that describe the run-time
11186/// behavior of a program, such as passing a non-POD value through an ellipsis.
11187/// Failure to do so will likely result in spurious diagnostics or failures
11188/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuba63ce62011-09-09 01:45:06 +000011189bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011190 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +000011191 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011192 case Unevaluated:
11193 // The argument will never be evaluated, so don't complain.
11194 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011195
Richard Smith764d2fe2011-12-20 02:08:33 +000011196 case ConstantEvaluated:
11197 // Relevant diagnostics should be produced by constant evaluation.
11198 break;
11199
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011200 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011201 case PotentiallyEvaluatedIfUsed:
Richard Trieuba63ce62011-09-09 01:45:06 +000011202 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +000011203 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuba63ce62011-09-09 01:45:06 +000011204 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek3427fac2011-02-23 01:52:04 +000011205 }
11206 else
11207 Diag(Loc, PD);
11208
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011209 return true;
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011210 }
11211
11212 return false;
11213}
11214
Anders Carlsson7f84ed92009-10-09 23:51:55 +000011215bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11216 CallExpr *CE, FunctionDecl *FD) {
11217 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11218 return false;
11219
Richard Smithfd555f62012-02-22 02:04:18 +000011220 // If we're inside a decltype's expression, don't check for a valid return
11221 // type or construct temporaries until we know whether this is the last call.
11222 if (ExprEvalContexts.back().IsDecltype) {
11223 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11224 return false;
11225 }
11226
Douglas Gregora6c5abb2012-05-04 16:48:41 +000011227 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011228 FunctionDecl *FD;
11229 CallExpr *CE;
11230
11231 public:
11232 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11233 : FD(FD), CE(CE) { }
11234
11235 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11236 if (!FD) {
11237 S.Diag(Loc, diag::err_call_incomplete_return)
11238 << T << CE->getSourceRange();
11239 return;
11240 }
11241
11242 S.Diag(Loc, diag::err_call_function_incomplete_return)
11243 << CE->getSourceRange() << FD->getDeclName() << T;
11244 S.Diag(FD->getLocation(),
11245 diag::note_function_with_incomplete_return_type_declared_here)
11246 << FD->getDeclName();
11247 }
11248 } Diagnoser(FD, CE);
11249
11250 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson7f84ed92009-10-09 23:51:55 +000011251 return true;
11252
11253 return false;
11254}
11255
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011256// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000011257// will prevent this condition from triggering, which is what we want.
11258void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11259 SourceLocation Loc;
11260
John McCall0506e4a2009-11-11 02:41:58 +000011261 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011262 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000011263
Chandler Carruthf87d6c02011-08-16 22:30:10 +000011264 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011265 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000011266 return;
11267
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011268 IsOrAssign = Op->getOpcode() == BO_OrAssign;
11269
John McCallb0e419e2009-11-12 00:06:05 +000011270 // Greylist some idioms by putting them into a warning subcategory.
11271 if (ObjCMessageExpr *ME
11272 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11273 Selector Sel = ME->getSelector();
11274
John McCallb0e419e2009-11-12 00:06:05 +000011275 // self = [<foo> init...]
Douglas Gregor486b74e2011-09-27 16:10:05 +000011276 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +000011277 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11278
11279 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000011280 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000011281 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11282 }
John McCall0506e4a2009-11-11 02:41:58 +000011283
John McCalld5707ab2009-10-12 21:59:07 +000011284 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +000011285 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011286 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000011287 return;
11288
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011289 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000011290 Loc = Op->getOperatorLoc();
Fariborz Jahanianf07bcc52012-08-29 17:17:11 +000011291 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
11292 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
11293 else {
John McCalld5707ab2009-10-12 21:59:07 +000011294 // Not an assignment.
11295 return;
11296 }
11297
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000011298 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011299
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011300 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000011301 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11302 Diag(Loc, diag::note_condition_assign_silence)
11303 << FixItHint::CreateInsertion(Open, "(")
11304 << FixItHint::CreateInsertion(Close, ")");
11305
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011306 if (IsOrAssign)
11307 Diag(Loc, diag::note_condition_or_assign_to_comparison)
11308 << FixItHint::CreateReplacement(Loc, "!=");
11309 else
11310 Diag(Loc, diag::note_condition_assign_to_comparison)
11311 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +000011312}
11313
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011314/// \brief Redundant parentheses over an equality comparison can indicate
11315/// that the user intended an assignment used as condition.
Richard Trieuba63ce62011-09-09 01:45:06 +000011316void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011317 // Don't warn if the parens came from a macro.
Richard Trieuba63ce62011-09-09 01:45:06 +000011318 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011319 if (parenLoc.isInvalid() || parenLoc.isMacroID())
11320 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000011321 // Don't warn for dependent expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +000011322 if (ParenE->isTypeDependent())
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000011323 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011324
Richard Trieuba63ce62011-09-09 01:45:06 +000011325 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011326
11327 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000011328 if (opE->getOpcode() == BO_EQ &&
11329 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11330 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011331 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000011332
Ted Kremenekae022092011-02-02 02:20:30 +000011333 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011334 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +000011335 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011336 << FixItHint::CreateRemoval(ParenERange.getBegin())
11337 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000011338 Diag(Loc, diag::note_equality_comparison_to_assign)
11339 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011340 }
11341}
11342
John Wiegley01296292011-04-08 18:41:53 +000011343ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +000011344 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011345 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11346 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000011347
John McCall0009fcc2011-04-26 20:42:42 +000011348 ExprResult result = CheckPlaceholderExpr(E);
11349 if (result.isInvalid()) return ExprError();
11350 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000011351
John McCall0009fcc2011-04-26 20:42:42 +000011352 if (!E->isTypeDependent()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000011353 if (getLangOpts().CPlusPlus)
John McCall34376a62010-12-04 03:47:34 +000011354 return CheckCXXBooleanCondition(E); // C++ 6.4p4
11355
John Wiegley01296292011-04-08 18:41:53 +000011356 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11357 if (ERes.isInvalid())
11358 return ExprError();
11359 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +000011360
11361 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000011362 if (!T->isScalarType()) { // C99 6.8.4.1p1
11363 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11364 << T << E->getSourceRange();
11365 return ExprError();
11366 }
John McCalld5707ab2009-10-12 21:59:07 +000011367 }
11368
John Wiegley01296292011-04-08 18:41:53 +000011369 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +000011370}
Douglas Gregore60e41a2010-05-06 17:25:47 +000011371
John McCalldadc5752010-08-24 06:29:42 +000011372ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +000011373 Expr *SubExpr) {
11374 if (!SubExpr)
Douglas Gregore60e41a2010-05-06 17:25:47 +000011375 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011376
Richard Trieuba63ce62011-09-09 01:45:06 +000011377 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +000011378}
John McCall36e7fe32010-10-12 00:20:44 +000011379
John McCall31996342011-04-07 08:22:57 +000011380namespace {
John McCall2979fe02011-04-12 00:42:48 +000011381 /// A visitor for rebuilding a call to an __unknown_any expression
11382 /// to have an appropriate type.
11383 struct RebuildUnknownAnyFunction
11384 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11385
11386 Sema &S;
11387
11388 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11389
11390 ExprResult VisitStmt(Stmt *S) {
11391 llvm_unreachable("unexpected statement!");
John McCall2979fe02011-04-12 00:42:48 +000011392 }
11393
Richard Trieu10162ab2011-09-09 03:59:41 +000011394 ExprResult VisitExpr(Expr *E) {
11395 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11396 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011397 return ExprError();
11398 }
11399
11400 /// Rebuild an expression which simply semantically wraps another
11401 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000011402 template <class T> ExprResult rebuildSugarExpr(T *E) {
11403 ExprResult SubResult = Visit(E->getSubExpr());
11404 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000011405
Richard Trieu10162ab2011-09-09 03:59:41 +000011406 Expr *SubExpr = SubResult.take();
11407 E->setSubExpr(SubExpr);
11408 E->setType(SubExpr->getType());
11409 E->setValueKind(SubExpr->getValueKind());
11410 assert(E->getObjectKind() == OK_Ordinary);
11411 return E;
John McCall2979fe02011-04-12 00:42:48 +000011412 }
11413
Richard Trieu10162ab2011-09-09 03:59:41 +000011414 ExprResult VisitParenExpr(ParenExpr *E) {
11415 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011416 }
11417
Richard Trieu10162ab2011-09-09 03:59:41 +000011418 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11419 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011420 }
11421
Richard Trieu10162ab2011-09-09 03:59:41 +000011422 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11423 ExprResult SubResult = Visit(E->getSubExpr());
11424 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000011425
Richard Trieu10162ab2011-09-09 03:59:41 +000011426 Expr *SubExpr = SubResult.take();
11427 E->setSubExpr(SubExpr);
11428 E->setType(S.Context.getPointerType(SubExpr->getType()));
11429 assert(E->getValueKind() == VK_RValue);
11430 assert(E->getObjectKind() == OK_Ordinary);
11431 return E;
John McCall2979fe02011-04-12 00:42:48 +000011432 }
11433
Richard Trieu10162ab2011-09-09 03:59:41 +000011434 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11435 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011436
Richard Trieu10162ab2011-09-09 03:59:41 +000011437 E->setType(VD->getType());
John McCall2979fe02011-04-12 00:42:48 +000011438
Richard Trieu10162ab2011-09-09 03:59:41 +000011439 assert(E->getValueKind() == VK_RValue);
David Blaikiebbafb8a2012-03-11 07:00:24 +000011440 if (S.getLangOpts().CPlusPlus &&
Richard Trieu10162ab2011-09-09 03:59:41 +000011441 !(isa<CXXMethodDecl>(VD) &&
11442 cast<CXXMethodDecl>(VD)->isInstance()))
11443 E->setValueKind(VK_LValue);
John McCall2979fe02011-04-12 00:42:48 +000011444
Richard Trieu10162ab2011-09-09 03:59:41 +000011445 return E;
John McCall2979fe02011-04-12 00:42:48 +000011446 }
11447
Richard Trieu10162ab2011-09-09 03:59:41 +000011448 ExprResult VisitMemberExpr(MemberExpr *E) {
11449 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000011450 }
11451
Richard Trieu10162ab2011-09-09 03:59:41 +000011452 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11453 return resolveDecl(E, E->getDecl());
John McCall2979fe02011-04-12 00:42:48 +000011454 }
11455 };
11456}
11457
11458/// Given a function expression of unknown-any type, try to rebuild it
11459/// to have a function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011460static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11461 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11462 if (Result.isInvalid()) return ExprError();
11463 return S.DefaultFunctionArrayConversion(Result.take());
John McCall2979fe02011-04-12 00:42:48 +000011464}
11465
11466namespace {
John McCall2d2e8702011-04-11 07:02:50 +000011467 /// A visitor for rebuilding an expression of type __unknown_anytype
11468 /// into one which resolves the type directly on the referring
11469 /// expression. Strict preservation of the original source
11470 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +000011471 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +000011472 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +000011473
11474 Sema &S;
11475
11476 /// The current destination type.
11477 QualType DestType;
11478
Richard Trieu10162ab2011-09-09 03:59:41 +000011479 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11480 : S(S), DestType(CastType) {}
John McCall31996342011-04-07 08:22:57 +000011481
John McCall39439732011-04-09 22:50:59 +000011482 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +000011483 llvm_unreachable("unexpected statement!");
John McCall31996342011-04-07 08:22:57 +000011484 }
11485
Richard Trieu10162ab2011-09-09 03:59:41 +000011486 ExprResult VisitExpr(Expr *E) {
11487 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11488 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011489 return ExprError();
John McCall31996342011-04-07 08:22:57 +000011490 }
11491
Richard Trieu10162ab2011-09-09 03:59:41 +000011492 ExprResult VisitCallExpr(CallExpr *E);
11493 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall2d2e8702011-04-11 07:02:50 +000011494
John McCall39439732011-04-09 22:50:59 +000011495 /// Rebuild an expression which simply semantically wraps another
11496 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000011497 template <class T> ExprResult rebuildSugarExpr(T *E) {
11498 ExprResult SubResult = Visit(E->getSubExpr());
11499 if (SubResult.isInvalid()) return ExprError();
11500 Expr *SubExpr = SubResult.take();
11501 E->setSubExpr(SubExpr);
11502 E->setType(SubExpr->getType());
11503 E->setValueKind(SubExpr->getValueKind());
11504 assert(E->getObjectKind() == OK_Ordinary);
11505 return E;
John McCall39439732011-04-09 22:50:59 +000011506 }
John McCall31996342011-04-07 08:22:57 +000011507
Richard Trieu10162ab2011-09-09 03:59:41 +000011508 ExprResult VisitParenExpr(ParenExpr *E) {
11509 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000011510 }
11511
Richard Trieu10162ab2011-09-09 03:59:41 +000011512 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11513 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000011514 }
11515
Richard Trieu10162ab2011-09-09 03:59:41 +000011516 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11517 const PointerType *Ptr = DestType->getAs<PointerType>();
11518 if (!Ptr) {
11519 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11520 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011521 return ExprError();
11522 }
Richard Trieu10162ab2011-09-09 03:59:41 +000011523 assert(E->getValueKind() == VK_RValue);
11524 assert(E->getObjectKind() == OK_Ordinary);
11525 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +000011526
11527 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011528 DestType = Ptr->getPointeeType();
11529 ExprResult SubResult = Visit(E->getSubExpr());
11530 if (SubResult.isInvalid()) return ExprError();
11531 E->setSubExpr(SubResult.take());
11532 return E;
John McCall2979fe02011-04-12 00:42:48 +000011533 }
11534
Richard Trieu10162ab2011-09-09 03:59:41 +000011535 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCall39439732011-04-09 22:50:59 +000011536
Richard Trieu10162ab2011-09-09 03:59:41 +000011537 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCall39439732011-04-09 22:50:59 +000011538
Richard Trieu10162ab2011-09-09 03:59:41 +000011539 ExprResult VisitMemberExpr(MemberExpr *E) {
11540 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000011541 }
John McCall39439732011-04-09 22:50:59 +000011542
Richard Trieu10162ab2011-09-09 03:59:41 +000011543 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11544 return resolveDecl(E, E->getDecl());
John McCall31996342011-04-07 08:22:57 +000011545 }
11546 };
11547}
11548
John McCall2d2e8702011-04-11 07:02:50 +000011549/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu10162ab2011-09-09 03:59:41 +000011550ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11551 Expr *CalleeExpr = E->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000011552
11553 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +000011554 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +000011555 FK_FunctionPointer,
11556 FK_BlockPointer
11557 };
11558
Richard Trieu10162ab2011-09-09 03:59:41 +000011559 FnKind Kind;
11560 QualType CalleeType = CalleeExpr->getType();
11561 if (CalleeType == S.Context.BoundMemberTy) {
11562 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11563 Kind = FK_MemberFunction;
11564 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11565 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11566 CalleeType = Ptr->getPointeeType();
11567 Kind = FK_FunctionPointer;
John McCall2d2e8702011-04-11 07:02:50 +000011568 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000011569 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11570 Kind = FK_BlockPointer;
John McCall2d2e8702011-04-11 07:02:50 +000011571 }
Richard Trieu10162ab2011-09-09 03:59:41 +000011572 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall2d2e8702011-04-11 07:02:50 +000011573
11574 // Verify that this is a legal result type of a function.
11575 if (DestType->isArrayType() || DestType->isFunctionType()) {
11576 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu10162ab2011-09-09 03:59:41 +000011577 if (Kind == FK_BlockPointer)
John McCall2d2e8702011-04-11 07:02:50 +000011578 diagID = diag::err_block_returning_array_function;
11579
Richard Trieu10162ab2011-09-09 03:59:41 +000011580 S.Diag(E->getExprLoc(), diagID)
John McCall2d2e8702011-04-11 07:02:50 +000011581 << DestType->isFunctionType() << DestType;
11582 return ExprError();
11583 }
11584
11585 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu10162ab2011-09-09 03:59:41 +000011586 E->setType(DestType.getNonLValueExprType(S.Context));
11587 E->setValueKind(Expr::getValueKindForType(DestType));
11588 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000011589
11590 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu10162ab2011-09-09 03:59:41 +000011591 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall2d2e8702011-04-11 07:02:50 +000011592 DestType = S.Context.getFunctionType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000011593 Proto->arg_type_begin(),
11594 Proto->getNumArgs(),
11595 Proto->getExtProtoInfo());
John McCall2d2e8702011-04-11 07:02:50 +000011596 else
11597 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000011598 FnType->getExtInfo());
John McCall2d2e8702011-04-11 07:02:50 +000011599
11600 // Rebuild the appropriate pointer-to-function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011601 switch (Kind) {
John McCall4adb38c2011-04-27 00:36:17 +000011602 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +000011603 // Nothing to do.
11604 break;
11605
11606 case FK_FunctionPointer:
11607 DestType = S.Context.getPointerType(DestType);
11608 break;
11609
11610 case FK_BlockPointer:
11611 DestType = S.Context.getBlockPointerType(DestType);
11612 break;
11613 }
11614
11615 // Finally, we can recurse.
Richard Trieu10162ab2011-09-09 03:59:41 +000011616 ExprResult CalleeResult = Visit(CalleeExpr);
11617 if (!CalleeResult.isUsable()) return ExprError();
11618 E->setCallee(CalleeResult.take());
John McCall2d2e8702011-04-11 07:02:50 +000011619
11620 // Bind a temporary if necessary.
Richard Trieu10162ab2011-09-09 03:59:41 +000011621 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000011622}
11623
Richard Trieu10162ab2011-09-09 03:59:41 +000011624ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000011625 // Verify that this is a legal result type of a call.
11626 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu10162ab2011-09-09 03:59:41 +000011627 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall2979fe02011-04-12 00:42:48 +000011628 << DestType->isFunctionType() << DestType;
11629 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011630 }
11631
John McCall3f4138c2011-07-13 17:56:40 +000011632 // Rewrite the method result type if available.
Richard Trieu10162ab2011-09-09 03:59:41 +000011633 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11634 assert(Method->getResultType() == S.Context.UnknownAnyTy);
11635 Method->setResultType(DestType);
John McCall3f4138c2011-07-13 17:56:40 +000011636 }
John McCall2979fe02011-04-12 00:42:48 +000011637
John McCall2d2e8702011-04-11 07:02:50 +000011638 // Change the type of the message.
Richard Trieu10162ab2011-09-09 03:59:41 +000011639 E->setType(DestType.getNonReferenceType());
11640 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000011641
Richard Trieu10162ab2011-09-09 03:59:41 +000011642 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000011643}
11644
Richard Trieu10162ab2011-09-09 03:59:41 +000011645ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000011646 // The only case we should ever see here is a function-to-pointer decay.
Sean Callanan2db103c2012-03-06 23:12:57 +000011647 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanan12495112012-03-06 21:34:12 +000011648 assert(E->getValueKind() == VK_RValue);
11649 assert(E->getObjectKind() == OK_Ordinary);
11650
11651 E->setType(DestType);
11652
11653 // Rebuild the sub-expression as the pointee (function) type.
11654 DestType = DestType->castAs<PointerType>()->getPointeeType();
11655
11656 ExprResult Result = Visit(E->getSubExpr());
11657 if (!Result.isUsable()) return ExprError();
11658
11659 E->setSubExpr(Result.take());
11660 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000011661 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanan12495112012-03-06 21:34:12 +000011662 assert(E->getValueKind() == VK_RValue);
11663 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000011664
Sean Callanan12495112012-03-06 21:34:12 +000011665 assert(isa<BlockPointerType>(E->getType()));
John McCall2979fe02011-04-12 00:42:48 +000011666
Sean Callanan12495112012-03-06 21:34:12 +000011667 E->setType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000011668
Sean Callanan12495112012-03-06 21:34:12 +000011669 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11670 DestType = S.Context.getLValueReferenceType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000011671
Sean Callanan12495112012-03-06 21:34:12 +000011672 ExprResult Result = Visit(E->getSubExpr());
11673 if (!Result.isUsable()) return ExprError();
11674
11675 E->setSubExpr(Result.take());
11676 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000011677 } else {
Sean Callanan12495112012-03-06 21:34:12 +000011678 llvm_unreachable("Unhandled cast type!");
11679 }
John McCall2d2e8702011-04-11 07:02:50 +000011680}
11681
Richard Trieu10162ab2011-09-09 03:59:41 +000011682ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11683 ExprValueKind ValueKind = VK_LValue;
11684 QualType Type = DestType;
John McCall2d2e8702011-04-11 07:02:50 +000011685
11686 // We know how to make this work for certain kinds of decls:
11687
11688 // - functions
Richard Trieu10162ab2011-09-09 03:59:41 +000011689 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11690 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11691 DestType = Ptr->getPointeeType();
11692 ExprResult Result = resolveDecl(E, VD);
11693 if (Result.isInvalid()) return ExprError();
11694 return S.ImpCastExprToType(Result.take(), Type,
John McCall9a877fe2011-08-10 04:12:23 +000011695 CK_FunctionToPointerDecay, VK_RValue);
11696 }
11697
Richard Trieu10162ab2011-09-09 03:59:41 +000011698 if (!Type->isFunctionType()) {
11699 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11700 << VD << E->getSourceRange();
John McCall9a877fe2011-08-10 04:12:23 +000011701 return ExprError();
11702 }
John McCall2d2e8702011-04-11 07:02:50 +000011703
Richard Trieu10162ab2011-09-09 03:59:41 +000011704 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11705 if (MD->isInstance()) {
11706 ValueKind = VK_RValue;
11707 Type = S.Context.BoundMemberTy;
John McCall4adb38c2011-04-27 00:36:17 +000011708 }
11709
John McCall2d2e8702011-04-11 07:02:50 +000011710 // Function references aren't l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011711 if (!S.getLangOpts().CPlusPlus)
Richard Trieu10162ab2011-09-09 03:59:41 +000011712 ValueKind = VK_RValue;
John McCall2d2e8702011-04-11 07:02:50 +000011713
11714 // - variables
Richard Trieu10162ab2011-09-09 03:59:41 +000011715 } else if (isa<VarDecl>(VD)) {
11716 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11717 Type = RefTy->getPointeeType();
11718 } else if (Type->isFunctionType()) {
11719 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11720 << VD << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011721 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011722 }
11723
11724 // - nothing else
11725 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000011726 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11727 << VD << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011728 return ExprError();
11729 }
11730
Richard Trieu10162ab2011-09-09 03:59:41 +000011731 VD->setType(DestType);
11732 E->setType(Type);
11733 E->setValueKind(ValueKind);
11734 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +000011735}
11736
John McCall31996342011-04-07 08:22:57 +000011737/// Check a cast of an unknown-any type. We intentionally only
11738/// trigger this for C-style casts.
Richard Trieuba63ce62011-09-09 01:45:06 +000011739ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11740 Expr *CastExpr, CastKind &CastKind,
11741 ExprValueKind &VK, CXXCastPath &Path) {
John McCall31996342011-04-07 08:22:57 +000011742 // Rewrite the casted expression from scratch.
Richard Trieuba63ce62011-09-09 01:45:06 +000011743 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCall39439732011-04-09 22:50:59 +000011744 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000011745
Richard Trieuba63ce62011-09-09 01:45:06 +000011746 CastExpr = result.take();
11747 VK = CastExpr->getValueKind();
11748 CastKind = CK_NoOp;
John McCall39439732011-04-09 22:50:59 +000011749
Richard Trieuba63ce62011-09-09 01:45:06 +000011750 return CastExpr;
John McCall31996342011-04-07 08:22:57 +000011751}
11752
Douglas Gregord8fb1e32011-12-01 01:37:36 +000011753ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11754 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11755}
11756
Richard Trieuba63ce62011-09-09 01:45:06 +000011757static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11758 Expr *orig = E;
John McCall2d2e8702011-04-11 07:02:50 +000011759 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000011760 while (true) {
Richard Trieuba63ce62011-09-09 01:45:06 +000011761 E = E->IgnoreParenImpCasts();
11762 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11763 E = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000011764 diagID = diag::err_uncasted_call_of_unknown_any;
11765 } else {
John McCall31996342011-04-07 08:22:57 +000011766 break;
John McCall2d2e8702011-04-11 07:02:50 +000011767 }
John McCall31996342011-04-07 08:22:57 +000011768 }
11769
John McCall2d2e8702011-04-11 07:02:50 +000011770 SourceLocation loc;
11771 NamedDecl *d;
Richard Trieuba63ce62011-09-09 01:45:06 +000011772 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011773 loc = ref->getLocation();
11774 d = ref->getDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011775 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011776 loc = mem->getMemberLoc();
11777 d = mem->getMemberDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011778 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011779 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidisa6011e22011-10-03 06:36:51 +000011780 loc = msg->getSelectorStartLoc();
John McCall2d2e8702011-04-11 07:02:50 +000011781 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000011782 if (!d) {
11783 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11784 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11785 << orig->getSourceRange();
11786 return ExprError();
11787 }
John McCall2d2e8702011-04-11 07:02:50 +000011788 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +000011789 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11790 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011791 return ExprError();
11792 }
11793
11794 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000011795
11796 // Never recoverable.
11797 return ExprError();
11798}
11799
John McCall36e7fe32010-10-12 00:20:44 +000011800/// Check for operands with placeholder types and complain if found.
11801/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000011802ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall4124c492011-10-17 18:40:02 +000011803 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11804 if (!placeholderType) return Owned(E);
11805
11806 switch (placeholderType->getKind()) {
John McCall36e7fe32010-10-12 00:20:44 +000011807
John McCall31996342011-04-07 08:22:57 +000011808 // Overloaded expressions.
John McCall4124c492011-10-17 18:40:02 +000011809 case BuiltinType::Overload: {
John McCall50a2c2c2011-10-11 23:14:30 +000011810 // Try to resolve a single function template specialization.
11811 // This is obligatory.
11812 ExprResult result = Owned(E);
11813 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11814 return result;
11815
11816 // If that failed, try to recover with a call.
11817 } else {
11818 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11819 /*complain*/ true);
11820 return result;
11821 }
11822 }
John McCall31996342011-04-07 08:22:57 +000011823
John McCall0009fcc2011-04-26 20:42:42 +000011824 // Bound member functions.
John McCall4124c492011-10-17 18:40:02 +000011825 case BuiltinType::BoundMember: {
John McCall50a2c2c2011-10-11 23:14:30 +000011826 ExprResult result = Owned(E);
11827 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11828 /*complain*/ true);
11829 return result;
John McCall4124c492011-10-17 18:40:02 +000011830 }
11831
11832 // ARC unbridged casts.
11833 case BuiltinType::ARCUnbridgedCast: {
11834 Expr *realCast = stripARCUnbridgedCast(E);
11835 diagnoseARCUnbridgedCast(realCast);
11836 return Owned(realCast);
11837 }
John McCall0009fcc2011-04-26 20:42:42 +000011838
John McCall31996342011-04-07 08:22:57 +000011839 // Expressions of unknown type.
John McCall4124c492011-10-17 18:40:02 +000011840 case BuiltinType::UnknownAny:
John McCall31996342011-04-07 08:22:57 +000011841 return diagnoseUnknownAnyExpr(*this, E);
11842
John McCall526ab472011-10-25 17:37:35 +000011843 // Pseudo-objects.
11844 case BuiltinType::PseudoObject:
11845 return checkPseudoObjectRValue(E);
11846
Eli Friedman34866c72012-08-31 00:14:07 +000011847 case BuiltinType::BuiltinFn:
11848 Diag(E->getLocStart(), diag::err_builtin_fn_use);
11849 return ExprError();
11850
John McCalle314e272011-10-18 21:02:43 +000011851 // Everything else should be impossible.
11852#define BUILTIN_TYPE(Id, SingletonId) \
11853 case BuiltinType::Id:
11854#define PLACEHOLDER_TYPE(Id, SingletonId)
11855#include "clang/AST/BuiltinTypes.def"
John McCall4124c492011-10-17 18:40:02 +000011856 break;
11857 }
11858
11859 llvm_unreachable("invalid placeholder type!");
John McCall36e7fe32010-10-12 00:20:44 +000011860}
Richard Trieu2c850c02011-04-21 21:44:26 +000011861
Richard Trieuba63ce62011-09-09 01:45:06 +000011862bool Sema::CheckCaseExpression(Expr *E) {
11863 if (E->isTypeDependent())
Richard Trieu2c850c02011-04-21 21:44:26 +000011864 return true;
Richard Trieuba63ce62011-09-09 01:45:06 +000011865 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11866 return E->getType()->isIntegralOrEnumerationType();
Richard Trieu2c850c02011-04-21 21:44:26 +000011867 return false;
11868}
Ted Kremeneke65b0862012-03-06 20:05:56 +000011869
11870/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11871ExprResult
11872Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11873 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11874 "Unknown Objective-C Boolean value!");
Fariborz Jahanianf2578572012-08-30 18:49:41 +000011875 QualType BoolT = Context.ObjCBuiltinBoolTy;
11876 if (!Context.getBOOLDecl()) {
11877 LookupResult Result(*this, &Context.Idents.get("BOOL"), SourceLocation(),
11878 Sema::LookupOrdinaryName);
11879 if (LookupName(Result, getCurScope())) {
11880 NamedDecl *ND = Result.getFoundDecl();
11881 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
11882 Context.setBOOLDecl(TD);
11883 }
11884 }
11885 if (Context.getBOOLDecl())
11886 BoolT = Context.getBOOLType();
Ted Kremeneke65b0862012-03-06 20:05:56 +000011887 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanianf2578572012-08-30 18:49:41 +000011888 BoolT, OpLoc));
Ted Kremeneke65b0862012-03-06 20:05:56 +000011889}