blob: b8cb50c9aee25e09aa5d5c9188b73f592d5dd5b3 [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "TreeTransform.h"
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000016#include "clang/AST/ASTConsumer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/AST/ASTContext.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000018#include "clang/AST/ASTLambda.h"
Sebastian Redl2ac2c722011-04-29 08:19:30 +000019#include "clang/AST/ASTMutationListener.h"
Douglas Gregord1702062010-04-29 00:18:15 +000020#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000022#include "clang/AST/DeclTemplate.h"
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000023#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000024#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000025#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000026#include "clang/AST/ExprObjC.h"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000027#include "clang/AST/ExprOpenMP.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000028#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000029#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000030#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000031#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000032#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000033#include "clang/Lex/LiteralSupport.h"
34#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000035#include "clang/Sema/AnalysisBasedWarnings.h"
John McCall8b0666c2010-08-20 18:27:03 +000036#include "clang/Sema/DeclSpec.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "clang/Sema/DelayedDiagnostic.h"
John McCall8b0666c2010-08-20 18:27:03 +000038#include "clang/Sema/Designator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "clang/Sema/Initialization.h"
40#include "clang/Sema/Lookup.h"
41#include "clang/Sema/ParsedTemplate.h"
John McCall8b0666c2010-08-20 18:27:03 +000042#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000043#include "clang/Sema/ScopeInfo.h"
Anna Zaks3b402712011-07-28 19:51:27 +000044#include "clang/Sema/SemaFixItUtils.h"
John McCallde6836a2010-08-24 07:21:54 +000045#include "clang/Sema/Template.h"
Alexey Bataevec474782014-10-09 08:45:04 +000046#include "llvm/Support/ConvertUTF.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000047using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000048using namespace sema;
Chris Lattner5b183d82006-11-10 05:03:26 +000049
Sebastian Redlb49c46c2011-09-24 17:48:00 +000050/// \brief Determine whether the use of this declaration is valid, without
51/// emitting diagnostics.
52bool Sema::CanUseDecl(NamedDecl *D) {
53 // See if this is an auto-typed variable whose initializer we are parsing.
54 if (ParsingInitForAutoVars.count(D))
55 return false;
56
57 // See if this is a deleted function.
58 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
59 if (FD->isDeleted())
60 return false;
Richard Smith2a7d4812013-05-04 07:00:32 +000061
62 // If the function has a deduced return type, and we can't deduce it,
63 // then we can't use it either.
Aaron Ballmandd69ef32014-08-19 15:55:55 +000064 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +000065 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +000066 return false;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000067 }
Sebastian Redl5999aec2011-10-16 18:19:16 +000068
69 // See if this function is unavailable.
70 if (D->getAvailability() == AR_Unavailable &&
71 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
72 return false;
73
Sebastian Redlb49c46c2011-09-24 17:48:00 +000074 return true;
75}
David Chisnall9f57c292009-08-17 16:35:33 +000076
Fariborz Jahanian66c93f42012-09-06 16:43:18 +000077static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
78 // Warn if this is used but marked unused.
79 if (D->hasAttr<UnusedAttr>()) {
Ben Langmuirc91ac9e2015-01-20 20:41:36 +000080 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
81 if (DC && !DC->hasAttr<UnusedAttr>())
Fariborz Jahanian66c93f42012-09-06 16:43:18 +000082 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
83 }
84}
85
Nico Weber0055a192015-03-19 19:18:22 +000086static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
87 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
88 if (!OMD)
89 return false;
90 const ObjCInterfaceDecl *OID = OMD->getClassInterface();
91 if (!OID)
92 return false;
93
94 for (const ObjCCategoryDecl *Cat : OID->visible_categories())
95 if (ObjCMethodDecl *CatMeth =
96 Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
97 if (!CatMeth->hasAttr<AvailabilityAttr>())
98 return true;
99 return false;
100}
101
102static AvailabilityResult
103DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
104 const ObjCInterfaceDecl *UnknownObjCClass,
105 bool ObjCPropertyAccess) {
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000106 // See if this declaration is unavailable or deprecated.
107 std::string Message;
Ted Kremenekc004b4d2015-05-14 22:07:25 +0000108 AvailabilityResult Result = D->getAvailability(&Message);
109
110 // For typedefs, if the typedef declaration appears available look
111 // to the underlying type to see if it is more restrictive.
David Blaikief0f00dc2015-05-14 22:47:19 +0000112 while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Ted Kremenekc004b4d2015-05-14 22:07:25 +0000113 if (Result == AR_Available) {
114 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
115 D = TT->getDecl();
116 Result = D->getAvailability(&Message);
117 continue;
118 }
119 }
120 break;
121 }
Fariborz Jahanian285b6b62014-06-18 17:58:27 +0000122
123 // Forward class declarations get their attributes from their definition.
124 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
Ted Kremenekc004b4d2015-05-14 22:07:25 +0000125 if (IDecl->getDefinition()) {
Fariborz Jahanian285b6b62014-06-18 17:58:27 +0000126 D = IDecl->getDefinition();
Ted Kremenekc004b4d2015-05-14 22:07:25 +0000127 Result = D->getAvailability(&Message);
128 }
Fariborz Jahanian285b6b62014-06-18 17:58:27 +0000129 }
Ted Kremenekc004b4d2015-05-14 22:07:25 +0000130
Fariborz Jahanian25d09c22011-11-28 19:45:58 +0000131 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
132 if (Result == AR_Available) {
133 const DeclContext *DC = ECD->getDeclContext();
134 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
135 Result = TheEnumDecl->getAvailability(&Message);
136 }
Jordan Rose2bd991a2012-10-10 16:42:54 +0000137
Craig Topperc3ec1492014-05-26 06:22:03 +0000138 const ObjCPropertyDecl *ObjCPDecl = nullptr;
Nico Weber0055a192015-03-19 19:18:22 +0000139 if (Result == AR_Deprecated || Result == AR_Unavailable ||
140 AR_NotYetIntroduced) {
Jordan Rose2bd991a2012-10-10 16:42:54 +0000141 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
142 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000143 AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
Jordan Rose2bd991a2012-10-10 16:42:54 +0000144 if (PDeclResult == Result)
145 ObjCPDecl = PD;
146 }
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000147 }
Jordan Rose2bd991a2012-10-10 16:42:54 +0000148 }
Fariborz Jahanian25d09c22011-11-28 19:45:58 +0000149
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000150 switch (Result) {
151 case AR_Available:
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000152 break;
Nico Weber55905142015-03-06 06:01:06 +0000153
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000154 case AR_Deprecated:
Ted Kremenekcb42dbe2013-11-20 17:24:03 +0000155 if (S.getCurContextAvailability() != AR_Deprecated)
Ted Kremenekb79ee572013-12-18 23:30:06 +0000156 S.EmitAvailabilityWarning(Sema::AD_Deprecation,
Fariborz Jahanian89ea9612014-06-16 17:25:41 +0000157 D, Message, Loc, UnknownObjCClass, ObjCPDecl,
158 ObjCPropertyAccess);
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000159 break;
Ted Kremenekb79ee572013-12-18 23:30:06 +0000160
Nico Weber0055a192015-03-19 19:18:22 +0000161 case AR_NotYetIntroduced: {
162 // Don't do this for enums, they can't be redeclared.
163 if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
164 break;
165
166 bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
167 // Objective-C method declarations in categories are not modelled as
168 // redeclarations, so manually look for a redeclaration in a category
169 // if necessary.
170 if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
171 Warn = false;
172 // In general, D will point to the most recent redeclaration. However,
173 // for `@class A;` decls, this isn't true -- manually go through the
174 // redecl chain in that case.
175 if (Warn && isa<ObjCInterfaceDecl>(D))
176 for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
177 Redecl = Redecl->getPreviousDecl())
178 if (!Redecl->hasAttr<AvailabilityAttr>() ||
179 Redecl->getAttr<AvailabilityAttr>()->isInherited())
180 Warn = false;
181
182 if (Warn)
183 S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc,
184 UnknownObjCClass, ObjCPDecl,
185 ObjCPropertyAccess);
186 break;
187 }
188
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000189 case AR_Unavailable:
Ted Kremenekb79ee572013-12-18 23:30:06 +0000190 if (S.getCurContextAvailability() != AR_Unavailable)
191 S.EmitAvailabilityWarning(Sema::AD_Unavailable,
Fariborz Jahanian89ea9612014-06-16 17:25:41 +0000192 D, Message, Loc, UnknownObjCClass, ObjCPDecl,
193 ObjCPropertyAccess);
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000194 break;
Ted Kremenekb79ee572013-12-18 23:30:06 +0000195
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000196 }
197 return Result;
198}
199
Eli Friedmanebea0f22013-07-18 23:29:14 +0000200/// \brief Emit a note explaining that this function is deleted.
Richard Smith852265f2012-03-30 20:53:28 +0000201void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
Eli Friedmanebea0f22013-07-18 23:29:14 +0000202 assert(Decl->isDeleted());
203
Richard Smith852265f2012-03-30 20:53:28 +0000204 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
205
Eli Friedmanebea0f22013-07-18 23:29:14 +0000206 if (Method && Method->isDeleted() && Method->isDefaulted()) {
Richard Smith6f1e2c62012-04-02 20:59:25 +0000207 // If the method was explicitly defaulted, point at that declaration.
208 if (!Method->isImplicit())
209 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
210
211 // Try to diagnose why this special member function was implicitly
212 // deleted. This might fail, if that reason no longer applies.
Richard Smith852265f2012-03-30 20:53:28 +0000213 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +0000214 if (CSM != CXXInvalid)
215 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
216
217 return;
Richard Smith852265f2012-03-30 20:53:28 +0000218 }
219
Eli Friedmanebea0f22013-07-18 23:29:14 +0000220 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
221 if (CXXConstructorDecl *BaseCD =
222 const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
223 Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
224 if (BaseCD->isDeleted()) {
225 NoteDeletedFunction(BaseCD);
226 } else {
227 // FIXME: An explanation of why exactly it can't be inherited
228 // would be nice.
229 Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
230 }
231 return;
232 }
233 }
234
Ted Kremenekb79ee572013-12-18 23:30:06 +0000235 Diag(Decl->getLocation(), diag::note_availability_specified_here)
236 << Decl << true;
Richard Smith852265f2012-03-30 20:53:28 +0000237}
238
Jordan Rose28cd12f2012-06-18 22:09:19 +0000239/// \brief Determine whether a FunctionDecl was ever declared with an
240/// explicit storage class.
241static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
Aaron Ballman86c93902014-03-06 23:45:36 +0000242 for (auto I : D->redecls()) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000243 if (I->getStorageClass() != SC_None)
Jordan Rose28cd12f2012-06-18 22:09:19 +0000244 return true;
245 }
246 return false;
247}
248
249/// \brief Check whether we're in an extern inline function and referring to a
Jordan Rosede9e9762012-06-20 18:50:06 +0000250/// variable or function with internal linkage (C11 6.7.4p3).
Jordan Rose28cd12f2012-06-18 22:09:19 +0000251///
Jordan Rose28cd12f2012-06-18 22:09:19 +0000252/// This is only a warning because we used to silently accept this code, but
Jordan Rosede9e9762012-06-20 18:50:06 +0000253/// in many cases it will not behave correctly. This is not enabled in C++ mode
254/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
255/// and so while there may still be user mistakes, most of the time we can't
256/// prove that there are errors.
Jordan Rose28cd12f2012-06-18 22:09:19 +0000257static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
258 const NamedDecl *D,
259 SourceLocation Loc) {
Jordan Rosede9e9762012-06-20 18:50:06 +0000260 // This is disabled under C++; there are too many ways for this to fire in
261 // contexts where the warning is a false positive, or where it is technically
262 // correct but benign.
263 if (S.getLangOpts().CPlusPlus)
264 return;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000265
266 // Check if this is an inlined function or method.
267 FunctionDecl *Current = S.getCurFunctionDecl();
268 if (!Current)
269 return;
270 if (!Current->isInlined())
271 return;
Rafael Espindola3ae00052013-05-13 00:12:11 +0000272 if (!Current->isExternallyVisible())
Jordan Rose28cd12f2012-06-18 22:09:19 +0000273 return;
Rafael Espindola3ae00052013-05-13 00:12:11 +0000274
Jordan Rose28cd12f2012-06-18 22:09:19 +0000275 // Check if the decl has internal linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +0000276 if (D->getFormalLinkage() != InternalLinkage)
Jordan Rose28cd12f2012-06-18 22:09:19 +0000277 return;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000278
Jordan Rose815fe262012-06-21 05:54:50 +0000279 // Downgrade from ExtWarn to Extension if
280 // (1) the supposedly external inline function is in the main file,
281 // and probably won't be included anywhere else.
282 // (2) the thing we're referencing is a pure function.
283 // (3) the thing we're referencing is another inline function.
284 // This last can give us false negatives, but it's better than warning on
285 // wrappers for simple C library functions.
286 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
Eli Friedman5ba37d52013-08-22 00:27:10 +0000287 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
Jordan Rose815fe262012-06-21 05:54:50 +0000288 if (!DowngradeWarning && UsedFn)
289 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
290
Richard Smith1b98ccc2014-07-19 01:39:17 +0000291 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
292 : diag::ext_internal_in_extern_inline)
Jordan Rose815fe262012-06-21 05:54:50 +0000293 << /*IsVar=*/!UsedFn << D;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000294
John McCallc87d9722013-04-02 02:48:58 +0000295 S.MaybeSuggestAddingStaticToDecl(Current);
Jordan Rose28cd12f2012-06-18 22:09:19 +0000296
Alp Toker2afa8782014-05-28 12:20:14 +0000297 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
298 << D;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000299}
300
John McCallc87d9722013-04-02 02:48:58 +0000301void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
Rafael Espindola8db352d2013-10-17 15:37:26 +0000302 const FunctionDecl *First = Cur->getFirstDecl();
John McCallc87d9722013-04-02 02:48:58 +0000303
304 // Suggest "static" on the function, if possible.
305 if (!hasAnyExplicitStorageClass(First)) {
306 SourceLocation DeclBegin = First->getSourceRange().getBegin();
307 Diag(DeclBegin, diag::note_convert_inline_to_static)
308 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
309 }
310}
311
Douglas Gregor171c45a2009-02-18 21:56:37 +0000312/// \brief Determine whether the use of this declaration is valid, and
313/// emit any corresponding diagnostics.
314///
315/// This routine diagnoses various problems with referencing
316/// declarations that can occur when using a declaration. For example,
317/// it might warn if a deprecated or unavailable declaration is being
318/// used, or produce an error (and return true) if a C++0x deleted
319/// function is being used.
320///
321/// \returns true if there was an error (this declaration cannot be
322/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +0000323///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +0000324bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian89ea9612014-06-16 17:25:41 +0000325 const ObjCInterfaceDecl *UnknownObjCClass,
326 bool ObjCPropertyAccess) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000327 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000328 // If there were any diagnostics suppressed by template argument deduction,
329 // emit them now.
Craig Topper79be4cd2013-07-05 04:33:53 +0000330 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000331 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
332 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000333 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000334 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
335 Diag(Suppressed[I].first, Suppressed[I].second);
Richard Smithb63b6ee2014-01-22 01:43:19 +0000336
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000337 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000338 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000339 // entry from the table, because we want to avoid ever emitting these
340 // diagnostics again.
341 Suppressed.clear();
342 }
Richard Smithb63b6ee2014-01-22 01:43:19 +0000343
344 // C++ [basic.start.main]p3:
345 // The function 'main' shall not be used within a program.
346 if (cast<FunctionDecl>(D)->isMain())
347 Diag(Loc, diag::ext_main_used);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000348 }
349
Richard Smith30482bc2011-02-20 03:19:35 +0000350 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +0000351 if (ParsingInitForAutoVars.count(D)) {
Richard Smithe301ba22015-11-11 02:02:15 +0000352 const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType();
353
Richard Smithb2bc2e62011-02-21 20:05:19 +0000354 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
Richard Smithe301ba22015-11-11 02:02:15 +0000355 << D->getDeclName() << (unsigned)AT->getKeyword();
Richard Smithb2bc2e62011-02-21 20:05:19 +0000356 return true;
Richard Smith30482bc2011-02-20 03:19:35 +0000357 }
358
Douglas Gregor171c45a2009-02-18 21:56:37 +0000359 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +0000360 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +0000361 if (FD->isDeleted()) {
362 Diag(Loc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +0000363 NoteDeletedFunction(FD);
Douglas Gregor171c45a2009-02-18 21:56:37 +0000364 return true;
365 }
Richard Smith2a7d4812013-05-04 07:00:32 +0000366
367 // If the function has a deduced return type, and we can't deduce it,
368 // then we can't use it either.
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000369 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +0000370 DeduceReturnType(FD, Loc))
371 return true;
Douglas Gregorde681d42009-02-24 04:26:15 +0000372 }
Nico Weber0055a192015-03-19 19:18:22 +0000373 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
374 ObjCPropertyAccess);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000375
Fariborz Jahanian66c93f42012-09-06 16:43:18 +0000376 DiagnoseUnusedOfDecl(*this, D, Loc);
Jordan Rose2684c682012-06-15 18:19:48 +0000377
Jordan Rose28cd12f2012-06-18 22:09:19 +0000378 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
Jordan Rose2684c682012-06-15 18:19:48 +0000379
Douglas Gregor171c45a2009-02-18 21:56:37 +0000380 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000381}
382
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000383/// \brief Retrieve the message suffix that should be added to a
384/// diagnostic complaining about the given function being deleted or
385/// unavailable.
386std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000387 std::string Message;
388 if (FD->getAvailability(&Message))
389 return ": " + Message;
390
391 return std::string();
392}
393
John McCallb46f2872011-09-09 07:56:05 +0000394/// DiagnoseSentinelCalls - This routine checks whether a call or
395/// message-send is to a declaration with the sentinel attribute, and
396/// if so, it checks that the requirements of the sentinel are
397/// satisfied.
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000398void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000399 ArrayRef<Expr *> Args) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000400 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000401 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000402 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000403
John McCallb46f2872011-09-09 07:56:05 +0000404 // The number of formal parameters of the declaration.
405 unsigned numFormalParams;
Mike Stump11289f42009-09-09 15:08:12 +0000406
John McCallb46f2872011-09-09 07:56:05 +0000407 // The kind of declaration. This is also an index into a %select in
408 // the diagnostic.
409 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
410
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000411 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000412 numFormalParams = MD->param_size();
413 calleeType = CT_Method;
Mike Stump12b8ce12009-08-04 21:02:39 +0000414 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000415 numFormalParams = FD->param_size();
416 calleeType = CT_Function;
417 } else if (isa<VarDecl>(D)) {
418 QualType type = cast<ValueDecl>(D)->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +0000419 const FunctionType *fn = nullptr;
John McCallb46f2872011-09-09 07:56:05 +0000420 if (const PointerType *ptr = type->getAs<PointerType>()) {
421 fn = ptr->getPointeeType()->getAs<FunctionType>();
422 if (!fn) return;
423 calleeType = CT_Function;
424 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
425 fn = ptr->getPointeeType()->castAs<FunctionType>();
426 calleeType = CT_Block;
427 } else {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000428 return;
John McCallb46f2872011-09-09 07:56:05 +0000429 }
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000430
John McCallb46f2872011-09-09 07:56:05 +0000431 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000432 numFormalParams = proto->getNumParams();
John McCallb46f2872011-09-09 07:56:05 +0000433 } else {
434 numFormalParams = 0;
435 }
436 } else {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000437 return;
438 }
John McCallb46f2872011-09-09 07:56:05 +0000439
440 // "nullPos" is the number of formal parameters at the end which
441 // effectively count as part of the variadic arguments. This is
442 // useful if you would prefer to not have *any* formal parameters,
443 // but the language forces you to have at least one.
444 unsigned nullPos = attr->getNullPos();
445 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
446 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
447
448 // The number of arguments which should follow the sentinel.
449 unsigned numArgsAfterSentinel = attr->getSentinel();
450
451 // If there aren't enough arguments for all the formal parameters,
452 // the sentinel, and the args after the sentinel, complain.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000453 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000454 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000455 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000456 return;
457 }
John McCallb46f2872011-09-09 07:56:05 +0000458
459 // Otherwise, find the sentinel expression.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000460 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
John McCall7ddbcf42010-05-06 23:53:00 +0000461 if (!sentinelExpr) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000462 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +0000463 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000464
Reid Kleckner92493e52014-11-13 23:19:36 +0000465 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
466 // or 'NULL' if those are actually defined in the context. Only use
John McCallb46f2872011-09-09 07:56:05 +0000467 // 'nil' for ObjC methods, where it's much more likely that the
468 // variadic arguments form a list of object pointers.
469 SourceLocation MissingNilLoc
Craig Topper07fa1762015-11-15 02:31:46 +0000470 = getLocForEndOfToken(sentinelExpr->getLocEnd());
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000471 std::string NullValue;
Richard Smith20e883e2015-04-29 23:20:19 +0000472 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000473 NullValue = "nil";
Reid Kleckner92493e52014-11-13 23:19:36 +0000474 else if (getLangOpts().CPlusPlus11)
475 NullValue = "nullptr";
Richard Smith20e883e2015-04-29 23:20:19 +0000476 else if (PP.isMacroDefined("NULL"))
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000477 NullValue = "NULL";
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000478 else
John McCallb46f2872011-09-09 07:56:05 +0000479 NullValue = "(void*) 0";
Eli Friedman9ab36372011-09-27 23:46:37 +0000480
481 if (MissingNilLoc.isInvalid())
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000482 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
Eli Friedman9ab36372011-09-27 23:46:37 +0000483 else
484 Diag(MissingNilLoc, diag::warn_missing_sentinel)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000485 << int(calleeType)
Eli Friedman9ab36372011-09-27 23:46:37 +0000486 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000487 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000488}
489
Richard Trieuba63ce62011-09-09 01:45:06 +0000490SourceRange Sema::getExprRange(Expr *E) const {
491 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor87f95b02009-02-26 21:00:50 +0000492}
493
Chris Lattner513165e2008-07-25 21:10:04 +0000494//===----------------------------------------------------------------------===//
495// Standard Promotions and Conversions
496//===----------------------------------------------------------------------===//
497
Chris Lattner513165e2008-07-25 21:10:04 +0000498/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000499ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
John McCall50a2c2c2011-10-11 23:14:30 +0000500 // Handle any placeholder expressions which made it here.
501 if (E->getType()->isPlaceholderType()) {
502 ExprResult result = CheckPlaceholderExpr(E);
503 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000504 E = result.get();
John McCall50a2c2c2011-10-11 23:14:30 +0000505 }
506
Chris Lattner513165e2008-07-25 21:10:04 +0000507 QualType Ty = E->getType();
508 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
509
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +0000510 if (Ty->isFunctionType()) {
511 // If we are here, we are not calling a function but taking
512 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
513 if (getLangOpts().OpenCL) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000514 if (Diagnose)
515 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +0000516 return ExprError();
517 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000518
519 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
520 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
521 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
522 return ExprError();
523
John Wiegley01296292011-04-08 18:41:53 +0000524 E = ImpCastExprToType(E, Context.getPointerType(Ty),
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000525 CK_FunctionToPointerDecay).get();
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +0000526 } else if (Ty->isArrayType()) {
Chris Lattner61f60a02008-07-25 21:33:13 +0000527 // In C90 mode, arrays only promote to pointers if the array expression is
528 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
529 // type 'array of type' is converted to an expression that has type 'pointer
530 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
531 // that has type 'array of type' ...". The relevant change is "an lvalue"
532 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000533 //
534 // C++ 4.2p1:
535 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
536 // T" can be converted to an rvalue of type "pointer to T".
537 //
David Blaikiebbafb8a2012-03-11 07:00:24 +0000538 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000539 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000540 CK_ArrayToPointerDecay).get();
Chris Lattner61f60a02008-07-25 21:33:13 +0000541 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000542 return E;
Chris Lattner513165e2008-07-25 21:10:04 +0000543}
544
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000545static void CheckForNullPointerDereference(Sema &S, Expr *E) {
546 // Check to see if we are dereferencing a null pointer. If so,
547 // and if not volatile-qualified, this is undefined behavior that the
548 // optimizer will delete, so warn about it. People sometimes try to use this
549 // to get a deterministic trap and are surprised by clang's behavior. This
550 // only handles the pattern "*null", which is a very syntactic check.
551 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
552 if (UO->getOpcode() == UO_Deref &&
553 UO->getSubExpr()->IgnoreParenCasts()->
554 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
555 !UO->getType().isVolatileQualified()) {
556 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
557 S.PDiag(diag::warn_indirection_through_null)
558 << UO->getSubExpr()->getSourceRange());
559 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
560 S.PDiag(diag::note_indirection_through_null));
561 }
562}
563
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +0000564static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +0000565 SourceLocation AssignLoc,
566 const Expr* RHS) {
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +0000567 const ObjCIvarDecl *IV = OIRE->getDecl();
568 if (!IV)
569 return;
570
571 DeclarationName MemberName = IV->getDeclName();
572 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
573 if (!Member || !Member->isStr("isa"))
574 return;
575
576 const Expr *Base = OIRE->getBase();
577 QualType BaseType = Base->getType();
578 if (OIRE->isArrow())
579 BaseType = BaseType->getPointeeType();
580 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
581 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000582 ObjCInterfaceDecl *ClassDeclared = nullptr;
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +0000583 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
584 if (!ClassDeclared->getSuperClass()
585 && (*ClassDeclared->ivar_begin()) == IV) {
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +0000586 if (RHS) {
587 NamedDecl *ObjectSetClass =
588 S.LookupSingleName(S.TUScope,
589 &S.Context.Idents.get("object_setClass"),
590 SourceLocation(), S.LookupOrdinaryName);
591 if (ObjectSetClass) {
Craig Topper07fa1762015-11-15 02:31:46 +0000592 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +0000593 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
594 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
595 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
596 AssignLoc), ",") <<
597 FixItHint::CreateInsertion(RHSLocEnd, ")");
598 }
599 else
600 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
601 } else {
602 NamedDecl *ObjectGetClass =
603 S.LookupSingleName(S.TUScope,
604 &S.Context.Idents.get("object_getClass"),
605 SourceLocation(), S.LookupOrdinaryName);
606 if (ObjectGetClass)
607 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
608 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
609 FixItHint::CreateReplacement(
610 SourceRange(OIRE->getOpLoc(),
611 OIRE->getLocEnd()), ")");
612 else
613 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
614 }
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +0000615 S.Diag(IV->getLocation(), diag::note_ivar_decl);
616 }
617 }
618}
619
John Wiegley01296292011-04-08 18:41:53 +0000620ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000621 // Handle any placeholder expressions which made it here.
622 if (E->getType()->isPlaceholderType()) {
623 ExprResult result = CheckPlaceholderExpr(E);
624 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000625 E = result.get();
John McCall50a2c2c2011-10-11 23:14:30 +0000626 }
627
John McCallf3735e02010-12-01 04:43:34 +0000628 // C++ [conv.lval]p1:
629 // A glvalue of a non-function, non-array type T can be
630 // converted to a prvalue.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000631 if (!E->isGLValue()) return E;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +0000632
John McCall27584242010-12-06 20:48:59 +0000633 QualType T = E->getType();
634 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000635
John McCall27584242010-12-06 20:48:59 +0000636 // We don't want to throw lvalue-to-rvalue casts on top of
637 // expressions of certain types in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000638 if (getLangOpts().CPlusPlus &&
John McCall27584242010-12-06 20:48:59 +0000639 (E->getType() == Context.OverloadTy ||
640 T->isDependentType() ||
641 T->isRecordType()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000642 return E;
John McCall27584242010-12-06 20:48:59 +0000643
644 // The C standard is actually really unclear on this point, and
645 // DR106 tells us what the result should be but not why. It's
646 // generally best to say that void types just doesn't undergo
647 // lvalue-to-rvalue at all. Note that expressions of unqualified
648 // 'void' type are never l-values, but qualified void can be.
649 if (T->isVoidType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000650 return E;
John McCall27584242010-12-06 20:48:59 +0000651
John McCall6ced97a2013-02-12 01:29:43 +0000652 // OpenCL usually rejects direct accesses to values of 'half' type.
653 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
654 T->isHalfType()) {
655 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
656 << 0 << T;
657 return ExprError();
658 }
659
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000660 CheckForNullPointerDereference(*this, E);
Fariborz Jahanian06bb7f72013-03-28 19:50:55 +0000661 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
662 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
663 &Context.Idents.get("object_getClass"),
664 SourceLocation(), LookupOrdinaryName);
665 if (ObjectGetClass)
666 Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
667 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
668 FixItHint::CreateReplacement(
669 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
670 else
671 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
672 }
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +0000673 else if (const ObjCIvarRefExpr *OIRE =
674 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
Craig Topperc3ec1492014-05-26 06:22:03 +0000675 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
676
John McCall27584242010-12-06 20:48:59 +0000677 // C++ [conv.lval]p1:
678 // [...] If T is a non-class type, the type of the prvalue is the
679 // cv-unqualified version of T. Otherwise, the type of the
680 // rvalue is T.
681 //
682 // C99 6.3.2.1p2:
683 // If the lvalue has qualified type, the value has the unqualified
684 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000685 // type of the lvalue.
John McCall27584242010-12-06 20:48:59 +0000686 if (T.hasQualifiers())
687 T = T.getUnqualifiedType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000688
David Majnemercca07d72015-09-10 07:20:05 +0000689 if (T->isMemberPointerType() &&
690 Context.getTargetInfo().getCXXABI().isMicrosoft())
691 RequireCompleteType(E->getExprLoc(), T, 0);
692
Eli Friedman3bda6b12012-02-02 23:15:15 +0000693 UpdateMarkingForLValueToRValue(E);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +0000694
695 // Loading a __weak object implicitly retains the value, so we need a cleanup to
696 // balance that.
697 if (getLangOpts().ObjCAutoRefCount &&
698 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
699 ExprNeedsCleanups = true;
Eli Friedman3bda6b12012-02-02 23:15:15 +0000700
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000701 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
702 nullptr, VK_RValue);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000703
Douglas Gregorc79862f2012-04-12 17:51:55 +0000704 // C11 6.3.2.1p2:
705 // ... if the lvalue has atomic type, the value has the non-atomic version
706 // of the type of the lvalue ...
707 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
708 T = Atomic->getValueType().getUnqualifiedType();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000709 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
710 nullptr, VK_RValue);
Douglas Gregorc79862f2012-04-12 17:51:55 +0000711 }
712
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000713 return Res;
John McCall27584242010-12-06 20:48:59 +0000714}
715
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000716ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
717 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
John Wiegley01296292011-04-08 18:41:53 +0000718 if (Res.isInvalid())
719 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000720 Res = DefaultLvalueConversion(Res.get());
John Wiegley01296292011-04-08 18:41:53 +0000721 if (Res.isInvalid())
722 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000723 return Res;
Douglas Gregorb92a1562010-02-03 00:27:59 +0000724}
725
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +0000726/// CallExprUnaryConversions - a special case of an unary conversion
727/// performed on a function designator of a call expression.
728ExprResult Sema::CallExprUnaryConversions(Expr *E) {
729 QualType Ty = E->getType();
730 ExprResult Res = E;
731 // Only do implicit cast for a function type, but not for a pointer
732 // to function type.
733 if (Ty->isFunctionType()) {
734 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000735 CK_FunctionToPointerDecay).get();
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +0000736 if (Res.isInvalid())
737 return ExprError();
738 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000739 Res = DefaultLvalueConversion(Res.get());
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +0000740 if (Res.isInvalid())
741 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000742 return Res.get();
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +0000743}
Douglas Gregorb92a1562010-02-03 00:27:59 +0000744
Chris Lattner513165e2008-07-25 21:10:04 +0000745/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000746/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000747/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000748/// apply if the array is an argument to the sizeof or address (&) operators.
749/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000750ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000751 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000752 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
753 if (Res.isInvalid())
Fariborz Jahanian47ef4662013-03-06 00:37:40 +0000754 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000755 E = Res.get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000756
John McCallf3735e02010-12-01 04:43:34 +0000757 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000758 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000759
Joey Goulydd7f4562013-01-23 11:56:20 +0000760 // Half FP have to be promoted to float unless it is natively supported
761 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000762 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000763
John McCallf3735e02010-12-01 04:43:34 +0000764 // Try to perform integral promotions if the object has a theoretically
765 // promotable type.
766 if (Ty->isIntegralOrUnscopedEnumerationType()) {
767 // C99 6.3.1.1p2:
768 //
769 // The following may be used in an expression wherever an int or
770 // unsigned int may be used:
771 // - an object or expression with an integer type whose integer
772 // conversion rank is less than or equal to the rank of int
773 // and unsigned int.
774 // - A bit-field of type _Bool, int, signed int, or unsigned int.
775 //
776 // If an int can represent all values of the original type, the
777 // value is converted to an int; otherwise, it is converted to an
778 // unsigned int. These are called the integer promotions. All
779 // other types are unchanged by the integer promotions.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000780
John McCallf3735e02010-12-01 04:43:34 +0000781 QualType PTy = Context.isPromotableBitField(E);
782 if (!PTy.isNull()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000783 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000784 return E;
John McCallf3735e02010-12-01 04:43:34 +0000785 }
786 if (Ty->isPromotableIntegerType()) {
787 QualType PT = Context.getPromotedIntegerType(Ty);
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000788 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000789 return E;
John McCallf3735e02010-12-01 04:43:34 +0000790 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000791 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000792 return E;
Chris Lattner513165e2008-07-25 21:10:04 +0000793}
794
Chris Lattner2ce500f2008-07-25 22:25:12 +0000795/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Tim Northoverda165072013-01-30 09:46:55 +0000796/// do not have a prototype. Arguments that have type float or __fp16
797/// are promoted to double. All other argument types are converted by
798/// UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000799ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
800 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000801 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000802
John Wiegley01296292011-04-08 18:41:53 +0000803 ExprResult Res = UsualUnaryConversions(E);
804 if (Res.isInvalid())
Fariborz Jahanian47ef4662013-03-06 00:37:40 +0000805 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000806 E = Res.get();
John McCall9bc26772010-12-06 18:36:11 +0000807
Tim Northoverda165072013-01-30 09:46:55 +0000808 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
809 // double.
810 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
811 if (BTy && (BTy->getKind() == BuiltinType::Half ||
812 BTy->getKind() == BuiltinType::Float))
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000813 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
John Wiegley01296292011-04-08 18:41:53 +0000814
John McCall4bb057d2011-08-27 22:06:17 +0000815 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall0562caa2011-08-29 23:55:37 +0000816 // promotion, even on class types, but note:
817 // C++11 [conv.lval]p2:
818 // When an lvalue-to-rvalue conversion occurs in an unevaluated
819 // operand or a subexpression thereof the value contained in the
820 // referenced object is not accessed. Otherwise, if the glvalue
821 // has a class type, the conversion copy-initializes a temporary
822 // of type T from the glvalue and the result of the conversion
823 // is a prvalue for the temporary.
Eli Friedman05e28012012-01-17 02:13:45 +0000824 // FIXME: add some way to gate this entire thing for correctness in
825 // potentially potentially evaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +0000826 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
Eli Friedman05e28012012-01-17 02:13:45 +0000827 ExprResult Temp = PerformCopyInitialization(
828 InitializedEntity::InitializeTemporary(E->getType()),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000829 E->getExprLoc(), E);
Eli Friedman05e28012012-01-17 02:13:45 +0000830 if (Temp.isInvalid())
831 return ExprError();
832 E = Temp.get();
John McCall29ad95b2011-08-27 01:09:30 +0000833 }
834
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000835 return E;
Chris Lattner2ce500f2008-07-25 22:25:12 +0000836}
837
Richard Smith55ce3522012-06-25 20:30:08 +0000838/// Determine the degree of POD-ness for an expression.
839/// Incomplete types are considered POD, since this check can be performed
840/// when we're in an unevaluated context.
841Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
Jordan Rose3e0ec582012-07-19 18:10:23 +0000842 if (Ty->isIncompleteType()) {
Richard Smithd7293d72013-08-05 18:49:43 +0000843 // C++11 [expr.call]p7:
844 // After these conversions, if the argument does not have arithmetic,
845 // enumeration, pointer, pointer to member, or class type, the program
846 // is ill-formed.
847 //
848 // Since we've already performed array-to-pointer and function-to-pointer
849 // decay, the only such type in C++ is cv void. This also handles
850 // initializer lists as variadic arguments.
851 if (Ty->isVoidType())
852 return VAK_Invalid;
853
Jordan Rose3e0ec582012-07-19 18:10:23 +0000854 if (Ty->isObjCObjectType())
855 return VAK_Invalid;
Richard Smith55ce3522012-06-25 20:30:08 +0000856 return VAK_Valid;
Jordan Rose3e0ec582012-07-19 18:10:23 +0000857 }
858
859 if (Ty.isCXX98PODType(Context))
860 return VAK_Valid;
861
Richard Smith16488472012-11-16 00:53:38 +0000862 // C++11 [expr.call]p7:
863 // Passing a potentially-evaluated argument of class type (Clause 9)
Richard Smith55ce3522012-06-25 20:30:08 +0000864 // having a non-trivial copy constructor, a non-trivial move constructor,
Richard Smith16488472012-11-16 00:53:38 +0000865 // or a non-trivial destructor, with no corresponding parameter,
Richard Smith55ce3522012-06-25 20:30:08 +0000866 // is conditionally-supported with implementation-defined semantics.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000867 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
Richard Smith55ce3522012-06-25 20:30:08 +0000868 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
Richard Smith16488472012-11-16 00:53:38 +0000869 if (!Record->hasNonTrivialCopyConstructor() &&
870 !Record->hasNonTrivialMoveConstructor() &&
871 !Record->hasNonTrivialDestructor())
Richard Smith55ce3522012-06-25 20:30:08 +0000872 return VAK_ValidInCXX11;
873
874 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
875 return VAK_Valid;
Richard Smithd7293d72013-08-05 18:49:43 +0000876
877 if (Ty->isObjCObjectType())
878 return VAK_Invalid;
879
Hans Wennborgd9dd4d22014-09-29 23:06:57 +0000880 if (getLangOpts().MSVCCompat)
881 return VAK_MSVCUndefined;
882
Richard Smithd7293d72013-08-05 18:49:43 +0000883 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
884 // permitted to reject them. We should consider doing so.
885 return VAK_Undefined;
Richard Smith55ce3522012-06-25 20:30:08 +0000886}
887
Richard Smithd7293d72013-08-05 18:49:43 +0000888void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
Richard Smith55ce3522012-06-25 20:30:08 +0000889 // Don't allow one to pass an Objective-C interface to a vararg.
Richard Smithd7293d72013-08-05 18:49:43 +0000890 const QualType &Ty = E->getType();
891 VarArgKind VAK = isValidVarArgType(Ty);
Richard Smith55ce3522012-06-25 20:30:08 +0000892
893 // Complain about passing non-POD types through varargs.
Richard Smithd7293d72013-08-05 18:49:43 +0000894 switch (VAK) {
Richard Smithd7293d72013-08-05 18:49:43 +0000895 case VAK_ValidInCXX11:
896 DiagRuntimeBehavior(
Craig Topperc3ec1492014-05-26 06:22:03 +0000897 E->getLocStart(), nullptr,
Richard Smithd7293d72013-08-05 18:49:43 +0000898 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
Richard Smith2868a732014-02-28 01:36:39 +0000899 << Ty << CT);
900 // Fall through.
901 case VAK_Valid:
902 if (Ty->isRecordType()) {
903 // This is unlikely to be what the user intended. If the class has a
904 // 'c_str' member function, the user probably meant to call that.
Craig Topperc3ec1492014-05-26 06:22:03 +0000905 DiagRuntimeBehavior(E->getLocStart(), nullptr,
Richard Smith2868a732014-02-28 01:36:39 +0000906 PDiag(diag::warn_pass_class_arg_to_vararg)
907 << Ty << CT << hasCStrMethod(E) << ".c_str()");
908 }
Richard Smithd7293d72013-08-05 18:49:43 +0000909 break;
910
911 case VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +0000912 case VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +0000913 DiagRuntimeBehavior(
Craig Topperc3ec1492014-05-26 06:22:03 +0000914 E->getLocStart(), nullptr,
Richard Smithd7293d72013-08-05 18:49:43 +0000915 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
916 << getLangOpts().CPlusPlus11 << Ty << CT);
917 break;
918
919 case VAK_Invalid:
920 if (Ty->isObjCObjectType())
921 DiagRuntimeBehavior(
Craig Topperc3ec1492014-05-26 06:22:03 +0000922 E->getLocStart(), nullptr,
Richard Smithd7293d72013-08-05 18:49:43 +0000923 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
924 << Ty << CT);
925 else
926 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
927 << isa<InitListExpr>(E) << Ty << CT;
928 break;
Richard Smith55ce3522012-06-25 20:30:08 +0000929 }
Richard Smith55ce3522012-06-25 20:30:08 +0000930}
931
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000932/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
Jordan Rose3e0ec582012-07-19 18:10:23 +0000933/// will create a trap if the resulting type is not a POD type.
John Wiegley01296292011-04-08 18:41:53 +0000934ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000935 FunctionDecl *FDecl) {
Richard Smith7659b122012-06-27 20:29:39 +0000936 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
John McCall4124c492011-10-17 18:40:02 +0000937 // Strip the unbridged-cast placeholder expression off, if applicable.
938 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
939 (CT == VariadicMethod ||
940 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
941 E = stripARCUnbridgedCast(E);
942
943 // Otherwise, do normal placeholder checking.
944 } else {
945 ExprResult ExprRes = CheckPlaceholderExpr(E);
946 if (ExprRes.isInvalid())
947 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000948 E = ExprRes.get();
John McCall4124c492011-10-17 18:40:02 +0000949 }
950 }
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000951
John McCall4124c492011-10-17 18:40:02 +0000952 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000953 if (ExprRes.isInvalid())
954 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000955 E = ExprRes.get();
Mike Stump11289f42009-09-09 15:08:12 +0000956
Richard Smith55ce3522012-06-25 20:30:08 +0000957 // Diagnostics regarding non-POD argument types are
958 // emitted along with format string checking in Sema::CheckFunctionCall().
Richard Smithd7293d72013-08-05 18:49:43 +0000959 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
Richard Smith55ce3522012-06-25 20:30:08 +0000960 // Turn this into a trap.
961 CXXScopeSpec SS;
962 SourceLocation TemplateKWLoc;
963 UnqualifiedId Name;
964 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
965 E->getLocStart());
966 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
967 Name, true, false);
968 if (TrapFn.isInvalid())
969 return ExprError();
John McCall31168b02011-06-15 23:02:42 +0000970
Richard Smith55ce3522012-06-25 20:30:08 +0000971 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
Dmitri Gribenko78852e92013-05-05 20:40:26 +0000972 E->getLocStart(), None,
Richard Smith55ce3522012-06-25 20:30:08 +0000973 E->getLocEnd());
974 if (Call.isInvalid())
975 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000976
Richard Smith55ce3522012-06-25 20:30:08 +0000977 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
978 Call.get(), E);
979 if (Comma.isInvalid())
980 return ExprError();
981 return Comma.get();
Douglas Gregor253cadf2011-05-21 16:27:21 +0000982 }
Richard Smith55ce3522012-06-25 20:30:08 +0000983
David Blaikiebbafb8a2012-03-11 07:00:24 +0000984 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000985 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahanianbf482812012-03-02 17:05:03 +0000986 diag::err_call_incomplete_argument))
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000987 return ExprError();
Richard Smith55ce3522012-06-25 20:30:08 +0000988
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000989 return E;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000990}
991
Richard Trieu7aa58f12011-09-02 20:58:51 +0000992/// \brief Converts an integer to complex float type. Helper function of
993/// UsualArithmeticConversions()
994///
995/// \return false if the integer expression is an integer type and is
996/// successfully converted to the complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000997static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
998 ExprResult &ComplexExpr,
999 QualType IntTy,
1000 QualType ComplexTy,
1001 bool SkipCast) {
1002 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1003 if (SkipCast) return false;
1004 if (IntTy->isIntegerType()) {
1005 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001006 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1007 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +00001008 CK_FloatingRealToComplex);
1009 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +00001010 assert(IntTy->isComplexIntegerType());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001011 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +00001012 CK_IntegralComplexToFloatingComplex);
1013 }
1014 return false;
1015}
1016
Richard Trieu7aa58f12011-09-02 20:58:51 +00001017/// \brief Handle arithmetic conversion with complex types. Helper function of
1018/// UsualArithmeticConversions()
Richard Trieu5065cdd2011-09-06 18:25:09 +00001019static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1020 ExprResult &RHS, QualType LHSType,
1021 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001022 bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +00001023 // if we have an integer operand, the result is the complex type.
Richard Trieu5065cdd2011-09-06 18:25:09 +00001024 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +00001025 /*skipCast*/false))
Richard Trieu5065cdd2011-09-06 18:25:09 +00001026 return LHSType;
1027 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001028 /*skipCast*/IsCompAssign))
Richard Trieu5065cdd2011-09-06 18:25:09 +00001029 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +00001030
1031 // This handles complex/complex, complex/float, or float/complex.
1032 // When both operands are complex, the shorter operand is converted to the
1033 // type of the longer, and that is the type of the result. This corresponds
1034 // to what is done when combining two real floating-point operands.
1035 // The fun begins when size promotion occur across type domains.
1036 // From H&S 6.3.4: When one operand is complex and the other is a real
1037 // floating-point type, the less precise type is converted, within it's
1038 // real or complex domain, to the precision of the other type. For example,
1039 // when combining a "long double" with a "double _Complex", the
1040 // "double _Complex" is promoted to "long double _Complex".
1041
Chandler Carrutha216cad2014-10-11 00:57:18 +00001042 // Compute the rank of the two types, regardless of whether they are complex.
1043 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +00001044
Chandler Carrutha216cad2014-10-11 00:57:18 +00001045 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1046 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1047 QualType LHSElementType =
1048 LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1049 QualType RHSElementType =
1050 RHSComplexType ? RHSComplexType->getElementType() : RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +00001051
Chandler Carrutha216cad2014-10-11 00:57:18 +00001052 QualType ResultType = S.Context.getComplexType(LHSElementType);
1053 if (Order < 0) {
1054 // Promote the precision of the LHS if not an assignment.
1055 ResultType = S.Context.getComplexType(RHSElementType);
1056 if (!IsCompAssign) {
1057 if (LHSComplexType)
1058 LHS =
1059 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1060 else
1061 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1062 }
1063 } else if (Order > 0) {
1064 // Promote the precision of the RHS.
1065 if (RHSComplexType)
1066 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1067 else
1068 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1069 }
1070 return ResultType;
Richard Trieu7aa58f12011-09-02 20:58:51 +00001071}
1072
1073/// \brief Hande arithmetic conversion from integer to float. Helper function
1074/// of UsualArithmeticConversions()
Richard Trieuba63ce62011-09-09 01:45:06 +00001075static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1076 ExprResult &IntExpr,
1077 QualType FloatTy, QualType IntTy,
1078 bool ConvertFloat, bool ConvertInt) {
1079 if (IntTy->isIntegerType()) {
1080 if (ConvertInt)
Richard Trieu7aa58f12011-09-02 20:58:51 +00001081 // Convert intExpr to the lhs floating point type.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001082 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +00001083 CK_IntegralToFloating);
Richard Trieuba63ce62011-09-09 01:45:06 +00001084 return FloatTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +00001085 }
1086
1087 // Convert both sides to the appropriate complex float.
Richard Trieuba63ce62011-09-09 01:45:06 +00001088 assert(IntTy->isComplexIntegerType());
1089 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +00001090
1091 // _Complex int -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +00001092 if (ConvertInt)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001093 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +00001094 CK_IntegralComplexToFloatingComplex);
1095
1096 // float -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +00001097 if (ConvertFloat)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001098 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +00001099 CK_FloatingRealToComplex);
1100
1101 return result;
1102}
1103
1104/// \brief Handle arithmethic conversion with floating point types. Helper
1105/// function of UsualArithmeticConversions()
Richard Trieucfe3f212011-09-06 18:38:41 +00001106static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1107 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001108 QualType RHSType, bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +00001109 bool LHSFloat = LHSType->isRealFloatingType();
1110 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu7aa58f12011-09-02 20:58:51 +00001111
1112 // If we have two real floating types, convert the smaller operand
1113 // to the bigger result.
1114 if (LHSFloat && RHSFloat) {
Richard Trieucfe3f212011-09-06 18:38:41 +00001115 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +00001116 if (order > 0) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001117 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
Richard Trieucfe3f212011-09-06 18:38:41 +00001118 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +00001119 }
1120
1121 assert(order < 0 && "illegal float comparison");
Richard Trieuba63ce62011-09-09 01:45:06 +00001122 if (!IsCompAssign)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001123 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
Richard Trieucfe3f212011-09-06 18:38:41 +00001124 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +00001125 }
1126
Ahmed Bougacha5b639082015-05-29 22:54:57 +00001127 if (LHSFloat) {
1128 // Half FP has to be promoted to float unless it is natively supported
1129 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1130 LHSType = S.Context.FloatTy;
1131
Richard Trieucfe3f212011-09-06 18:38:41 +00001132 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001133 /*convertFloat=*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +00001134 /*convertInt=*/ true);
Ahmed Bougacha5b639082015-05-29 22:54:57 +00001135 }
Richard Trieu7aa58f12011-09-02 20:58:51 +00001136 assert(RHSFloat);
Richard Trieucfe3f212011-09-06 18:38:41 +00001137 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +00001138 /*convertInt=*/ true,
Richard Trieuba63ce62011-09-09 01:45:06 +00001139 /*convertFloat=*/!IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +00001140}
1141
Bill Schmidteb03ae22013-02-01 15:34:29 +00001142typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
Richard Trieu7aa58f12011-09-02 20:58:51 +00001143
Bill Schmidteb03ae22013-02-01 15:34:29 +00001144namespace {
1145/// These helper callbacks are placed in an anonymous namespace to
1146/// permit their use as function template parameters.
1147ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1148 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1149}
Richard Trieu7aa58f12011-09-02 20:58:51 +00001150
Bill Schmidteb03ae22013-02-01 15:34:29 +00001151ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1152 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1153 CK_IntegralComplexCast);
1154}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001155}
Richard Trieu7aa58f12011-09-02 20:58:51 +00001156
1157/// \brief Handle integer arithmetic conversions. Helper function of
1158/// UsualArithmeticConversions()
Bill Schmidteb03ae22013-02-01 15:34:29 +00001159template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001160static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1161 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001162 QualType RHSType, bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +00001163 // The rules for this case are in C99 6.3.1.8
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001164 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1165 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1166 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1167 if (LHSSigned == RHSSigned) {
Richard Trieu7aa58f12011-09-02 20:58:51 +00001168 // Same signedness; use the higher-ranked type
1169 if (order >= 0) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001170 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001171 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +00001172 } else if (!IsCompAssign)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001173 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001174 return RHSType;
1175 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +00001176 // The unsigned type has greater than or equal rank to the
1177 // signed type, so use the unsigned type
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001178 if (RHSSigned) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001179 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001180 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +00001181 } else if (!IsCompAssign)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001182 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001183 return RHSType;
1184 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +00001185 // The two types are different widths; if we are here, that
1186 // means the signed type is larger than the unsigned type, so
1187 // use the signed type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001188 if (LHSSigned) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001189 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001190 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +00001191 } else if (!IsCompAssign)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001192 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001193 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +00001194 } else {
1195 // The signed type is higher-ranked than the unsigned type,
1196 // but isn't actually any bigger (like unsigned int and long
1197 // on most 32-bit systems). Use the unsigned type corresponding
1198 // to the signed type.
1199 QualType result =
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001200 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001201 RHS = (*doRHSCast)(S, RHS.get(), result);
Richard Trieuba63ce62011-09-09 01:45:06 +00001202 if (!IsCompAssign)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001203 LHS = (*doLHSCast)(S, LHS.get(), result);
Richard Trieu7aa58f12011-09-02 20:58:51 +00001204 return result;
1205 }
1206}
1207
Bill Schmidteb03ae22013-02-01 15:34:29 +00001208/// \brief Handle conversions with GCC complex int extension. Helper function
1209/// of UsualArithmeticConversions()
1210static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1211 ExprResult &RHS, QualType LHSType,
1212 QualType RHSType,
1213 bool IsCompAssign) {
1214 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1215 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1216
1217 if (LHSComplexInt && RHSComplexInt) {
1218 QualType LHSEltType = LHSComplexInt->getElementType();
1219 QualType RHSEltType = RHSComplexInt->getElementType();
1220 QualType ScalarType =
1221 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1222 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1223
1224 return S.Context.getComplexType(ScalarType);
1225 }
1226
1227 if (LHSComplexInt) {
1228 QualType LHSEltType = LHSComplexInt->getElementType();
1229 QualType ScalarType =
1230 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1231 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1232 QualType ComplexType = S.Context.getComplexType(ScalarType);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001233 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
Bill Schmidteb03ae22013-02-01 15:34:29 +00001234 CK_IntegralRealToComplex);
1235
1236 return ComplexType;
1237 }
1238
1239 assert(RHSComplexInt);
1240
1241 QualType RHSEltType = RHSComplexInt->getElementType();
1242 QualType ScalarType =
1243 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1244 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1245 QualType ComplexType = S.Context.getComplexType(ScalarType);
1246
1247 if (!IsCompAssign)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001248 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
Bill Schmidteb03ae22013-02-01 15:34:29 +00001249 CK_IntegralRealToComplex);
1250 return ComplexType;
1251}
1252
Chris Lattner513165e2008-07-25 21:10:04 +00001253/// UsualArithmeticConversions - Performs various conversions that are common to
1254/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +00001255/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +00001256/// responsible for emitting appropriate error diagnostics.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001257QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00001258 bool IsCompAssign) {
1259 if (!IsCompAssign) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001260 LHS = UsualUnaryConversions(LHS.get());
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001261 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001262 return QualType();
1263 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00001264
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001265 RHS = UsualUnaryConversions(RHS.get());
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001266 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001267 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001268
Mike Stump11289f42009-09-09 15:08:12 +00001269 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +00001270 // For example, "const float" and "float" are equivalent.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001271 QualType LHSType =
1272 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1273 QualType RHSType =
1274 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001275
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001276 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1277 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1278 LHSType = AtomicLHS->getValueType();
1279
Douglas Gregora11693b2008-11-12 17:17:38 +00001280 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001281 if (LHSType == RHSType)
1282 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +00001283
1284 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1285 // The caller can deal with this (e.g. pointer + int).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001286 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001287 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001288
John McCalld005ac92010-11-13 08:17:45 +00001289 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001290 QualType LHSUnpromotedType = LHSType;
1291 if (LHSType->isPromotableIntegerType())
1292 LHSType = Context.getPromotedIntegerType(LHSType);
1293 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +00001294 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001295 LHSType = LHSBitfieldPromoteTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00001296 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001297 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +00001298
John McCalld005ac92010-11-13 08:17:45 +00001299 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001300 if (LHSType == RHSType)
1301 return LHSType;
John McCalld005ac92010-11-13 08:17:45 +00001302
1303 // At this point, we have two different arithmetic types.
1304
1305 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001306 if (LHSType->isComplexType() || RHSType->isComplexType())
1307 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001308 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001309
1310 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001311 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1312 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001313 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001314
1315 // Handle GCC complex int extension.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001316 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer499c68b2011-09-06 19:57:14 +00001317 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001318 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001319
1320 // Finally, we have two differing integer types.
Bill Schmidteb03ae22013-02-01 15:34:29 +00001321 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1322 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
Douglas Gregora11693b2008-11-12 17:17:38 +00001323}
1324
Bill Schmidteb03ae22013-02-01 15:34:29 +00001325
Chris Lattner513165e2008-07-25 21:10:04 +00001326//===----------------------------------------------------------------------===//
1327// Semantic Analysis for various Expression Types
1328//===----------------------------------------------------------------------===//
1329
1330
Peter Collingbourne91147592011-04-15 00:35:48 +00001331ExprResult
1332Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1333 SourceLocation DefaultLoc,
1334 SourceLocation RParenLoc,
1335 Expr *ControllingExpr,
Dmitri Gribenko82360372013-05-10 13:06:58 +00001336 ArrayRef<ParsedType> ArgTypes,
1337 ArrayRef<Expr *> ArgExprs) {
Richard Trieuba63ce62011-09-09 01:45:06 +00001338 unsigned NumAssocs = ArgTypes.size();
1339 assert(NumAssocs == ArgExprs.size());
Peter Collingbourne91147592011-04-15 00:35:48 +00001340
Peter Collingbourne91147592011-04-15 00:35:48 +00001341 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1342 for (unsigned i = 0; i < NumAssocs; ++i) {
Dmitri Gribenko82360372013-05-10 13:06:58 +00001343 if (ArgTypes[i])
1344 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
Peter Collingbourne91147592011-04-15 00:35:48 +00001345 else
Craig Topperc3ec1492014-05-26 06:22:03 +00001346 Types[i] = nullptr;
Peter Collingbourne91147592011-04-15 00:35:48 +00001347 }
1348
1349 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
Dmitri Gribenko82360372013-05-10 13:06:58 +00001350 ControllingExpr,
1351 llvm::makeArrayRef(Types, NumAssocs),
1352 ArgExprs);
Benjamin Kramer34623762011-04-15 11:21:57 +00001353 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +00001354 return ER;
1355}
1356
1357ExprResult
1358Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1359 SourceLocation DefaultLoc,
1360 SourceLocation RParenLoc,
1361 Expr *ControllingExpr,
Dmitri Gribenko82360372013-05-10 13:06:58 +00001362 ArrayRef<TypeSourceInfo *> Types,
1363 ArrayRef<Expr *> Exprs) {
1364 unsigned NumAssocs = Types.size();
1365 assert(NumAssocs == Exprs.size());
Aaron Ballmanb035cd72015-11-05 00:06:05 +00001366
1367 // Decay and strip qualifiers for the controlling expression type, and handle
1368 // placeholder type replacement. See committee discussion from WG14 DR423.
1369 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1370 if (R.isInvalid())
1371 return ExprError();
1372 ControllingExpr = R.get();
John McCall587b3482013-02-12 02:08:12 +00001373
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00001374 // The controlling expression is an unevaluated operand, so side effects are
1375 // likely unintended.
1376 if (ActiveTemplateInstantiations.empty() &&
1377 ControllingExpr->HasSideEffects(Context, false))
1378 Diag(ControllingExpr->getExprLoc(),
1379 diag::warn_side_effects_unevaluated_context);
1380
Peter Collingbourne91147592011-04-15 00:35:48 +00001381 bool TypeErrorFound = false,
1382 IsResultDependent = ControllingExpr->isTypeDependent(),
1383 ContainsUnexpandedParameterPack
1384 = ControllingExpr->containsUnexpandedParameterPack();
1385
1386 for (unsigned i = 0; i < NumAssocs; ++i) {
1387 if (Exprs[i]->containsUnexpandedParameterPack())
1388 ContainsUnexpandedParameterPack = true;
1389
1390 if (Types[i]) {
1391 if (Types[i]->getType()->containsUnexpandedParameterPack())
1392 ContainsUnexpandedParameterPack = true;
1393
1394 if (Types[i]->getType()->isDependentType()) {
1395 IsResultDependent = true;
1396 } else {
Benjamin Kramere56f3932011-12-23 17:00:35 +00001397 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbourne91147592011-04-15 00:35:48 +00001398 // complete object type other than a variably modified type."
1399 unsigned D = 0;
1400 if (Types[i]->getType()->isIncompleteType())
1401 D = diag::err_assoc_type_incomplete;
1402 else if (!Types[i]->getType()->isObjectType())
1403 D = diag::err_assoc_type_nonobject;
1404 else if (Types[i]->getType()->isVariablyModifiedType())
1405 D = diag::err_assoc_type_variably_modified;
1406
1407 if (D != 0) {
1408 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1409 << Types[i]->getTypeLoc().getSourceRange()
1410 << Types[i]->getType();
1411 TypeErrorFound = true;
1412 }
1413
Benjamin Kramere56f3932011-12-23 17:00:35 +00001414 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbourne91147592011-04-15 00:35:48 +00001415 // selection shall specify compatible types."
1416 for (unsigned j = i+1; j < NumAssocs; ++j)
1417 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1418 Context.typesAreCompatible(Types[i]->getType(),
1419 Types[j]->getType())) {
1420 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1421 diag::err_assoc_compatible_types)
1422 << Types[j]->getTypeLoc().getSourceRange()
1423 << Types[j]->getType()
1424 << Types[i]->getType();
1425 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1426 diag::note_compat_assoc)
1427 << Types[i]->getTypeLoc().getSourceRange()
1428 << Types[i]->getType();
1429 TypeErrorFound = true;
1430 }
1431 }
1432 }
1433 }
1434 if (TypeErrorFound)
1435 return ExprError();
1436
1437 // If we determined that the generic selection is result-dependent, don't
1438 // try to compute the result expression.
1439 if (IsResultDependent)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001440 return new (Context) GenericSelectionExpr(
1441 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1442 ContainsUnexpandedParameterPack);
Peter Collingbourne91147592011-04-15 00:35:48 +00001443
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001444 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +00001445 unsigned DefaultIndex = -1U;
1446 for (unsigned i = 0; i < NumAssocs; ++i) {
1447 if (!Types[i])
1448 DefaultIndex = i;
1449 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1450 Types[i]->getType()))
1451 CompatIndices.push_back(i);
1452 }
1453
Benjamin Kramere56f3932011-12-23 17:00:35 +00001454 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbourne91147592011-04-15 00:35:48 +00001455 // type compatible with at most one of the types named in its generic
1456 // association list."
1457 if (CompatIndices.size() > 1) {
1458 // We strip parens here because the controlling expression is typically
1459 // parenthesized in macro definitions.
1460 ControllingExpr = ControllingExpr->IgnoreParens();
1461 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1462 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1463 << (unsigned) CompatIndices.size();
Craig Topper2341c0d2013-07-04 03:08:24 +00001464 for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +00001465 E = CompatIndices.end(); I != E; ++I) {
1466 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1467 diag::note_compat_assoc)
1468 << Types[*I]->getTypeLoc().getSourceRange()
1469 << Types[*I]->getType();
1470 }
1471 return ExprError();
1472 }
1473
Benjamin Kramere56f3932011-12-23 17:00:35 +00001474 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbourne91147592011-04-15 00:35:48 +00001475 // its controlling expression shall have type compatible with exactly one of
1476 // the types named in its generic association list."
1477 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1478 // We strip parens here because the controlling expression is typically
1479 // parenthesized in macro definitions.
1480 ControllingExpr = ControllingExpr->IgnoreParens();
1481 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1482 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1483 return ExprError();
1484 }
1485
Benjamin Kramere56f3932011-12-23 17:00:35 +00001486 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbourne91147592011-04-15 00:35:48 +00001487 // type name that is compatible with the type of the controlling expression,
1488 // then the result expression of the generic selection is the expression
1489 // in that generic association. Otherwise, the result expression of the
1490 // generic selection is the expression in the default generic association."
1491 unsigned ResultIndex =
1492 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1493
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001494 return new (Context) GenericSelectionExpr(
1495 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1496 ContainsUnexpandedParameterPack, ResultIndex);
Peter Collingbourne91147592011-04-15 00:35:48 +00001497}
1498
Richard Smith75b67d62012-03-08 01:34:56 +00001499/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1500/// location of the token and the offset of the ud-suffix within it.
1501static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1502 unsigned Offset) {
1503 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001504 S.getLangOpts());
Richard Smith75b67d62012-03-08 01:34:56 +00001505}
1506
Richard Smithbcc22fc2012-03-09 08:00:36 +00001507/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1508/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1509static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1510 IdentifierInfo *UDSuffix,
1511 SourceLocation UDSuffixLoc,
1512 ArrayRef<Expr*> Args,
1513 SourceLocation LitEndLoc) {
1514 assert(Args.size() <= 2 && "too many arguments for literal operator");
1515
1516 QualType ArgTy[2];
1517 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1518 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1519 if (ArgTy[ArgIdx]->isArrayType())
1520 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1521 }
1522
1523 DeclarationName OpName =
1524 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1525 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1526 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1527
1528 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1529 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
Richard Smithb8b41d32013-10-07 19:57:58 +00001530 /*AllowRaw*/false, /*AllowTemplate*/false,
1531 /*AllowStringTemplate*/false) == Sema::LOLR_Error)
Richard Smithbcc22fc2012-03-09 08:00:36 +00001532 return ExprError();
1533
1534 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1535}
1536
Steve Naroff83895f72007-09-16 03:34:24 +00001537/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001538/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1539/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1540/// multiple tokens. However, the common case is that StringToks points to one
1541/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001542///
John McCalldadc5752010-08-24 06:29:42 +00001543ExprResult
Craig Topper9d5583e2014-06-26 04:58:39 +00001544Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1545 assert(!StringToks.empty() && "Must have at least one string!");
Chris Lattner5b183d82006-11-10 05:03:26 +00001546
Craig Topper9d5583e2014-06-26 04:58:39 +00001547 StringLiteralParser Literal(StringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001548 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001549 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001550
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001551 SmallVector<SourceLocation, 4> StringTokLocs;
Craig Topper9d5583e2014-06-26 04:58:39 +00001552 for (unsigned i = 0; i != StringToks.size(); ++i)
Chris Lattner5b183d82006-11-10 05:03:26 +00001553 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001554
Richard Smithb8b41d32013-10-07 19:57:58 +00001555 QualType CharTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001556 StringLiteral::StringKind Kind = StringLiteral::Ascii;
Richard Smithb8b41d32013-10-07 19:57:58 +00001557 if (Literal.isWide()) {
1558 CharTy = Context.getWideCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001559 Kind = StringLiteral::Wide;
Richard Smithb8b41d32013-10-07 19:57:58 +00001560 } else if (Literal.isUTF8()) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00001561 Kind = StringLiteral::UTF8;
Richard Smithb8b41d32013-10-07 19:57:58 +00001562 } else if (Literal.isUTF16()) {
1563 CharTy = Context.Char16Ty;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001564 Kind = StringLiteral::UTF16;
Richard Smithb8b41d32013-10-07 19:57:58 +00001565 } else if (Literal.isUTF32()) {
1566 CharTy = Context.Char32Ty;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001567 Kind = StringLiteral::UTF32;
Richard Smithb8b41d32013-10-07 19:57:58 +00001568 } else if (Literal.isPascal()) {
1569 CharTy = Context.UnsignedCharTy;
1570 }
Douglas Gregorfb65e592011-07-27 05:40:30 +00001571
Richard Smithb8b41d32013-10-07 19:57:58 +00001572 QualType CharTyConst = CharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001573 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001574 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Richard Smithb8b41d32013-10-07 19:57:58 +00001575 CharTyConst.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001576
Chris Lattner36fc8792008-02-11 00:02:17 +00001577 // Get an array type for the string, according to C99 6.4.5. This includes
1578 // the nul terminator character as well as the string length for pascal
1579 // strings.
Richard Smithb8b41d32013-10-07 19:57:58 +00001580 QualType StrTy = Context.getConstantArrayType(CharTyConst,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001581 llvm::APInt(32, Literal.GetNumStringChars()+1),
Richard Smithb8b41d32013-10-07 19:57:58 +00001582 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001583
Joey Gouly561bba22013-11-14 18:26:10 +00001584 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1585 if (getLangOpts().OpenCL) {
1586 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1587 }
1588
Chris Lattner5b183d82006-11-10 05:03:26 +00001589 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smithc67fdd42012-03-07 08:35:16 +00001590 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1591 Kind, Literal.Pascal, StrTy,
1592 &StringTokLocs[0],
1593 StringTokLocs.size());
1594 if (Literal.getUDSuffix().empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001595 return Lit;
Richard Smithc67fdd42012-03-07 08:35:16 +00001596
1597 // We're building a user-defined literal.
1598 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smith75b67d62012-03-08 01:34:56 +00001599 SourceLocation UDSuffixLoc =
1600 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1601 Literal.getUDSuffixOffset());
Richard Smithc67fdd42012-03-07 08:35:16 +00001602
Richard Smithbcc22fc2012-03-09 08:00:36 +00001603 // Make sure we're allowed user-defined literals here.
1604 if (!UDLScope)
1605 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1606
Richard Smithc67fdd42012-03-07 08:35:16 +00001607 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1608 // operator "" X (str, len)
1609 QualType SizeType = Context.getSizeType();
Richard Smithb8b41d32013-10-07 19:57:58 +00001610
1611 DeclarationName OpName =
1612 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1613 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1614 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1615
1616 QualType ArgTy[] = {
1617 Context.getArrayDecayedType(StrTy), SizeType
1618 };
1619
1620 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1621 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1622 /*AllowRaw*/false, /*AllowTemplate*/false,
1623 /*AllowStringTemplate*/true)) {
1624
1625 case LOLR_Cooked: {
1626 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1627 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1628 StringTokLocs[0]);
1629 Expr *Args[] = { Lit, LenArg };
1630
1631 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1632 }
1633
1634 case LOLR_StringTemplate: {
1635 TemplateArgumentListInfo ExplicitArgs;
1636
1637 unsigned CharBits = Context.getIntWidth(CharTy);
1638 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1639 llvm::APSInt Value(CharBits, CharIsUnsigned);
1640
1641 TemplateArgument TypeArg(CharTy);
1642 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1643 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1644
1645 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1646 Value = Lit->getCodeUnit(I);
1647 TemplateArgument Arg(Context, Value, CharTy);
1648 TemplateArgumentLocInfo ArgInfo;
1649 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1650 }
1651 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1652 &ExplicitArgs);
1653 }
1654 case LOLR_Raw:
1655 case LOLR_Template:
1656 llvm_unreachable("unexpected literal operator lookup result");
1657 case LOLR_Error:
1658 return ExprError();
1659 }
1660 llvm_unreachable("unexpected literal operator lookup result");
Chris Lattner5b183d82006-11-10 05:03:26 +00001661}
1662
John McCalldadc5752010-08-24 06:29:42 +00001663ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001664Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001665 SourceLocation Loc,
1666 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001667 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001668 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001669}
1670
John McCallf4cd4f92011-02-09 01:13:10 +00001671/// BuildDeclRefExpr - Build an expression that references a
1672/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001673ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001674Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001675 const DeclarationNameInfo &NameInfo,
Larisse Voufo39a1e502013-08-06 01:03:05 +00001676 const CXXScopeSpec *SS, NamedDecl *FoundD,
1677 const TemplateArgumentListInfo *TemplateArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001678 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00001679 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1680 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
Jacques Pienaar5bdd6772014-12-16 20:12:38 +00001681 if (CheckCUDATarget(Caller, Callee)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00001682 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
Jacques Pienaar5bdd6772014-12-16 20:12:38 +00001683 << IdentifyCUDATarget(Callee) << D->getIdentifier()
1684 << IdentifyCUDATarget(Caller);
Peter Collingbourne7277fe82011-10-02 23:49:40 +00001685 Diag(D->getLocation(), diag::note_previous_decl)
1686 << D->getIdentifier();
1687 return ExprError();
1688 }
1689 }
1690
Alexey Bataev07649fb2014-12-16 08:01:48 +00001691 bool RefersToCapturedVariable =
Alexey Bataevf841bd92014-12-16 07:00:22 +00001692 isa<VarDecl>(D) &&
1693 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
John McCall113bee02012-03-10 09:33:50 +00001694
Larisse Voufo39a1e502013-08-06 01:03:05 +00001695 DeclRefExpr *E;
1696 if (isa<VarTemplateSpecializationDecl>(D)) {
1697 VarTemplateSpecializationDecl *VarSpec =
1698 cast<VarTemplateSpecializationDecl>(D);
1699
Alexey Bataev19acc3d2015-01-12 10:17:46 +00001700 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1701 : NestedNameSpecifierLoc(),
1702 VarSpec->getTemplateKeywordLoc(), D,
1703 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1704 FoundD, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001705 } else {
1706 assert(!TemplateArgs && "No template arguments for non-variable"
Alp Tokerf6a24ce2013-12-05 16:25:25 +00001707 " template specialization references");
Alexey Bataev07649fb2014-12-16 08:01:48 +00001708 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1709 : NestedNameSpecifierLoc(),
1710 SourceLocation(), D, RefersToCapturedVariable,
1711 NameInfo, Ty, VK, FoundD);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001712 }
Mike Stump11289f42009-09-09 15:08:12 +00001713
Eli Friedmanfa0df832012-02-02 03:46:19 +00001714 MarkDeclRefReferenced(E);
John McCall086a4642010-11-24 05:12:34 +00001715
John McCall460ce582015-10-22 18:38:17 +00001716 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001717 Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1718 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
Fariborz Jahanian6f829e32013-05-21 21:20:26 +00001719 recordUseOfEvaluatedWeak(E);
Jordan Rose657b5f42012-09-28 22:21:35 +00001720
John McCall086a4642010-11-24 05:12:34 +00001721 // Just in case we're building an illegal pointer-to-member.
Richard Smithcaf33902011-10-10 18:28:20 +00001722 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1723 if (FD && FD->isBitField())
John McCall086a4642010-11-24 05:12:34 +00001724 E->setObjectKind(OK_BitField);
1725
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001726 return E;
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001727}
1728
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001729/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001730/// possibly a list of template arguments.
1731///
1732/// If this produces template arguments, it is permitted to call
1733/// DecomposeTemplateName.
1734///
1735/// This actually loses a lot of source location information for
1736/// non-standard name kinds; we should consider preserving that in
1737/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001738void
1739Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1740 TemplateArgumentListInfo &Buffer,
1741 DeclarationNameInfo &NameInfo,
1742 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001743 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1744 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1745 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1746
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001747 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
John McCall10eae182009-11-30 22:42:35 +00001748 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001749 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001750
John McCall3e56fd42010-08-23 07:28:44 +00001751 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001752 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001753 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001754 TemplateArgs = &Buffer;
1755 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001756 NameInfo = GetNameFromUnqualifiedId(Id);
Craig Topperc3ec1492014-05-26 06:22:03 +00001757 TemplateArgs = nullptr;
John McCall10eae182009-11-30 22:42:35 +00001758 }
1759}
1760
Kaelyn Takatab16e6322014-11-20 22:06:40 +00001761static void emitEmptyLookupTypoDiagnostic(
1762 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1763 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1764 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1765 DeclContext *Ctx =
1766 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1767 if (!TC) {
1768 // Emit a special diagnostic for failed member lookups.
1769 // FIXME: computing the declaration context might fail here (?)
1770 if (Ctx)
1771 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1772 << SS.getRange();
1773 else
1774 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1775 return;
1776 }
1777
1778 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1779 bool DroppedSpecifier =
1780 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1781 unsigned NoteID =
1782 (TC.getCorrectionDecl() && isa<ImplicitParamDecl>(TC.getCorrectionDecl()))
1783 ? diag::note_implicit_param_decl
1784 : diag::note_previous_decl;
1785 if (!Ctx)
1786 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1787 SemaRef.PDiag(NoteID));
1788 else
1789 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1790 << Typo << Ctx << DroppedSpecifier
1791 << SS.getRange(),
1792 SemaRef.PDiag(NoteID));
1793}
1794
John McCalld681c392009-12-16 08:11:27 +00001795/// Diagnose an empty lookup.
1796///
1797/// \return false if new lookup candidates were found
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001798bool
1799Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1800 std::unique_ptr<CorrectionCandidateCallback> CCC,
1801 TemplateArgumentListInfo *ExplicitTemplateArgs,
Kaelyn Takatab16e6322014-11-20 22:06:40 +00001802 ArrayRef<Expr *> Args, TypoExpr **Out) {
John McCalld681c392009-12-16 08:11:27 +00001803 DeclarationName Name = R.getLookupName();
1804
John McCalld681c392009-12-16 08:11:27 +00001805 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001806 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001807 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1808 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001809 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001810 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001811 diagnostic_suggest = diag::err_undeclared_use_suggest;
1812 }
John McCalld681c392009-12-16 08:11:27 +00001813
Douglas Gregor598b08f2009-12-31 05:20:13 +00001814 // If the original lookup was an unqualified lookup, fake an
1815 // unqualified lookup. This is useful when (for example) the
1816 // original lookup would not have found something because it was a
1817 // dependent name.
Richard Smith42fd9ef2015-10-05 20:05:21 +00001818 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
Francois Pichetde232cb2011-11-25 01:10:54 +00001819 while (DC) {
John McCalld681c392009-12-16 08:11:27 +00001820 if (isa<CXXRecordDecl>(DC)) {
1821 LookupQualifiedName(R, DC);
1822
1823 if (!R.empty()) {
1824 // Don't give errors about ambiguities in this lookup.
1825 R.suppressDiagnostics();
1826
Francois Pichet857f9d62011-11-17 03:44:24 +00001827 // During a default argument instantiation the CurContext points
1828 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1829 // function parameter list, hence add an explicit check.
1830 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1831 ActiveTemplateInstantiations.back().Kind ==
1832 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCalld681c392009-12-16 08:11:27 +00001833 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1834 bool isInstance = CurMethod &&
1835 CurMethod->isInstance() &&
Francois Pichet857f9d62011-11-17 03:44:24 +00001836 DC == CurMethod->getParent() && !isDefaultArgument;
John McCalld681c392009-12-16 08:11:27 +00001837
1838 // Give a code modification hint to insert 'this->'.
1839 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1840 // Actually quite difficult!
Alp Tokerbfa39342014-01-14 12:51:41 +00001841 if (getLangOpts().MSVCCompat)
Reid Kleckner10ca24c2014-06-11 00:01:28 +00001842 diagnostic = diag::ext_found_via_dependent_bases_lookup;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001843 if (isInstance) {
Nico Weber3c10fb12012-06-22 16:39:39 +00001844 Diag(R.getNameLoc(), diagnostic) << Name
1845 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
Nico Weber3c10fb12012-06-22 16:39:39 +00001846 CheckCXXThisCapture(R.getNameLoc());
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001847 } else {
John McCalld681c392009-12-16 08:11:27 +00001848 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001849 }
John McCalld681c392009-12-16 08:11:27 +00001850
1851 // Do we really want to note all of these?
1852 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1853 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1854
Francois Pichet857f9d62011-11-17 03:44:24 +00001855 // Return true if we are inside a default argument instantiation
1856 // and the found name refers to an instance member function, otherwise
1857 // the function calling DiagnoseEmptyLookup will try to create an
1858 // implicit member call and this is wrong for default argument.
1859 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1860 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1861 return true;
1862 }
1863
John McCalld681c392009-12-16 08:11:27 +00001864 // Tell the callee to try to recover.
1865 return false;
1866 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001867
1868 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001869 }
Francois Pichetde232cb2011-11-25 01:10:54 +00001870
1871 // In Microsoft mode, if we are performing lookup from within a friend
1872 // function definition declared at class scope then we must set
1873 // DC to the lexical parent to be able to search into the parent
1874 // class.
Alp Tokerbfa39342014-01-14 12:51:41 +00001875 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
Francois Pichetde232cb2011-11-25 01:10:54 +00001876 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1877 DC->getLexicalParent()->isRecord())
1878 DC = DC->getLexicalParent();
1879 else
1880 DC = DC->getParent();
John McCalld681c392009-12-16 08:11:27 +00001881 }
1882
Douglas Gregor598b08f2009-12-31 05:20:13 +00001883 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001884 TypoCorrection Corrected;
Kaelyn Takatab16e6322014-11-20 22:06:40 +00001885 if (S && Out) {
1886 SourceLocation TypoLoc = R.getNameLoc();
1887 assert(!ExplicitTemplateArgs &&
1888 "Diagnosing an empty lookup with explicit template args!");
1889 *Out = CorrectTypoDelayed(
1890 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1891 [=](const TypoCorrection &TC) {
1892 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1893 diagnostic, diagnostic_suggest);
1894 },
1895 nullptr, CTK_ErrorRecovery);
1896 if (*Out)
1897 return true;
1898 } else if (S && (Corrected =
1899 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1900 &SS, std::move(CCC), CTK_ErrorRecovery))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001901 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
Richard Smithf9b15102013-08-17 00:46:16 +00001902 bool DroppedSpecifier =
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00001903 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001904 R.setLookupName(Corrected.getCorrection());
1905
Richard Smithf9b15102013-08-17 00:46:16 +00001906 bool AcceptableWithRecovery = false;
1907 bool AcceptableWithoutRecovery = false;
1908 NamedDecl *ND = Corrected.getCorrectionDecl();
1909 if (ND) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001910 if (Corrected.isOverloaded()) {
Richard Smith100b24a2014-04-17 01:52:14 +00001911 OverloadCandidateSet OCS(R.getNameLoc(),
1912 OverloadCandidateSet::CSK_Normal);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001913 OverloadCandidateSet::iterator Best;
1914 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1915 CDEnd = Corrected.end();
1916 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001917 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001918 dyn_cast<FunctionTemplateDecl>(*CD))
1919 AddTemplateOverloadCandidate(
1920 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001921 Args, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001922 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1923 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1924 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001925 Args, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001926 }
1927 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001928 case OR_Success:
1929 ND = Best->Function;
1930 Corrected.setCorrectionDecl(ND);
1931 break;
1932 default:
1933 // FIXME: Arbitrarily pick the first declaration for the note.
1934 Corrected.setCorrectionDecl(ND);
1935 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001936 }
1937 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001938 R.addDecl(ND);
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00001939 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1940 CXXRecordDecl *Record = nullptr;
1941 if (Corrected.getCorrectionSpecifier()) {
1942 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1943 Record = Ty->getAsCXXRecordDecl();
1944 }
1945 if (!Record)
1946 Record = cast<CXXRecordDecl>(
1947 ND->getDeclContext()->getRedeclContext());
1948 R.setNamingClass(Record);
1949 }
Ted Kremenekc6ebda12013-02-21 21:40:44 +00001950
Richard Smithf9b15102013-08-17 00:46:16 +00001951 AcceptableWithRecovery =
1952 isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
1953 // FIXME: If we ended up with a typo for a type name or
1954 // Objective-C class name, we're in trouble because the parser
1955 // is in the wrong place to recover. Suggest the typo
1956 // correction, but don't make it a fix-it since we're not going
1957 // to recover well anyway.
1958 AcceptableWithoutRecovery =
1959 isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001960 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001961 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001962 // because we aren't able to recover.
Richard Smithf9b15102013-08-17 00:46:16 +00001963 AcceptableWithoutRecovery = true;
1964 }
1965
1966 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1967 unsigned NoteID = (Corrected.getCorrectionDecl() &&
1968 isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
1969 ? diag::note_implicit_param_decl
1970 : diag::note_previous_decl;
Douglas Gregor25363982010-01-01 00:15:04 +00001971 if (SS.isEmpty())
Richard Smithf9b15102013-08-17 00:46:16 +00001972 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1973 PDiag(NoteID), AcceptableWithRecovery);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001974 else
Richard Smithf9b15102013-08-17 00:46:16 +00001975 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1976 << Name << computeDeclContext(SS, false)
1977 << DroppedSpecifier << SS.getRange(),
1978 PDiag(NoteID), AcceptableWithRecovery);
1979
1980 // Tell the callee whether to try to recover.
1981 return !AcceptableWithRecovery;
Douglas Gregor25363982010-01-01 00:15:04 +00001982 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001983 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001984 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001985
1986 // Emit a special diagnostic for failed member lookups.
1987 // FIXME: computing the declaration context might fail here (?)
1988 if (!SS.isEmpty()) {
1989 Diag(R.getNameLoc(), diag::err_no_member)
1990 << Name << computeDeclContext(SS, false)
1991 << SS.getRange();
1992 return true;
1993 }
1994
John McCalld681c392009-12-16 08:11:27 +00001995 // Give up, we can't recover.
1996 Diag(R.getNameLoc(), diagnostic) << Name;
1997 return true;
1998}
1999
Reid Kleckner10ca24c2014-06-11 00:01:28 +00002000/// In Microsoft mode, if we are inside a template class whose parent class has
2001/// dependent base classes, and we can't resolve an unqualified identifier, then
2002/// assume the identifier is a member of a dependent base class. We can only
2003/// recover successfully in static methods, instance methods, and other contexts
2004/// where 'this' is available. This doesn't precisely match MSVC's
2005/// instantiation model, but it's close enough.
2006static Expr *
2007recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2008 DeclarationNameInfo &NameInfo,
2009 SourceLocation TemplateKWLoc,
2010 const TemplateArgumentListInfo *TemplateArgs) {
2011 // Only try to recover from lookup into dependent bases in static methods or
2012 // contexts where 'this' is available.
2013 QualType ThisType = S.getCurrentThisType();
2014 const CXXRecordDecl *RD = nullptr;
2015 if (!ThisType.isNull())
2016 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2017 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2018 RD = MD->getParent();
2019 if (!RD || !RD->hasAnyDependentBases())
2020 return nullptr;
2021
2022 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2023 // is available, suggest inserting 'this->' as a fixit.
2024 SourceLocation Loc = NameInfo.getLoc();
Reid Kleckner13a97992014-06-11 21:57:15 +00002025 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2026 DB << NameInfo.getName() << RD;
Reid Kleckner10ca24c2014-06-11 00:01:28 +00002027
2028 if (!ThisType.isNull()) {
2029 DB << FixItHint::CreateInsertion(Loc, "this->");
2030 return CXXDependentScopeMemberExpr::Create(
2031 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2032 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2033 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2034 }
2035
2036 // Synthesize a fake NNS that points to the derived class. This will
2037 // perform name lookup during template instantiation.
2038 CXXScopeSpec SS;
2039 auto *NNS =
2040 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2041 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2042 return DependentScopeDeclRefExpr::Create(
2043 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2044 TemplateArgs);
2045}
2046
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002047ExprResult
2048Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2049 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2050 bool HasTrailingLParen, bool IsAddressOfOperand,
2051 std::unique_ptr<CorrectionCandidateCallback> CCC,
Kaelyn Takatab16e6322014-11-20 22:06:40 +00002052 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002053 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCalle66edc12009-11-24 19:00:30 +00002054 "cannot be direct & operand and have a trailing lparen");
John McCalle66edc12009-11-24 19:00:30 +00002055 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00002056 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00002057
John McCall10eae182009-11-30 22:42:35 +00002058 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00002059
2060 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002061 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00002062 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00002063 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00002064
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002065 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00002066 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002067 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002068
John McCalle66edc12009-11-24 19:00:30 +00002069 // C++ [temp.dep.expr]p3:
2070 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00002071 // -- an identifier that was declared with a dependent type,
2072 // (note: handled after lookup)
2073 // -- a template-id that is dependent,
2074 // (note: handled in BuildTemplateIdExpr)
2075 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00002076 // -- a nested-name-specifier that contains a class-name that
2077 // names a dependent type.
2078 // Determine whether this is a member of an unknown specialization;
2079 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00002080 bool DependentID = false;
2081 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2082 Name.getCXXNameType()->isDependentType()) {
2083 DependentID = true;
2084 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002085 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00002086 if (RequireCompleteDeclContext(SS, DC))
2087 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00002088 } else {
2089 DependentID = true;
2090 }
2091 }
2092
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002093 if (DependentID)
Abramo Bagnara7945c982012-01-27 09:46:47 +00002094 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2095 IsAddressOfOperand, TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002096
John McCalle66edc12009-11-24 19:00:30 +00002097 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00002098 LookupResult R(*this, NameInfo,
2099 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2100 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00002101 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00002102 // Lookup the template name again to correctly establish the context in
2103 // which it was found. This is really unfortunate as we already did the
2104 // lookup to determine that it was a template name in the first place. If
2105 // this becomes a performance hit, we can work harder to preserve those
2106 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00002107 bool MemberOfUnknownSpecialization;
2108 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2109 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00002110
2111 if (MemberOfUnknownSpecialization ||
2112 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnara7945c982012-01-27 09:46:47 +00002113 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2114 IsAddressOfOperand, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00002115 } else {
Benjamin Kramer46921442012-01-20 14:57:34 +00002116 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002117 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00002118
Douglas Gregora5226932011-02-04 13:35:07 +00002119 // If the result might be in a dependent base class, this is a dependent
2120 // id-expression.
2121 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnara7945c982012-01-27 09:46:47 +00002122 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2123 IsAddressOfOperand, TemplateArgs);
2124
John McCalle66edc12009-11-24 19:00:30 +00002125 // If this reference is in an Objective-C method, then we need to do
2126 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002127 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00002128 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00002129 if (E.isInvalid())
2130 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002131
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002132 if (Expr *Ex = E.getAs<Expr>())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002133 return Ex;
Steve Naroffebf4cb42008-06-02 23:03:37 +00002134 }
Chris Lattner59a25942008-03-31 00:36:02 +00002135 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00002136
John McCalle66edc12009-11-24 19:00:30 +00002137 if (R.isAmbiguous())
2138 return ExprError();
2139
Reid Kleckner59148b32014-06-09 23:16:24 +00002140 // This could be an implicitly declared function reference (legal in C90,
2141 // extension in C99, forbidden in C++).
2142 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2143 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2144 if (D) R.addDecl(D);
2145 }
2146
Douglas Gregor171c45a2009-02-18 21:56:37 +00002147 // Determine whether this name might be a candidate for
2148 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00002149 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00002150
John McCalle66edc12009-11-24 19:00:30 +00002151 if (R.empty() && !ADL) {
Reid Kleckner59148b32014-06-09 23:16:24 +00002152 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
Reid Kleckner10ca24c2014-06-11 00:01:28 +00002153 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2154 TemplateKWLoc, TemplateArgs))
2155 return E;
John McCalle66edc12009-11-24 19:00:30 +00002156 }
2157
Nikola Smiljanic1c125682014-07-09 05:42:35 +00002158 // Don't diagnose an empty lookup for inline assembly.
Reid Kleckner59148b32014-06-09 23:16:24 +00002159 if (IsInlineAsmIdentifier)
2160 return ExprError();
2161
John McCalle66edc12009-11-24 19:00:30 +00002162 // If this name wasn't predeclared and if this is not a function
2163 // call, diagnose the problem.
Kaelyn Takatab16e6322014-11-20 22:06:40 +00002164 TypoExpr *TE = nullptr;
2165 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2166 II, SS.isValid() ? SS.getScopeRep() : nullptr);
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002167 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00002168 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2169 "Typo correction callback misconfigured");
Kaelyn Takatab16e6322014-11-20 22:06:40 +00002170 if (CCC) {
2171 // Make sure the callback knows what the typo being diagnosed is.
2172 CCC->setTypoName(II);
2173 if (SS.isValid())
2174 CCC->setTypoNNS(SS.getScopeRep());
2175 }
Kaelyn Takata15867822014-11-21 18:48:04 +00002176 if (DiagnoseEmptyLookup(S, SS, R,
2177 CCC ? std::move(CCC) : std::move(DefaultValidator),
2178 nullptr, None, &TE)) {
Kaelyn Takatab16e6322014-11-20 22:06:40 +00002179 if (TE && KeywordReplacement) {
2180 auto &State = getTypoExprState(TE);
2181 auto BestTC = State.Consumer->getNextCorrection();
2182 if (BestTC.isKeyword()) {
2183 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2184 if (State.DiagHandler)
2185 State.DiagHandler(BestTC);
2186 KeywordReplacement->startToken();
2187 KeywordReplacement->setKind(II->getTokenID());
2188 KeywordReplacement->setIdentifierInfo(II);
2189 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2190 // Clean up the state associated with the TypoExpr, since it has
2191 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2192 clearDelayedTypo(TE);
2193 // Signal that a correction to a keyword was performed by returning a
2194 // valid-but-null ExprResult.
2195 return (Expr*)nullptr;
2196 }
2197 State.Consumer->resetCorrectionStream();
2198 }
2199 return TE ? TE : ExprError();
2200 }
Francois Pichetd8e4e412011-09-24 10:38:05 +00002201
Reid Kleckner59148b32014-06-09 23:16:24 +00002202 assert(!R.empty() &&
2203 "DiagnoseEmptyLookup returned false but added no results");
2204
2205 // If we found an Objective-C instance variable, let
2206 // LookupInObjCMethod build the appropriate expression to
2207 // reference the ivar.
2208 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2209 R.clear();
2210 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2211 // In a hopelessly buggy code, Objective-C instance variable
2212 // lookup fails and no expression will be built to reference it.
2213 if (!E.isInvalid() && !E.get())
Chad Rosierb9aff1e2013-05-24 18:32:55 +00002214 return ExprError();
Reid Kleckner59148b32014-06-09 23:16:24 +00002215 return E;
Steve Naroff92e30f82007-04-02 22:35:25 +00002216 }
Chris Lattner17ed4872006-11-20 04:58:19 +00002217 }
Mike Stump11289f42009-09-09 15:08:12 +00002218
John McCalle66edc12009-11-24 19:00:30 +00002219 // This is guaranteed from this point on.
2220 assert(!R.empty() || ADL);
2221
John McCall2d74de92009-12-01 22:10:20 +00002222 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00002223 // C++ [class.mfct.non-static]p3:
2224 // When an id-expression that is not part of a class member access
2225 // syntax and not used to form a pointer to member is used in the
2226 // body of a non-static member function of class X, if name lookup
2227 // resolves the name in the id-expression to a non-static non-type
2228 // member of some class C, the id-expression is transformed into a
2229 // class member access expression using (*this) as the
2230 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00002231 //
2232 // But we don't actually need to do this for '&' operands if R
2233 // resolved to a function or overloaded function set, because the
2234 // expression is ill-formed if it actually works out to be a
2235 // non-static member function:
2236 //
2237 // C++ [expr.ref]p4:
2238 // Otherwise, if E1.E2 refers to a non-static member function. . .
2239 // [t]he expression can be used only as the left-hand operand of a
2240 // member function call.
2241 //
2242 // There are other safeguards against such uses, but it's important
2243 // to get this right here so that we don't end up making a
2244 // spuriously dependent expression if we're inside a dependent
2245 // instance method.
John McCall57500772009-12-16 12:17:52 +00002246 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00002247 bool MightBeImplicitMember;
Richard Trieuba63ce62011-09-09 01:45:06 +00002248 if (!IsAddressOfOperand)
John McCall8d08b9b2010-08-27 09:08:28 +00002249 MightBeImplicitMember = true;
2250 else if (!SS.isEmpty())
2251 MightBeImplicitMember = false;
2252 else if (R.isOverloadedResult())
2253 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00002254 else if (R.isUnresolvableResult())
2255 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00002256 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00002257 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
Reid Kleckner0a0c8892013-06-19 16:37:23 +00002258 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2259 isa<MSPropertyDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00002260
2261 if (MightBeImplicitMember)
Abramo Bagnara7945c982012-01-27 09:46:47 +00002262 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00002263 R, TemplateArgs, S);
John McCallb53bbd42009-11-22 01:44:31 +00002264 }
2265
Larisse Voufo39a1e502013-08-06 01:03:05 +00002266 if (TemplateArgs || TemplateKWLoc.isValid()) {
2267
2268 // In C++1y, if this is a variable template id, then check it
2269 // in BuildTemplateIdExpr().
2270 // The single lookup result must be a variable template declaration.
2271 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2272 Id.TemplateId->Kind == TNK_Var_template) {
2273 assert(R.getAsSingle<VarTemplateDecl>() &&
2274 "There should only be one declaration found.");
2275 }
2276
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002277 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002278 }
John McCallb53bbd42009-11-22 01:44:31 +00002279
John McCalle66edc12009-11-24 19:00:30 +00002280 return BuildDeclarationNameExpr(SS, R, ADL);
2281}
2282
John McCall10eae182009-11-30 22:42:35 +00002283/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2284/// declaration name, generally during template instantiation.
2285/// There's a large number of things which don't need to be done along
2286/// this path.
Aaron Ballman6924dcd2015-09-01 14:49:24 +00002287ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2288 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2289 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
Richard Smith40c180d2012-10-23 19:56:01 +00002290 DeclContext *DC = computeDeclContext(SS, false);
2291 if (!DC)
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002292 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002293 NameInfo, /*TemplateArgs=*/nullptr);
John McCalle66edc12009-11-24 19:00:30 +00002294
John McCall0b66eb32010-05-01 00:40:08 +00002295 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00002296 return ExprError();
2297
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002298 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00002299 LookupQualifiedName(R, DC);
2300
2301 if (R.isAmbiguous())
2302 return ExprError();
2303
Richard Smith40c180d2012-10-23 19:56:01 +00002304 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2305 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002306 NameInfo, /*TemplateArgs=*/nullptr);
Richard Smith40c180d2012-10-23 19:56:01 +00002307
John McCalle66edc12009-11-24 19:00:30 +00002308 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002309 Diag(NameInfo.getLoc(), diag::err_no_member)
2310 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002311 return ExprError();
2312 }
2313
Reid Kleckner32506ed2014-06-12 23:03:48 +00002314 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2315 // Diagnose a missing typename if this resolved unambiguously to a type in
2316 // a dependent context. If we can recover with a type, downgrade this to
2317 // a warning in Microsoft compatibility mode.
2318 unsigned DiagID = diag::err_typename_missing;
2319 if (RecoveryTSI && getLangOpts().MSVCCompat)
2320 DiagID = diag::ext_typename_missing;
2321 SourceLocation Loc = SS.getBeginLoc();
2322 auto D = Diag(Loc, DiagID);
2323 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2324 << SourceRange(Loc, NameInfo.getEndLoc());
2325
2326 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2327 // context.
2328 if (!RecoveryTSI)
2329 return ExprError();
2330
2331 // Only issue the fixit if we're prepared to recover.
2332 D << FixItHint::CreateInsertion(Loc, "typename ");
2333
2334 // Recover by pretending this was an elaborated type.
2335 QualType Ty = Context.getTypeDeclType(TD);
2336 TypeLocBuilder TLB;
2337 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2338
2339 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2340 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2341 QTL.setElaboratedKeywordLoc(SourceLocation());
2342 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2343
2344 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2345
2346 return ExprEmpty();
Reid Kleckner377c1592014-06-10 23:29:48 +00002347 }
2348
Richard Smithdb2630f2012-10-21 03:28:35 +00002349 // Defend against this resolving to an implicit member access. We usually
2350 // won't get here if this might be a legitimate a class member (we end up in
2351 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2352 // a pointer-to-member or in an unevaluated context in C++11.
2353 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2354 return BuildPossibleImplicitMemberExpr(SS,
2355 /*TemplateKWLoc=*/SourceLocation(),
Aaron Ballman6924dcd2015-09-01 14:49:24 +00002356 R, /*TemplateArgs=*/nullptr, S);
Richard Smithdb2630f2012-10-21 03:28:35 +00002357
2358 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
John McCalle66edc12009-11-24 19:00:30 +00002359}
2360
2361/// LookupInObjCMethod - The parser has read a name in, and Sema has
2362/// detected that we're currently inside an ObjC method. Perform some
2363/// additional lookup.
2364///
2365/// Ideally, most of this would be done by lookup, but there's
2366/// actually quite a lot of extra work involved.
2367///
2368/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00002369ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002370Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00002371 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00002372 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00002373 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Fariborz Jahanian223ca5c2013-02-18 17:22:23 +00002374
2375 // Check for error condition which is already reported.
2376 if (!CurMethod)
2377 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002378
John McCalle66edc12009-11-24 19:00:30 +00002379 // There are two cases to handle here. 1) scoped lookup could have failed,
2380 // in which case we should look for an ivar. 2) scoped lookup could have
2381 // found a decl, but that decl is outside the current instance method (i.e.
2382 // a global variable). In these two cases, we do a lookup for an ivar with
2383 // this name, if the lookup sucedes, we replace it our current decl.
2384
2385 // If we're in a class method, we don't normally want to look for
2386 // ivars. But if we don't find anything else, and there's an
2387 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00002388 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00002389
2390 bool LookForIvars;
2391 if (Lookup.empty())
2392 LookForIvars = true;
2393 else if (IsClassMethod)
2394 LookForIvars = false;
2395 else
2396 LookForIvars = (Lookup.isSingleResult() &&
2397 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Craig Topperc3ec1492014-05-26 06:22:03 +00002398 ObjCInterfaceDecl *IFace = nullptr;
John McCalle66edc12009-11-24 19:00:30 +00002399 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00002400 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00002401 ObjCInterfaceDecl *ClassDeclared;
Craig Topperc3ec1492014-05-26 06:22:03 +00002402 ObjCIvarDecl *IV = nullptr;
Argyrios Kyrtzidis4e8b1362011-10-19 02:25:16 +00002403 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCalle66edc12009-11-24 19:00:30 +00002404 // Diagnose using an ivar in a class method.
2405 if (IsClassMethod)
2406 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2407 << IV->getDeclName());
2408
2409 // If we're referencing an invalid decl, just return this as a silent
2410 // error node. The error diagnostic was already emitted on the decl.
2411 if (IV->isInvalidDecl())
2412 return ExprError();
2413
2414 // Check if referencing a field with __attribute__((deprecated)).
2415 if (DiagnoseUseOfDecl(IV, Loc))
2416 return ExprError();
2417
2418 // Diagnose the use of an ivar outside of the declaring class.
2419 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00002420 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002421 !getLangOpts().DebuggerSupport)
John McCalle66edc12009-11-24 19:00:30 +00002422 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2423
2424 // FIXME: This should use a new expr for a direct reference, don't
2425 // turn this into Self->ivar, just return a BareIVarExpr or something.
2426 IdentifierInfo &II = Context.Idents.get("self");
2427 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002428 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00002429 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00002430 CXXScopeSpec SelfScopeSpec;
Abramo Bagnara7945c982012-01-27 09:46:47 +00002431 SourceLocation TemplateKWLoc;
2432 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00002433 SelfName, false, false);
2434 if (SelfExpr.isInvalid())
2435 return ExprError();
2436
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002437 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00002438 if (SelfExpr.isInvalid())
2439 return ExprError();
John McCall27584242010-12-06 20:48:59 +00002440
Nick Lewycky45b50522013-02-02 00:25:55 +00002441 MarkAnyDeclReferenced(Loc, IV, true);
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00002442
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00002443 ObjCMethodFamily MF = CurMethod->getMethodFamily();
Fariborz Jahaniana934a022013-02-14 19:07:19 +00002444 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2445 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00002446 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
Jordan Rose657b5f42012-09-28 22:21:35 +00002447
Nico Weber21ad7e52014-07-27 04:09:29 +00002448 ObjCIvarRefExpr *Result = new (Context)
Douglas Gregore83b9562015-07-07 03:57:53 +00002449 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2450 IV->getLocation(), SelfExpr.get(), true, true);
Jordan Rose657b5f42012-09-28 22:21:35 +00002451
2452 if (getLangOpts().ObjCAutoRefCount) {
2453 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002454 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Fariborz Jahanian6f829e32013-05-21 21:20:26 +00002455 recordUseOfEvaluatedWeak(Result);
Jordan Rose657b5f42012-09-28 22:21:35 +00002456 }
Fariborz Jahanian4a675082012-10-03 17:55:29 +00002457 if (CurContext->isClosure())
2458 Diag(Loc, diag::warn_implicitly_retains_self)
2459 << FixItHint::CreateInsertion(Loc, "self->");
Jordan Rose657b5f42012-09-28 22:21:35 +00002460 }
2461
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002462 return Result;
John McCalle66edc12009-11-24 19:00:30 +00002463 }
Chris Lattner87313662010-04-12 05:10:17 +00002464 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00002465 // We should warn if a local variable hides an ivar.
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00002466 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2467 ObjCInterfaceDecl *ClassDeclared;
2468 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2469 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor0b144e12011-12-15 00:29:59 +00002470 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00002471 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2472 }
John McCalle66edc12009-11-24 19:00:30 +00002473 }
Fariborz Jahanian028b9e12011-12-20 22:21:08 +00002474 } else if (Lookup.isSingleResult() &&
2475 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2476 // If accessing a stand-alone ivar in a class method, this is an error.
2477 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2478 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2479 << IV->getDeclName());
John McCalle66edc12009-11-24 19:00:30 +00002480 }
2481
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002482 if (Lookup.empty() && II && AllowBuiltinCreation) {
2483 // FIXME. Consolidate this with similar code in LookupName.
2484 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002485 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002486 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2487 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2488 S, Lookup.isForRedeclaration(),
2489 Lookup.getNameLoc());
2490 if (D) Lookup.addDecl(D);
2491 }
2492 }
2493 }
John McCalle66edc12009-11-24 19:00:30 +00002494 // Sentinel value saying that we didn't do anything special.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002495 return ExprResult((Expr *)nullptr);
Douglas Gregor3256d042009-06-30 15:47:41 +00002496}
John McCalld14a8642009-11-21 08:51:07 +00002497
John McCall16df1e52010-03-30 21:47:33 +00002498/// \brief Cast a base object to a member's actual type.
2499///
2500/// Logically this happens in three phases:
2501///
2502/// * First we cast from the base type to the naming class.
2503/// The naming class is the class into which we were looking
2504/// when we found the member; it's the qualifier type if a
2505/// qualifier was provided, and otherwise it's the base type.
2506///
2507/// * Next we cast from the naming class to the declaring class.
2508/// If the member we found was brought into a class's scope by
2509/// a using declaration, this is that class; otherwise it's
2510/// the class declaring the member.
2511///
2512/// * Finally we cast from the declaring class to the "true"
2513/// declaring class of the member. This conversion does not
2514/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00002515ExprResult
2516Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002517 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002518 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002519 NamedDecl *Member) {
2520 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2521 if (!RD)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002522 return From;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002523
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002524 QualType DestRecordType;
2525 QualType DestType;
2526 QualType FromRecordType;
2527 QualType FromType = From->getType();
2528 bool PointerConversions = false;
2529 if (isa<FieldDecl>(Member)) {
2530 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002531
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002532 if (FromType->getAs<PointerType>()) {
2533 DestType = Context.getPointerType(DestRecordType);
2534 FromRecordType = FromType->getPointeeType();
2535 PointerConversions = true;
2536 } else {
2537 DestType = DestRecordType;
2538 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002539 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002540 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2541 if (Method->isStatic())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002542 return From;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002543
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002544 DestType = Method->getThisType(Context);
2545 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002546
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002547 if (FromType->getAs<PointerType>()) {
2548 FromRecordType = FromType->getPointeeType();
2549 PointerConversions = true;
2550 } else {
2551 FromRecordType = FromType;
2552 DestType = DestRecordType;
2553 }
2554 } else {
2555 // No conversion necessary.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002556 return From;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002557 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002558
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002559 if (DestType->isDependentType() || FromType->isDependentType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002560 return From;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002561
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002562 // If the unqualified types are the same, no conversion is necessary.
2563 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002564 return From;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002565
John McCall16df1e52010-03-30 21:47:33 +00002566 SourceRange FromRange = From->getSourceRange();
2567 SourceLocation FromLoc = FromRange.getBegin();
2568
Eli Friedmanbe4b3632011-09-27 21:58:52 +00002569 ExprValueKind VK = From->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002570
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002571 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002572 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002573 // class name.
2574 //
2575 // If the member was a qualified name and the qualified referred to a
2576 // specific base subobject type, we'll cast to that intermediate type
2577 // first and then to the object in which the member is declared. That allows
2578 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2579 //
2580 // class Base { public: int x; };
2581 // class Derived1 : public Base { };
2582 // class Derived2 : public Base { };
2583 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2584 //
2585 // void VeryDerived::f() {
2586 // x = 17; // error: ambiguous base subobjects
2587 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2588 // }
David Majnemer13657812013-08-05 04:53:41 +00002589 if (Qualifier && Qualifier->getAsType()) {
John McCall16df1e52010-03-30 21:47:33 +00002590 QualType QType = QualType(Qualifier->getAsType(), 0);
John McCall16df1e52010-03-30 21:47:33 +00002591 assert(QType->isRecordType() && "lookup done with non-record type");
2592
2593 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2594
2595 // In C++98, the qualifier type doesn't actually have to be a base
2596 // type of the object type, in which case we just ignore it.
2597 // Otherwise build the appropriate casts.
2598 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002599 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002600 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002601 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002602 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002603
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002604 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002605 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002606 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002607 VK, &BasePath).get();
John McCall16df1e52010-03-30 21:47:33 +00002608
2609 FromType = QType;
2610 FromRecordType = QRecordType;
2611
2612 // If the qualifier type was the same as the destination type,
2613 // we're done.
2614 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002615 return From;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002616 }
2617 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002618
John McCall16df1e52010-03-30 21:47:33 +00002619 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002620
John McCall16df1e52010-03-30 21:47:33 +00002621 // If we actually found the member through a using declaration, cast
2622 // down to the using declaration's type.
2623 //
2624 // Pointer equality is fine here because only one declaration of a
2625 // class ever has member declarations.
2626 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2627 assert(isa<UsingShadowDecl>(FoundDecl));
2628 QualType URecordType = Context.getTypeDeclType(
2629 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2630
2631 // We only need to do this if the naming-class to declaring-class
2632 // conversion is non-trivial.
2633 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2634 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002635 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002636 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002637 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002638 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002639
John McCall16df1e52010-03-30 21:47:33 +00002640 QualType UType = URecordType;
2641 if (PointerConversions)
2642 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002643 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002644 VK, &BasePath).get();
John McCall16df1e52010-03-30 21:47:33 +00002645 FromType = UType;
2646 FromRecordType = URecordType;
2647 }
2648
2649 // We don't do access control for the conversion from the
2650 // declaring class to the true declaring class.
2651 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002652 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002653
John McCallcf142162010-08-07 06:22:56 +00002654 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002655 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2656 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002657 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002658 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002659
John Wiegley01296292011-04-08 18:41:53 +00002660 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2661 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002662}
Douglas Gregor3256d042009-06-30 15:47:41 +00002663
John McCalle66edc12009-11-24 19:00:30 +00002664bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002665 const LookupResult &R,
2666 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002667 // Only when used directly as the postfix-expression of a call.
2668 if (!HasTrailingLParen)
2669 return false;
2670
2671 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002672 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002673 return false;
2674
2675 // Only in C++ or ObjC++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002676 if (!getLangOpts().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002677 return false;
2678
2679 // Turn off ADL when we find certain kinds of declarations during
2680 // normal lookup:
2681 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2682 NamedDecl *D = *I;
2683
2684 // C++0x [basic.lookup.argdep]p3:
2685 // -- a declaration of a class member
2686 // Since using decls preserve this property, we check this on the
2687 // original decl.
John McCall57500772009-12-16 12:17:52 +00002688 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002689 return false;
2690
2691 // C++0x [basic.lookup.argdep]p3:
2692 // -- a block-scope function declaration that is not a
2693 // using-declaration
2694 // NOTE: we also trigger this for function templates (in fact, we
2695 // don't check the decl type at all, since all other decl types
2696 // turn off ADL anyway).
2697 if (isa<UsingShadowDecl>(D))
2698 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Richard Smith541b38b2013-09-20 01:15:31 +00002699 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
John McCalld14a8642009-11-21 08:51:07 +00002700 return false;
2701
2702 // C++0x [basic.lookup.argdep]p3:
2703 // -- a declaration that is neither a function or a function
2704 // template
2705 // And also for builtin functions.
2706 if (isa<FunctionDecl>(D)) {
2707 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2708
2709 // But also builtin functions.
2710 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2711 return false;
2712 } else if (!isa<FunctionTemplateDecl>(D))
2713 return false;
2714 }
2715
2716 return true;
2717}
2718
2719
John McCalld14a8642009-11-21 08:51:07 +00002720/// Diagnoses obvious problems with the use of the given declaration
2721/// as an expression. This is only actually called for lookups that
2722/// were not overloaded, and it doesn't promise that the declaration
2723/// will in fact be used.
2724static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002725 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002726 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2727 return true;
2728 }
2729
2730 if (isa<ObjCInterfaceDecl>(D)) {
2731 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2732 return true;
2733 }
2734
2735 if (isa<NamespaceDecl>(D)) {
2736 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2737 return true;
2738 }
2739
2740 return false;
2741}
2742
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00002743ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2744 LookupResult &R, bool NeedsADL,
2745 bool AcceptInvalidDecl) {
John McCall3a60c872009-12-08 22:45:53 +00002746 // If this is a single, fully-resolved result and we don't need ADL,
2747 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002748 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Daniel Jasper689ae012013-03-22 10:01:35 +00002749 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00002750 R.getRepresentativeDecl(), nullptr,
2751 AcceptInvalidDecl);
John McCalld14a8642009-11-21 08:51:07 +00002752
2753 // We only need to check the declaration if there's exactly one
2754 // result, because in the overloaded case the results can only be
2755 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002756 if (R.isSingleResult() &&
2757 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002758 return ExprError();
2759
John McCall58cc69d2010-01-27 01:50:18 +00002760 // Otherwise, just build an unresolved lookup expression. Suppress
2761 // any lookup-related diagnostics; we'll hash these out later, when
2762 // we've picked a target.
2763 R.suppressDiagnostics();
2764
John McCalld14a8642009-11-21 08:51:07 +00002765 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002766 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002767 SS.getWithLocInContext(Context),
2768 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002769 NeedsADL, R.isOverloadedResult(),
2770 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002771
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002772 return ULE;
John McCalld14a8642009-11-21 08:51:07 +00002773}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002774
John McCalld14a8642009-11-21 08:51:07 +00002775/// \brief Complete semantic analysis for a reference to the given declaration.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002776ExprResult Sema::BuildDeclarationNameExpr(
2777 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00002778 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2779 bool AcceptInvalidDecl) {
John McCalld14a8642009-11-21 08:51:07 +00002780 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002781 assert(!isa<FunctionTemplateDecl>(D) &&
2782 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002783
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002784 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002785 if (CheckDeclInExpr(*this, Loc, D))
2786 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002787
Douglas Gregore7488b92009-12-01 16:58:18 +00002788 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2789 // Specifically diagnose references to class templates that are missing
2790 // a template argument list.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002791 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2792 << Template << SS.getRange();
Douglas Gregore7488b92009-12-01 16:58:18 +00002793 Diag(Template->getLocation(), diag::note_template_decl_here);
2794 return ExprError();
2795 }
2796
2797 // Make sure that we're referring to a value.
2798 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2799 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002800 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002801 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002802 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002803 return ExprError();
2804 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002805
Douglas Gregor171c45a2009-02-18 21:56:37 +00002806 // Check whether this declaration can be used. Note that we suppress
2807 // this check when we're going to perform argument-dependent lookup
2808 // on this function name, because this might not be the function
2809 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002810 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002811 return ExprError();
2812
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002813 // Only create DeclRefExpr's for valid Decl's.
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00002814 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002815 return ExprError();
2816
John McCallf3a88602011-02-03 08:15:49 +00002817 // Handle members of anonymous structs and unions. If we got here,
2818 // and the reference is to a class member indirect field, then this
2819 // must be the subject of a pointer-to-member expression.
2820 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2821 if (!indirectField->isCXXClassMember())
2822 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2823 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002824
Eli Friedman9bb33f52012-02-03 02:04:35 +00002825 {
John McCallf4cd4f92011-02-09 01:13:10 +00002826 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002827 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002828
2829 switch (D->getKind()) {
2830 // Ignore all the non-ValueDecl kinds.
2831#define ABSTRACT_DECL(kind)
2832#define VALUE(type, base)
2833#define DECL(type, base) \
2834 case Decl::type:
2835#include "clang/AST/DeclNodes.inc"
2836 llvm_unreachable("invalid value decl kind");
John McCallf4cd4f92011-02-09 01:13:10 +00002837
2838 // These shouldn't make it here.
2839 case Decl::ObjCAtDefsField:
2840 case Decl::ObjCIvar:
2841 llvm_unreachable("forming non-member reference to ivar?");
John McCallf4cd4f92011-02-09 01:13:10 +00002842
2843 // Enum constants are always r-values and never references.
2844 // Unresolved using declarations are dependent.
2845 case Decl::EnumConstant:
2846 case Decl::UnresolvedUsingValue:
2847 valueKind = VK_RValue;
2848 break;
2849
2850 // Fields and indirect fields that got here must be for
2851 // pointer-to-member expressions; we just call them l-values for
2852 // internal consistency, because this subexpression doesn't really
2853 // exist in the high-level semantics.
2854 case Decl::Field:
2855 case Decl::IndirectField:
David Blaikiebbafb8a2012-03-11 07:00:24 +00002856 assert(getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002857 "building reference to field in C?");
2858
2859 // These can't have reference type in well-formed programs, but
2860 // for internal consistency we do this anyway.
2861 type = type.getNonReferenceType();
2862 valueKind = VK_LValue;
2863 break;
2864
2865 // Non-type template parameters are either l-values or r-values
2866 // depending on the type.
2867 case Decl::NonTypeTemplateParm: {
2868 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2869 type = reftype->getPointeeType();
2870 valueKind = VK_LValue; // even if the parameter is an r-value reference
2871 break;
2872 }
2873
2874 // For non-references, we need to strip qualifiers just in case
2875 // the template parameter was declared as 'const int' or whatever.
2876 valueKind = VK_RValue;
2877 type = type.getUnqualifiedType();
2878 break;
2879 }
2880
2881 case Decl::Var:
Larisse Voufo39a1e502013-08-06 01:03:05 +00002882 case Decl::VarTemplateSpecialization:
2883 case Decl::VarTemplatePartialSpecialization:
John McCallf4cd4f92011-02-09 01:13:10 +00002884 // In C, "extern void blah;" is valid and is an r-value.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002885 if (!getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002886 !type.hasQualifiers() &&
2887 type->isVoidType()) {
2888 valueKind = VK_RValue;
2889 break;
2890 }
2891 // fallthrough
2892
2893 case Decl::ImplicitParam:
Douglas Gregor812d8f62012-02-18 05:51:20 +00002894 case Decl::ParmVar: {
John McCallf4cd4f92011-02-09 01:13:10 +00002895 // These are always l-values.
2896 valueKind = VK_LValue;
2897 type = type.getNonReferenceType();
Eli Friedman9bb33f52012-02-03 02:04:35 +00002898
Douglas Gregor812d8f62012-02-18 05:51:20 +00002899 // FIXME: Does the addition of const really only apply in
2900 // potentially-evaluated contexts? Since the variable isn't actually
2901 // captured in an unevaluated context, it seems that the answer is no.
David Blaikie131fcb42012-08-06 22:47:24 +00002902 if (!isUnevaluatedContext()) {
Douglas Gregor812d8f62012-02-18 05:51:20 +00002903 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2904 if (!CapturedType.isNull())
2905 type = CapturedType;
2906 }
2907
John McCallf4cd4f92011-02-09 01:13:10 +00002908 break;
Douglas Gregor812d8f62012-02-18 05:51:20 +00002909 }
2910
John McCallf4cd4f92011-02-09 01:13:10 +00002911 case Decl::Function: {
Eli Friedman34866c72012-08-31 00:14:07 +00002912 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2913 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2914 type = Context.BuiltinFnTy;
2915 valueKind = VK_RValue;
2916 break;
2917 }
2918 }
2919
John McCall2979fe02011-04-12 00:42:48 +00002920 const FunctionType *fty = type->castAs<FunctionType>();
2921
2922 // If we're referring to a function with an __unknown_anytype
2923 // result type, make the entire expression __unknown_anytype.
Alp Toker314cc812014-01-25 16:55:45 +00002924 if (fty->getReturnType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00002925 type = Context.UnknownAnyTy;
2926 valueKind = VK_RValue;
2927 break;
2928 }
2929
John McCallf4cd4f92011-02-09 01:13:10 +00002930 // Functions are l-values in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002931 if (getLangOpts().CPlusPlus) {
John McCallf4cd4f92011-02-09 01:13:10 +00002932 valueKind = VK_LValue;
2933 break;
2934 }
2935
2936 // C99 DR 316 says that, if a function type comes from a
2937 // function definition (without a prototype), that type is only
2938 // used for checking compatibility. Therefore, when referencing
2939 // the function, we pretend that we don't have the full function
2940 // type.
John McCall2979fe02011-04-12 00:42:48 +00002941 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2942 isa<FunctionProtoType>(fty))
Alp Toker314cc812014-01-25 16:55:45 +00002943 type = Context.getFunctionNoProtoType(fty->getReturnType(),
John McCall2979fe02011-04-12 00:42:48 +00002944 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002945
2946 // Functions are r-values in C.
2947 valueKind = VK_RValue;
2948 break;
2949 }
2950
John McCall5e77d762013-04-16 07:28:30 +00002951 case Decl::MSProperty:
2952 valueKind = VK_LValue;
2953 break;
2954
John McCallf4cd4f92011-02-09 01:13:10 +00002955 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002956 // If we're referring to a method with an __unknown_anytype
2957 // result type, make the entire expression __unknown_anytype.
2958 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002959 if (const FunctionProtoType *proto
2960 = dyn_cast<FunctionProtoType>(VD->getType()))
Alp Toker314cc812014-01-25 16:55:45 +00002961 if (proto->getReturnType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00002962 type = Context.UnknownAnyTy;
2963 valueKind = VK_RValue;
2964 break;
2965 }
2966
John McCallf4cd4f92011-02-09 01:13:10 +00002967 // C++ methods are l-values if static, r-values if non-static.
2968 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2969 valueKind = VK_LValue;
2970 break;
2971 }
2972 // fallthrough
2973
2974 case Decl::CXXConversion:
2975 case Decl::CXXDestructor:
2976 case Decl::CXXConstructor:
2977 valueKind = VK_RValue;
2978 break;
2979 }
2980
Larisse Voufo39a1e502013-08-06 01:03:05 +00002981 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2982 TemplateArgs);
John McCallf4cd4f92011-02-09 01:13:10 +00002983 }
Chris Lattner17ed4872006-11-20 04:58:19 +00002984}
Chris Lattnere168f762006-11-10 05:29:30 +00002985
Alexey Bataevec474782014-10-09 08:45:04 +00002986static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
2987 SmallString<32> &Target) {
2988 Target.resize(CharByteWidth * (Source.size() + 1));
2989 char *ResultPtr = &Target[0];
2990 const UTF8 *ErrorPtr;
2991 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
2992 (void)success;
2993 assert(success);
2994 Target.resize(ResultPtr - &Target[0]);
2995}
2996
Wei Panc354d212013-09-16 13:57:27 +00002997ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
2998 PredefinedExpr::IdentType IT) {
2999 // Pick the current block, lambda, captured statement or function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003000 Decl *currentDecl = nullptr;
Benjamin Kramer90f54222013-08-21 11:45:27 +00003001 if (const BlockScopeInfo *BSI = getCurBlock())
3002 currentDecl = BSI->TheDecl;
3003 else if (const LambdaScopeInfo *LSI = getCurLambda())
3004 currentDecl = LSI->CallOperator;
Wei Pan8d6b19a2013-08-26 14:27:34 +00003005 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3006 currentDecl = CSI->TheCapturedDecl;
Benjamin Kramer90f54222013-08-21 11:45:27 +00003007 else
3008 currentDecl = getCurFunctionOrMethodDecl();
Benjamin Kramer6928cf72012-12-06 15:42:21 +00003009
Anders Carlsson2fb08242009-09-08 18:24:21 +00003010 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00003011 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00003012 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00003013 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003014
Anders Carlsson0b209a82009-09-11 01:22:35 +00003015 QualType ResTy;
Alexey Bataevec474782014-10-09 08:45:04 +00003016 StringLiteral *SL = nullptr;
Wei Panc354d212013-09-16 13:57:27 +00003017 if (cast<DeclContext>(currentDecl)->isDependentContext())
Anders Carlsson0b209a82009-09-11 01:22:35 +00003018 ResTy = Context.DependentTy;
Wei Panc354d212013-09-16 13:57:27 +00003019 else {
3020 // Pre-defined identifiers are of type char[x], where x is the length of
3021 // the string.
Alexey Bataevec474782014-10-09 08:45:04 +00003022 auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3023 unsigned Length = Str.length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003024
Anders Carlsson0b209a82009-09-11 01:22:35 +00003025 llvm::APInt LengthI(32, Length + 1);
Alexey Bataevec474782014-10-09 08:45:04 +00003026 if (IT == PredefinedExpr::LFunction) {
Hans Wennborg0d81e012013-05-10 10:08:40 +00003027 ResTy = Context.WideCharTy.withConst();
Alexey Bataevec474782014-10-09 08:45:04 +00003028 SmallString<32> RawChars;
3029 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3030 Str, RawChars);
3031 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3032 /*IndexTypeQuals*/ 0);
3033 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3034 /*Pascal*/ false, ResTy, Loc);
3035 } else {
Nico Weber3a691a32012-06-23 02:07:59 +00003036 ResTy = Context.CharTy.withConst();
Alexey Bataevec474782014-10-09 08:45:04 +00003037 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3038 /*IndexTypeQuals*/ 0);
3039 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3040 /*Pascal*/ false, ResTy, Loc);
3041 }
Anders Carlsson0b209a82009-09-11 01:22:35 +00003042 }
Wei Panc354d212013-09-16 13:57:27 +00003043
Alexey Bataevec474782014-10-09 08:45:04 +00003044 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
Chris Lattnere168f762006-11-10 05:29:30 +00003045}
3046
Wei Panc354d212013-09-16 13:57:27 +00003047ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3048 PredefinedExpr::IdentType IT;
3049
3050 switch (Kind) {
3051 default: llvm_unreachable("Unknown simple primary expr!");
3052 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3053 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
David Majnemerbed356a2013-11-06 23:31:56 +00003054 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
Reid Kleckner52eddda2014-04-08 18:13:24 +00003055 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
Wei Panc354d212013-09-16 13:57:27 +00003056 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3057 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3058 }
3059
3060 return BuildPredefinedExpr(Loc, IT);
3061}
3062
Richard Smithbcc22fc2012-03-09 08:00:36 +00003063ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003064 SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00003065 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003066 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00003067 if (Invalid)
3068 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003069
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00003070 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00003071 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00003072 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00003073 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00003074
Chris Lattnerc3847ba2009-12-30 21:19:39 +00003075 QualType Ty;
Seth Cantrell02f86052012-01-18 12:27:06 +00003076 if (Literal.isWide())
Hans Wennborg0d81e012013-05-10 10:08:40 +00003077 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00003078 else if (Literal.isUTF16())
Seth Cantrell02f86052012-01-18 12:27:06 +00003079 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregorfb65e592011-07-27 05:40:30 +00003080 else if (Literal.isUTF32())
Seth Cantrell02f86052012-01-18 12:27:06 +00003081 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003082 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell02f86052012-01-18 12:27:06 +00003083 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00003084 else
3085 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00003086
Douglas Gregorfb65e592011-07-27 05:40:30 +00003087 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3088 if (Literal.isWide())
3089 Kind = CharacterLiteral::Wide;
3090 else if (Literal.isUTF16())
3091 Kind = CharacterLiteral::UTF16;
3092 else if (Literal.isUTF32())
3093 Kind = CharacterLiteral::UTF32;
3094
Richard Smith75b67d62012-03-08 01:34:56 +00003095 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3096 Tok.getLocation());
3097
3098 if (Literal.getUDSuffix().empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003099 return Lit;
Richard Smith75b67d62012-03-08 01:34:56 +00003100
3101 // We're building a user-defined literal.
3102 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3103 SourceLocation UDSuffixLoc =
3104 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3105
Richard Smithbcc22fc2012-03-09 08:00:36 +00003106 // Make sure we're allowed user-defined literals here.
3107 if (!UDLScope)
3108 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3109
Richard Smith75b67d62012-03-08 01:34:56 +00003110 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3111 // operator "" X (ch)
Richard Smithbcc22fc2012-03-09 08:00:36 +00003112 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003113 Lit, Tok.getLocation());
Steve Naroffae4143e2007-04-26 20:39:23 +00003114}
3115
Ted Kremeneke65b0862012-03-06 20:05:56 +00003116ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3117 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003118 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3119 Context.IntTy, Loc);
Ted Kremeneke65b0862012-03-06 20:05:56 +00003120}
3121
Richard Smith39570d002012-03-08 08:45:32 +00003122static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3123 QualType Ty, SourceLocation Loc) {
3124 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3125
3126 using llvm::APFloat;
3127 APFloat Val(Format);
3128
3129 APFloat::opStatus result = Literal.GetFloatValue(Val);
3130
3131 // Overflow is always an error, but underflow is only an error if
3132 // we underflowed to zero (APFloat reports denormals as underflow).
3133 if ((result & APFloat::opOverflow) ||
3134 ((result & APFloat::opUnderflow) && Val.isZero())) {
3135 unsigned diagnostic;
3136 SmallString<20> buffer;
3137 if (result & APFloat::opOverflow) {
3138 diagnostic = diag::warn_float_overflow;
3139 APFloat::getLargest(Format).toString(buffer);
3140 } else {
3141 diagnostic = diag::warn_float_underflow;
3142 APFloat::getSmallest(Format).toString(buffer);
3143 }
3144
3145 S.Diag(Loc, diagnostic)
3146 << Ty
3147 << StringRef(buffer.data(), buffer.size());
3148 }
3149
3150 bool isExact = (result == APFloat::opOK);
3151 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3152}
3153
Tyler Nowickic724a83e2014-10-12 20:46:07 +00003154bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3155 assert(E && "Invalid expression");
3156
3157 if (E->isValueDependent())
3158 return false;
3159
3160 QualType QT = E->getType();
3161 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3162 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3163 return true;
3164 }
3165
3166 llvm::APSInt ValueAPS;
3167 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3168
3169 if (R.isInvalid())
3170 return true;
3171
3172 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3173 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3174 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3175 << ValueAPS.toString(10) << ValueIsPositive;
3176 return true;
3177 }
3178
3179 return false;
3180}
3181
Richard Smithbcc22fc2012-03-09 08:00:36 +00003182ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00003183 // Fast path for a single digit (which is quite common). A single digit
Richard Smithbcc22fc2012-03-09 08:00:36 +00003184 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Steve Narofff2fb89e2007-03-13 20:29:44 +00003185 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00003186 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremeneke65b0862012-03-06 20:05:56 +00003187 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Steve Narofff2fb89e2007-03-13 20:29:44 +00003188 }
Ted Kremeneke9814182009-01-13 23:19:12 +00003189
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00003190 SmallString<128> SpellingBuffer;
3191 // NumericLiteralParser wants to overread by one character. Add padding to
3192 // the buffer in case the token is copied to the buffer. If getSpelling()
3193 // returns a StringRef to the memory buffer, it should have a null char at
3194 // the EOF, so it is also safe.
3195 SpellingBuffer.resize(Tok.getLength() + 1);
Sebastian Redlffbcf962009-01-18 18:53:16 +00003196
Chris Lattner67ca9252007-05-21 01:08:44 +00003197 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00003198 bool Invalid = false;
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00003199 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00003200 if (Invalid)
3201 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003202
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00003203 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00003204 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00003205 return ExprError();
3206
Richard Smith39570d002012-03-08 08:45:32 +00003207 if (Literal.hasUDSuffix()) {
3208 // We're building a user-defined literal.
3209 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3210 SourceLocation UDSuffixLoc =
3211 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3212
Richard Smithbcc22fc2012-03-09 08:00:36 +00003213 // Make sure we're allowed user-defined literals here.
3214 if (!UDLScope)
3215 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smith39570d002012-03-08 08:45:32 +00003216
Richard Smithbcc22fc2012-03-09 08:00:36 +00003217 QualType CookedTy;
Richard Smith39570d002012-03-08 08:45:32 +00003218 if (Literal.isFloatingLiteral()) {
3219 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3220 // long double, the literal is treated as a call of the form
3221 // operator "" X (f L)
Richard Smithbcc22fc2012-03-09 08:00:36 +00003222 CookedTy = Context.LongDoubleTy;
Richard Smith39570d002012-03-08 08:45:32 +00003223 } else {
3224 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3225 // unsigned long long, the literal is treated as a call of the form
3226 // operator "" X (n ULL)
Richard Smithbcc22fc2012-03-09 08:00:36 +00003227 CookedTy = Context.UnsignedLongLongTy;
Richard Smith39570d002012-03-08 08:45:32 +00003228 }
3229
Richard Smithbcc22fc2012-03-09 08:00:36 +00003230 DeclarationName OpName =
3231 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3232 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3233 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3234
Richard Smithb8b41d32013-10-07 19:57:58 +00003235 SourceLocation TokLoc = Tok.getLocation();
3236
Richard Smithbcc22fc2012-03-09 08:00:36 +00003237 // Perform literal operator lookup to determine if we're building a raw
3238 // literal or a cooked one.
3239 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003240 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
Richard Smithb8b41d32013-10-07 19:57:58 +00003241 /*AllowRaw*/true, /*AllowTemplate*/true,
3242 /*AllowStringTemplate*/false)) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003243 case LOLR_Error:
3244 return ExprError();
3245
3246 case LOLR_Cooked: {
3247 Expr *Lit;
3248 if (Literal.isFloatingLiteral()) {
3249 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3250 } else {
3251 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3252 if (Literal.GetIntegerValue(ResultVal))
Aaron Ballman31f42312014-07-24 14:51:23 +00003253 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3254 << /* Unsigned */ 1;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003255 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3256 Tok.getLocation());
3257 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003258 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
Richard Smithbcc22fc2012-03-09 08:00:36 +00003259 }
3260
3261 case LOLR_Raw: {
3262 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3263 // literal is treated as a call of the form
3264 // operator "" X ("n")
Richard Smithbcc22fc2012-03-09 08:00:36 +00003265 unsigned Length = Literal.getUDSuffixOffset();
3266 QualType StrTy = Context.getConstantArrayType(
Richard Smithbe8229c2013-01-23 23:38:20 +00003267 Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
Richard Smithbcc22fc2012-03-09 08:00:36 +00003268 ArrayType::Normal, 0);
3269 Expr *Lit = StringLiteral::Create(
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00003270 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
Richard Smithbcc22fc2012-03-09 08:00:36 +00003271 /*Pascal*/false, StrTy, &TokLoc, 1);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003272 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
Richard Smithbcc22fc2012-03-09 08:00:36 +00003273 }
3274
Richard Smithb8b41d32013-10-07 19:57:58 +00003275 case LOLR_Template: {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003276 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3277 // template), L is treated as a call fo the form
3278 // operator "" X <'c1', 'c2', ... 'ck'>()
3279 // where n is the source character sequence c1 c2 ... ck.
3280 TemplateArgumentListInfo ExplicitArgs;
3281 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3282 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3283 llvm::APSInt Value(CharBits, CharIsUnsigned);
3284 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00003285 Value = TokSpelling[I];
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003286 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smithbcc22fc2012-03-09 08:00:36 +00003287 TemplateArgumentLocInfo ArgInfo;
3288 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3289 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003290 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003291 &ExplicitArgs);
Richard Smithbcc22fc2012-03-09 08:00:36 +00003292 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003293 case LOLR_StringTemplate:
3294 llvm_unreachable("unexpected literal operator lookup result");
3295 }
Richard Smith39570d002012-03-08 08:45:32 +00003296 }
3297
Chris Lattner1c20a172007-08-26 03:42:43 +00003298 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00003299
Chris Lattner1c20a172007-08-26 03:42:43 +00003300 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00003301 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00003302 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00003303 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00003304 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00003305 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00003306 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00003307 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00003308
Richard Smith39570d002012-03-08 08:45:32 +00003309 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00003310
Peter Collingbournec77f85b2011-03-11 19:24:59 +00003311 if (Ty == Context.DoubleTy) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003312 if (getLangOpts().SinglePrecisionConstants) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003313 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
Fraser Cormackcc6e8942015-01-30 10:51:46 +00003314 } else if (getLangOpts().OpenCL &&
3315 !((getLangOpts().OpenCLVersion >= 120) ||
3316 getOpenCLOptions().cl_khr_fp64)) {
Peter Collingbournec77f85b2011-03-11 19:24:59 +00003317 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003318 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00003319 }
3320 }
Chris Lattner1c20a172007-08-26 03:42:43 +00003321 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00003322 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00003323 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003324 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00003325
Dmitri Gribenko1cd23052012-09-24 18:19:21 +00003326 // 'long long' is a C99 or C++11 feature.
3327 if (!getLangOpts().C99 && Literal.isLongLong) {
3328 if (getLangOpts().CPlusPlus)
3329 Diag(Tok.getLocation(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003330 getLangOpts().CPlusPlus11 ?
Dmitri Gribenko1cd23052012-09-24 18:19:21 +00003331 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3332 else
3333 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3334 }
Neil Boothac582c52007-08-29 22:00:19 +00003335
Chris Lattner67ca9252007-05-21 01:08:44 +00003336 // Get the value in the widest-possible width.
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00003337 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00003338 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00003339
Chris Lattner67ca9252007-05-21 01:08:44 +00003340 if (Literal.GetIntegerValue(ResultVal)) {
Eli Friedman088d39a2013-07-23 00:25:18 +00003341 // If this value didn't fit into uintmax_t, error and force to ull.
Aaron Ballman31f42312014-07-24 14:51:23 +00003342 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3343 << /* Unsigned */ 1;
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003344 Ty = Context.UnsignedLongLongTy;
3345 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00003346 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00003347 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00003348 // If this value fits into a ULL, try to figure out what else it fits into
3349 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00003350
Chris Lattner67ca9252007-05-21 01:08:44 +00003351 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3352 // be an unsigned int.
3353 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3354
3355 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00003356 unsigned Width = 0;
David Majnemer65a407c2014-06-21 18:46:07 +00003357
3358 // Microsoft specific integer suffixes are explicitly sized.
3359 if (Literal.MicrosoftInteger) {
David Majnemer5055dfc2015-07-26 09:02:26 +00003360 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
David Majnemerbe09e8e2015-03-06 18:04:22 +00003361 Width = 8;
3362 Ty = Context.CharTy;
David Majnemer65a407c2014-06-21 18:46:07 +00003363 } else {
3364 Width = Literal.MicrosoftInteger;
3365 Ty = Context.getIntTypeForBitwidth(Width,
3366 /*Signed=*/!Literal.isUnsigned);
3367 }
3368 }
3369
3370 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
Chris Lattner7b939cf2007-08-23 21:58:08 +00003371 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00003372 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003373
Chris Lattner67ca9252007-05-21 01:08:44 +00003374 // Does it fit in a unsigned int?
3375 if (ResultVal.isIntN(IntSize)) {
3376 // Does it fit in a signed int?
3377 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003378 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00003379 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003380 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00003381 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00003382 }
Chris Lattner67ca9252007-05-21 01:08:44 +00003383 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003384
Chris Lattner67ca9252007-05-21 01:08:44 +00003385 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003386 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003387 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003388
Chris Lattner67ca9252007-05-21 01:08:44 +00003389 // Does it fit in a unsigned long?
3390 if (ResultVal.isIntN(LongSize)) {
3391 // Does it fit in a signed long?
3392 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003393 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00003394 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003395 Ty = Context.UnsignedLongTy;
Hubert Tong13234ae2015-06-08 21:59:59 +00003396 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3397 // is compatible.
3398 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3399 const unsigned LongLongSize =
3400 Context.getTargetInfo().getLongLongWidth();
3401 Diag(Tok.getLocation(),
3402 getLangOpts().CPlusPlus
3403 ? Literal.isLong
3404 ? diag::warn_old_implicitly_unsigned_long_cxx
3405 : /*C++98 UB*/ diag::
3406 ext_old_implicitly_unsigned_long_cxx
3407 : diag::warn_old_implicitly_unsigned_long)
3408 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3409 : /*will be ill-formed*/ 1);
3410 Ty = Context.UnsignedLongTy;
3411 }
Chris Lattner55258cf2008-05-09 05:59:00 +00003412 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00003413 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003414 }
3415
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00003416 // Check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003417 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003418 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003419
Chris Lattner67ca9252007-05-21 01:08:44 +00003420 // Does it fit in a unsigned long long?
3421 if (ResultVal.isIntN(LongLongSize)) {
3422 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00003423 // To be compatible with MSVC, hex integer literals ending with the
3424 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00003425 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003426 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003427 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00003428 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003429 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00003430 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00003431 }
3432 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003433
Chris Lattner67ca9252007-05-21 01:08:44 +00003434 // If we still couldn't decide a type, we probably have something that
3435 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003436 if (Ty.isNull()) {
Aaron Ballman31f42312014-07-24 14:51:23 +00003437 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003438 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00003439 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00003440 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003441
Chris Lattner55258cf2008-05-09 05:59:00 +00003442 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00003443 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00003444 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003445 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00003446 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003447
Chris Lattner1c20a172007-08-26 03:42:43 +00003448 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3449 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00003450 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00003451 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00003452
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003453 return Res;
Chris Lattnere168f762006-11-10 05:29:30 +00003454}
3455
Richard Trieuba63ce62011-09-09 01:45:06 +00003456ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003457 assert(E && "ActOnParenExpr() missing expr");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003458 return new (Context) ParenExpr(L, R, E);
Chris Lattnere168f762006-11-10 05:29:30 +00003459}
3460
Chandler Carruth62da79c2011-05-26 08:53:12 +00003461static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3462 SourceLocation Loc,
3463 SourceRange ArgRange) {
3464 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3465 // scalar or vector data type argument..."
3466 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3467 // type (C99 6.2.5p18) or void.
3468 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3469 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3470 << T << ArgRange;
3471 return true;
3472 }
3473
3474 assert((T->isVoidType() || !T->isIncompleteType()) &&
3475 "Scalar types should always be complete");
3476 return false;
3477}
3478
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003479static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3480 SourceLocation Loc,
3481 SourceRange ArgRange,
3482 UnaryExprOrTypeTrait TraitKind) {
Eli Friedman4e28b262013-08-13 22:26:42 +00003483 // Invalid types must be hard errors for SFINAE in C++.
3484 if (S.LangOpts.CPlusPlus)
3485 return true;
3486
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003487 // C99 6.5.3.4p1:
Richard Smith9cf21ae2013-03-18 23:37:25 +00003488 if (T->isFunctionType() &&
3489 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3490 // sizeof(function)/alignof(function) is allowed as an extension.
3491 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3492 << TraitKind << ArgRange;
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003493 return false;
3494 }
3495
Joey Gouly4ba0f1e2013-12-31 15:47:49 +00003496 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3497 // this is an error (OpenCL v1.1 s6.3.k)
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003498 if (T->isVoidType()) {
Joey Gouly4ba0f1e2013-12-31 15:47:49 +00003499 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3500 : diag::ext_sizeof_alignof_void_type;
3501 S.Diag(Loc, DiagID) << TraitKind << ArgRange;
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003502 return false;
3503 }
3504
3505 return true;
3506}
3507
3508static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3509 SourceLocation Loc,
3510 SourceRange ArgRange,
3511 UnaryExprOrTypeTrait TraitKind) {
John McCallf2538342012-07-31 05:14:30 +00003512 // Reject sizeof(interface) and sizeof(interface<proto>) if the
3513 // runtime doesn't allow it.
3514 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003515 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3516 << T << (TraitKind == UETT_SizeOf)
3517 << ArgRange;
3518 return true;
3519 }
3520
3521 return false;
3522}
3523
Benjamin Kramer054faa52013-03-29 21:43:21 +00003524/// \brief Check whether E is a pointer from a decayed array type (the decayed
3525/// pointer type is equal to T) and emit a warning if it is.
3526static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3527 Expr *E) {
3528 // Don't warn if the operation changed the type.
3529 if (T != E->getType())
3530 return;
3531
3532 // Now look for array decays.
3533 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3534 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3535 return;
3536
3537 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3538 << ICE->getType()
3539 << ICE->getSubExpr()->getType();
3540}
3541
Alp Toker95e7ff22014-01-01 05:57:51 +00003542/// \brief Check the constraints on expression operands to unary type expression
Chandler Carruth14502c22011-05-26 08:53:10 +00003543/// and type traits.
3544///
Chandler Carruth7c430c02011-05-27 01:33:31 +00003545/// Completes any types necessary and validates the constraints on the operand
3546/// expression. The logic mostly mirrors the type-based overload, but may modify
3547/// the expression as it completes the type for that expression through template
3548/// instantiation, etc.
Richard Trieuba63ce62011-09-09 01:45:06 +00003549bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth14502c22011-05-26 08:53:10 +00003550 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003551 QualType ExprTy = E->getType();
John McCall768439e2013-05-06 07:40:34 +00003552 assert(!ExprTy->isReferenceType());
Chandler Carruth7c430c02011-05-27 01:33:31 +00003553
3554 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00003555 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3556 E->getSourceRange());
Chandler Carruth7c430c02011-05-27 01:33:31 +00003557
3558 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00003559 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3560 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00003561 return false;
3562
Richard Smithf6d70302014-06-10 23:34:28 +00003563 // 'alignof' applied to an expression only requires the base element type of
3564 // the expression to be complete. 'sizeof' requires the expression's type to
3565 // be complete (and will attempt to complete it if it's an array of unknown
3566 // bound).
3567 if (ExprKind == UETT_AlignOf) {
3568 if (RequireCompleteType(E->getExprLoc(),
3569 Context.getBaseElementType(E->getType()),
3570 diag::err_sizeof_alignof_incomplete_type, ExprKind,
3571 E->getSourceRange()))
3572 return true;
3573 } else {
3574 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3575 ExprKind, E->getSourceRange()))
3576 return true;
3577 }
Chandler Carruth7c430c02011-05-27 01:33:31 +00003578
John McCall768439e2013-05-06 07:40:34 +00003579 // Completing the expression's type may have changed it.
Richard Trieuba63ce62011-09-09 01:45:06 +00003580 ExprTy = E->getType();
John McCall768439e2013-05-06 07:40:34 +00003581 assert(!ExprTy->isReferenceType());
Chandler Carruth7c430c02011-05-27 01:33:31 +00003582
Eli Friedman4e28b262013-08-13 22:26:42 +00003583 if (ExprTy->isFunctionType()) {
3584 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3585 << ExprKind << E->getSourceRange();
3586 return true;
3587 }
3588
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003589 // The operand for sizeof and alignof is in an unevaluated expression context,
3590 // so side effects could result in unintended consequences.
3591 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3592 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3593 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3594
Richard Trieuba63ce62011-09-09 01:45:06 +00003595 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3596 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00003597 return true;
3598
Nico Weber0870deb2011-06-15 02:47:03 +00003599 if (ExprKind == UETT_SizeOf) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003600 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Weber0870deb2011-06-15 02:47:03 +00003601 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3602 QualType OType = PVD->getOriginalType();
3603 QualType Type = PVD->getType();
3604 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003605 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Weber0870deb2011-06-15 02:47:03 +00003606 << Type << OType;
3607 Diag(PVD->getLocation(), diag::note_declared_at);
3608 }
3609 }
3610 }
Benjamin Kramer054faa52013-03-29 21:43:21 +00003611
3612 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3613 // decays into a pointer and returns an unintended result. This is most
3614 // likely a typo for "sizeof(array) op x".
3615 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3616 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3617 BO->getLHS());
3618 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3619 BO->getRHS());
3620 }
Nico Weber0870deb2011-06-15 02:47:03 +00003621 }
3622
Chandler Carruth7c430c02011-05-27 01:33:31 +00003623 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00003624}
3625
3626/// \brief Check the constraints on operands to unary expression and type
3627/// traits.
3628///
3629/// This will complete any types necessary, and validate the various constraints
3630/// on those operands.
3631///
Steve Naroff71b59a92007-06-04 22:22:31 +00003632/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00003633/// C99 6.3.2.1p[2-4] all state:
3634/// Except when it is the operand of the sizeof operator ...
3635///
3636/// C++ [expr.sizeof]p4
3637/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3638/// standard conversions are not applied to the operand of sizeof.
3639///
3640/// This policy is followed for all of the unary trait expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00003641bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00003642 SourceLocation OpLoc,
3643 SourceRange ExprRange,
3644 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003645 if (ExprType->isDependentType())
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003646 return false;
3647
Richard Smithc3fbf682014-06-10 21:11:26 +00003648 // C++ [expr.sizeof]p2:
3649 // When applied to a reference or a reference type, the result
3650 // is the size of the referenced type.
3651 // C++11 [expr.alignof]p3:
3652 // When alignof is applied to a reference type, the result
3653 // shall be the alignment of the referenced type.
Richard Trieuba63ce62011-09-09 01:45:06 +00003654 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3655 ExprType = Ref->getPointeeType();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003656
Richard Smithc3fbf682014-06-10 21:11:26 +00003657 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3658 // When alignof or _Alignof is applied to an array type, the result
3659 // is the alignment of the element type.
Alexey Bataev00396512015-07-02 03:40:19 +00003660 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
Richard Smithc3fbf682014-06-10 21:11:26 +00003661 ExprType = Context.getBaseElementType(ExprType);
3662
Chandler Carruth62da79c2011-05-26 08:53:12 +00003663 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00003664 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003665
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003666 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00003667 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003668 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00003669 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003670
Richard Trieuba63ce62011-09-09 01:45:06 +00003671 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003672 diag::err_sizeof_alignof_incomplete_type,
3673 ExprKind, ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00003674 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003675
Eli Friedman4e28b262013-08-13 22:26:42 +00003676 if (ExprType->isFunctionType()) {
3677 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3678 << ExprKind << ExprRange;
3679 return true;
3680 }
3681
Richard Trieuba63ce62011-09-09 01:45:06 +00003682 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003683 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00003684 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003685
Chris Lattner62975a72009-04-24 00:30:45 +00003686 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00003687}
3688
Chandler Carruth14502c22011-05-26 08:53:10 +00003689static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00003690 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003691
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003692 // Cannot know anything else if the expression is dependent.
3693 if (E->isTypeDependent())
3694 return false;
3695
John McCall768439e2013-05-06 07:40:34 +00003696 if (E->getObjectKind() == OK_BitField) {
Richard Smithe301ba22015-11-11 02:02:15 +00003697 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
Chandler Carruth14502c22011-05-26 08:53:10 +00003698 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003699 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00003700 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00003701
Craig Topperc3ec1492014-05-26 06:22:03 +00003702 ValueDecl *D = nullptr;
John McCall768439e2013-05-06 07:40:34 +00003703 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3704 D = DRE->getDecl();
3705 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3706 D = ME->getMemberDecl();
3707 }
3708
3709 // If it's a field, require the containing struct to have a
3710 // complete definition so that we can compute the layout.
3711 //
Richard Smithc3fbf682014-06-10 21:11:26 +00003712 // This can happen in C++11 onwards, either by naming the member
3713 // in a way that is not transformed into a member access expression
3714 // (in an unevaluated operand, for instance), or by naming the member
3715 // in a trailing-return-type.
John McCall768439e2013-05-06 07:40:34 +00003716 //
3717 // For the record, since __alignof__ on expressions is a GCC
3718 // extension, GCC seems to permit this but always gives the
3719 // nonsensical answer 0.
3720 //
3721 // We don't really need the layout here --- we could instead just
3722 // directly check for all the appropriate alignment-lowing
3723 // attributes --- but that would require duplicating a lot of
3724 // logic that just isn't worth duplicating for such a marginal
3725 // use-case.
3726 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3727 // Fast path this check, since we at least know the record has a
3728 // definition if we can find a member of it.
3729 if (!FD->getParent()->isCompleteDefinition()) {
3730 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3731 << E->getSourceRange();
3732 return true;
3733 }
3734
3735 // Otherwise, if it's a field, and the field doesn't have
3736 // reference type, then it must have a complete type (or be a
3737 // flexible array member, which we explicitly want to
3738 // white-list anyway), which makes the following checks trivial.
3739 if (!FD->getType()->isReferenceType())
Douglas Gregor71235ec2009-05-02 02:18:30 +00003740 return false;
John McCall768439e2013-05-06 07:40:34 +00003741 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00003742
Chandler Carruth14502c22011-05-26 08:53:10 +00003743 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003744}
3745
Chandler Carruth14502c22011-05-26 08:53:10 +00003746bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00003747 E = E->IgnoreParens();
3748
3749 // Cannot know anything else if the expression is dependent.
3750 if (E->isTypeDependent())
3751 return false;
3752
Chandler Carruth14502c22011-05-26 08:53:10 +00003753 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00003754}
3755
Douglas Gregor0950e412009-03-13 21:01:28 +00003756/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00003757ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003758Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3759 SourceLocation OpLoc,
3760 UnaryExprOrTypeTrait ExprKind,
3761 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00003762 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00003763 return ExprError();
3764
John McCallbcd03502009-12-07 02:54:59 +00003765 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00003766
Douglas Gregor0950e412009-03-13 21:01:28 +00003767 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00003768 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00003769 return ExprError();
3770
3771 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003772 return new (Context) UnaryExprOrTypeTraitExpr(
3773 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
Douglas Gregor0950e412009-03-13 21:01:28 +00003774}
3775
3776/// \brief Build a sizeof or alignof expression given an expression
3777/// operand.
John McCalldadc5752010-08-24 06:29:42 +00003778ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00003779Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3780 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00003781 ExprResult PE = CheckPlaceholderExpr(E);
3782 if (PE.isInvalid())
3783 return ExprError();
3784
3785 E = PE.get();
3786
Douglas Gregor0950e412009-03-13 21:01:28 +00003787 // Verify that the operand is valid.
3788 bool isInvalid = false;
3789 if (E->isTypeDependent()) {
3790 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003791 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003792 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003793 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003794 isInvalid = CheckVecStepExpr(E);
Alexey Bataev00396512015-07-02 03:40:19 +00003795 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
3796 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
3797 isInvalid = true;
John McCalld25db7e2013-05-06 21:39:12 +00003798 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
Richard Smithe301ba22015-11-11 02:02:15 +00003799 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00003800 isInvalid = true;
3801 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00003802 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00003803 }
3804
3805 if (isInvalid)
3806 return ExprError();
3807
Eli Friedmane0afc982012-01-21 01:01:51 +00003808 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
Benjamin Kramerd81108f2012-11-14 15:08:31 +00003809 PE = TransformToPotentiallyEvaluated(E);
Eli Friedmane0afc982012-01-21 01:01:51 +00003810 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003811 E = PE.get();
Eli Friedmane0afc982012-01-21 01:01:51 +00003812 }
3813
Douglas Gregor0950e412009-03-13 21:01:28 +00003814 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003815 return new (Context) UnaryExprOrTypeTraitExpr(
3816 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
Douglas Gregor0950e412009-03-13 21:01:28 +00003817}
3818
Peter Collingbournee190dee2011-03-11 19:24:49 +00003819/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3820/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00003821/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00003822ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003823Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003824 UnaryExprOrTypeTrait ExprKind, bool IsType,
Craig Toppere335f252015-10-04 04:53:55 +00003825 void *TyOrEx, SourceRange ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00003826 // If error parsing type, ignore.
Craig Topperc3ec1492014-05-26 06:22:03 +00003827 if (!TyOrEx) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00003828
Richard Trieuba63ce62011-09-09 01:45:06 +00003829 if (IsType) {
John McCallbcd03502009-12-07 02:54:59 +00003830 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00003831 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003832 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00003833 }
Sebastian Redl6f282892008-11-11 17:56:53 +00003834
Douglas Gregor0950e412009-03-13 21:01:28 +00003835 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00003836 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003837 return Result;
Chris Lattnere168f762006-11-10 05:29:30 +00003838}
3839
John Wiegley01296292011-04-08 18:41:53 +00003840static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003841 bool IsReal) {
John Wiegley01296292011-04-08 18:41:53 +00003842 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00003843 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00003844
John McCall34376a62010-12-04 03:47:34 +00003845 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00003846 if (V.get()->getObjectKind() != OK_Ordinary) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003847 V = S.DefaultLvalueConversion(V.get());
John Wiegley01296292011-04-08 18:41:53 +00003848 if (V.isInvalid())
3849 return QualType();
3850 }
John McCall34376a62010-12-04 03:47:34 +00003851
Chris Lattnere267f5d2007-08-26 05:39:26 +00003852 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00003853 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00003854 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00003855
Chris Lattnere267f5d2007-08-26 05:39:26 +00003856 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00003857 if (V.get()->getType()->isArithmeticType())
3858 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003859
John McCall36226622010-10-12 02:09:17 +00003860 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00003861 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00003862 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003863 if (PR.get() != V.get()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003864 V = PR;
Richard Trieuba63ce62011-09-09 01:45:06 +00003865 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall36226622010-10-12 02:09:17 +00003866 }
3867
Chris Lattnere267f5d2007-08-26 05:39:26 +00003868 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00003869 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuba63ce62011-09-09 01:45:06 +00003870 << (IsReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00003871 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00003872}
3873
3874
Chris Lattnere168f762006-11-10 05:29:30 +00003875
John McCalldadc5752010-08-24 06:29:42 +00003876ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003877Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003878 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00003879 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00003880 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003881 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003882 case tok::plusplus: Opc = UO_PostInc; break;
3883 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003884 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003885
Sebastian Redla9351792012-02-11 23:51:47 +00003886 // Since this might is a postfix expression, get rid of ParenListExprs.
3887 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3888 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003889 Input = Result.get();
Sebastian Redla9351792012-02-11 23:51:47 +00003890
John McCallb268a282010-08-23 23:25:46 +00003891 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003892}
3893
John McCallf2538342012-07-31 05:14:30 +00003894/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3895///
3896/// \return true on error
3897static bool checkArithmeticOnObjCPointer(Sema &S,
3898 SourceLocation opLoc,
3899 Expr *op) {
3900 assert(op->getType()->isObjCObjectPointerType());
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +00003901 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
3902 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
John McCallf2538342012-07-31 05:14:30 +00003903 return false;
3904
3905 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3906 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3907 << op->getSourceRange();
3908 return true;
3909}
3910
Alexey Bataevf7630272015-11-25 12:01:00 +00003911static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
3912 auto *BaseNoParens = Base->IgnoreParens();
3913 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
3914 return MSProp->getPropertyDecl()->getType()->isArrayType();
3915 return isa<MSPropertySubscriptExpr>(BaseNoParens);
3916}
3917
John McCalldadc5752010-08-24 06:29:42 +00003918ExprResult
John McCallf22d0ac2013-03-04 01:30:55 +00003919Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3920 Expr *idx, SourceLocation rbLoc) {
Alexey Bataev627cbd32015-08-25 15:15:12 +00003921 if (base && !base->getType().isNull() &&
3922 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
Alexey Bataev1a3320e2015-08-25 14:24:04 +00003923 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
3924 /*Length=*/nullptr, rbLoc);
3925
Nate Begeman5ec4b312009-08-10 23:49:36 +00003926 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCallf22d0ac2013-03-04 01:30:55 +00003927 if (isa<ParenListExpr>(base)) {
3928 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3929 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003930 base = result.get();
John McCallf22d0ac2013-03-04 01:30:55 +00003931 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00003932
John McCallf22d0ac2013-03-04 01:30:55 +00003933 // Handle any non-overload placeholder types in the base and index
3934 // expressions. We can't handle overloads here because the other
3935 // operand might be an overloadable type, in which case the overload
3936 // resolution for the operator overload should get the first crack
3937 // at the overload.
Alexey Bataevf7630272015-11-25 12:01:00 +00003938 bool IsMSPropertySubscript = false;
John McCallf22d0ac2013-03-04 01:30:55 +00003939 if (base->getType()->isNonOverloadPlaceholderType()) {
Alexey Bataevf7630272015-11-25 12:01:00 +00003940 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
3941 if (!IsMSPropertySubscript) {
3942 ExprResult result = CheckPlaceholderExpr(base);
3943 if (result.isInvalid())
3944 return ExprError();
3945 base = result.get();
3946 }
John McCallf22d0ac2013-03-04 01:30:55 +00003947 }
3948 if (idx->getType()->isNonOverloadPlaceholderType()) {
3949 ExprResult result = CheckPlaceholderExpr(idx);
3950 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003951 idx = result.get();
John McCallf22d0ac2013-03-04 01:30:55 +00003952 }
Mike Stump11289f42009-09-09 15:08:12 +00003953
John McCallf22d0ac2013-03-04 01:30:55 +00003954 // Build an unanalyzed expression if either operand is type-dependent.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003955 if (getLangOpts().CPlusPlus &&
John McCallf22d0ac2013-03-04 01:30:55 +00003956 (base->isTypeDependent() || idx->isTypeDependent())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003957 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
3958 VK_LValue, OK_Ordinary, rbLoc);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003959 }
3960
Alexey Bataevf7630272015-11-25 12:01:00 +00003961 // MSDN, property (C++)
3962 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
3963 // This attribute can also be used in the declaration of an empty array in a
3964 // class or structure definition. For example:
3965 // __declspec(property(get=GetX, put=PutX)) int x[];
3966 // The above statement indicates that x[] can be used with one or more array
3967 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
3968 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
3969 if (IsMSPropertySubscript) {
3970 // Build MS property subscript expression if base is MS property reference
3971 // or MS property subscript.
3972 return new (Context) MSPropertySubscriptExpr(
3973 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
3974 }
3975
John McCallf22d0ac2013-03-04 01:30:55 +00003976 // Use C++ overloaded-operator rules if either operand has record
3977 // type. The spec says to do this if either type is *overloadable*,
3978 // but enum types can't declare subscript operators or conversion
3979 // operators, so there's nothing interesting for overload resolution
3980 // to do if there aren't any record types involved.
3981 //
3982 // ObjC pointers have their own subscripting logic that is not tied
3983 // to overload resolution and so should not take this path.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003984 if (getLangOpts().CPlusPlus &&
John McCallf22d0ac2013-03-04 01:30:55 +00003985 (base->getType()->isRecordType() ||
3986 (!base->getType()->isObjCObjectPointerType() &&
3987 idx->getType()->isRecordType()))) {
3988 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003989 }
3990
John McCallf22d0ac2013-03-04 01:30:55 +00003991 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003992}
3993
Alexey Bataev1a3320e2015-08-25 14:24:04 +00003994ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
3995 Expr *LowerBound,
3996 SourceLocation ColonLoc, Expr *Length,
3997 SourceLocation RBLoc) {
3998 if (Base->getType()->isPlaceholderType() &&
3999 !Base->getType()->isSpecificPlaceholderType(
4000 BuiltinType::OMPArraySection)) {
4001 ExprResult Result = CheckPlaceholderExpr(Base);
4002 if (Result.isInvalid())
4003 return ExprError();
4004 Base = Result.get();
4005 }
4006 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4007 ExprResult Result = CheckPlaceholderExpr(LowerBound);
4008 if (Result.isInvalid())
4009 return ExprError();
4010 LowerBound = Result.get();
4011 }
4012 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4013 ExprResult Result = CheckPlaceholderExpr(Length);
4014 if (Result.isInvalid())
4015 return ExprError();
4016 Length = Result.get();
4017 }
4018
4019 // Build an unanalyzed expression if either operand is type-dependent.
4020 if (Base->isTypeDependent() ||
4021 (LowerBound &&
4022 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4023 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4024 return new (Context)
4025 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4026 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4027 }
4028
4029 // Perform default conversions.
Alexey Bataeva1764212015-09-30 09:22:36 +00004030 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004031 QualType ResultTy;
4032 if (OriginalTy->isAnyPointerType()) {
4033 ResultTy = OriginalTy->getPointeeType();
4034 } else if (OriginalTy->isArrayType()) {
4035 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4036 } else {
4037 return ExprError(
4038 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4039 << Base->getSourceRange());
4040 }
4041 // C99 6.5.2.1p1
4042 if (LowerBound) {
4043 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4044 LowerBound);
4045 if (Res.isInvalid())
4046 return ExprError(Diag(LowerBound->getExprLoc(),
4047 diag::err_omp_typecheck_section_not_integer)
4048 << 0 << LowerBound->getSourceRange());
4049 LowerBound = Res.get();
4050
4051 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4052 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4053 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4054 << 0 << LowerBound->getSourceRange();
4055 }
4056 if (Length) {
4057 auto Res =
4058 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4059 if (Res.isInvalid())
4060 return ExprError(Diag(Length->getExprLoc(),
4061 diag::err_omp_typecheck_section_not_integer)
4062 << 1 << Length->getSourceRange());
4063 Length = Res.get();
4064
4065 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4066 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4067 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4068 << 1 << Length->getSourceRange();
4069 }
4070
4071 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4072 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4073 // type. Note that functions are not objects, and that (in C99 parlance)
4074 // incomplete types are not object types.
4075 if (ResultTy->isFunctionType()) {
4076 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4077 << ResultTy << Base->getSourceRange();
4078 return ExprError();
4079 }
4080
4081 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4082 diag::err_omp_section_incomplete_type, Base))
4083 return ExprError();
4084
4085 if (LowerBound) {
4086 llvm::APSInt LowerBoundValue;
4087 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4088 // OpenMP 4.0, [2.4 Array Sections]
4089 // The lower-bound and length must evaluate to non-negative integers.
4090 if (LowerBoundValue.isNegative()) {
4091 Diag(LowerBound->getExprLoc(), diag::err_omp_section_negative)
4092 << 0 << LowerBoundValue.toString(/*Radix=*/10, /*Signed=*/true)
4093 << LowerBound->getSourceRange();
4094 return ExprError();
4095 }
4096 }
4097 }
4098
4099 if (Length) {
4100 llvm::APSInt LengthValue;
4101 if (Length->EvaluateAsInt(LengthValue, Context)) {
4102 // OpenMP 4.0, [2.4 Array Sections]
4103 // The lower-bound and length must evaluate to non-negative integers.
4104 if (LengthValue.isNegative()) {
4105 Diag(Length->getExprLoc(), diag::err_omp_section_negative)
4106 << 1 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4107 << Length->getSourceRange();
4108 return ExprError();
4109 }
4110 }
4111 } else if (ColonLoc.isValid() &&
4112 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4113 !OriginalTy->isVariableArrayType()))) {
4114 // OpenMP 4.0, [2.4 Array Sections]
4115 // When the size of the array dimension is not known, the length must be
4116 // specified explicitly.
4117 Diag(ColonLoc, diag::err_omp_section_length_undefined)
4118 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4119 return ExprError();
4120 }
4121
4122 return new (Context)
4123 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4124 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4125}
4126
John McCalldadc5752010-08-24 06:29:42 +00004127ExprResult
John McCallb268a282010-08-23 23:25:46 +00004128Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004129 Expr *Idx, SourceLocation RLoc) {
John McCallb268a282010-08-23 23:25:46 +00004130 Expr *LHSExp = Base;
4131 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00004132
Chris Lattner36d572b2007-07-16 00:14:47 +00004133 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00004134 if (!LHSExp->getType()->getAs<VectorType>()) {
4135 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4136 if (Result.isInvalid())
4137 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004138 LHSExp = Result.get();
John Wiegley01296292011-04-08 18:41:53 +00004139 }
4140 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4141 if (Result.isInvalid())
4142 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004143 RHSExp = Result.get();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004144
Chris Lattner36d572b2007-07-16 00:14:47 +00004145 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00004146 ExprValueKind VK = VK_LValue;
4147 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00004148
Steve Naroffc1aadb12007-03-28 21:49:40 +00004149 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00004150 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00004151 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00004152 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00004153 Expr *BaseExpr, *IndexExpr;
4154 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004155 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4156 BaseExpr = LHSExp;
4157 IndexExpr = RHSExp;
4158 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004159 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00004160 BaseExpr = LHSExp;
4161 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00004162 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004163 } else if (const ObjCObjectPointerType *PTy =
John McCallf2538342012-07-31 05:14:30 +00004164 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004165 BaseExpr = LHSExp;
4166 IndexExpr = RHSExp;
John McCallf2538342012-07-31 05:14:30 +00004167
4168 // Use custom logic if this should be the pseudo-object subscript
4169 // expression.
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +00004170 if (!LangOpts.isSubscriptPointerArithmetic())
Craig Topperc3ec1492014-05-26 06:22:03 +00004171 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4172 nullptr);
John McCallf2538342012-07-31 05:14:30 +00004173
Steve Naroff7cae42b2009-07-10 23:34:53 +00004174 ResultType = PTy->getPointeeType();
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00004175 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4176 // Handle the uncommon case of "123[Ptr]".
4177 BaseExpr = RHSExp;
4178 IndexExpr = LHSExp;
4179 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004180 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00004181 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004182 // Handle the uncommon case of "123[Ptr]".
4183 BaseExpr = RHSExp;
4184 IndexExpr = LHSExp;
4185 ResultType = PTy->getPointeeType();
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +00004186 if (!LangOpts.isSubscriptPointerArithmetic()) {
John McCallf2538342012-07-31 05:14:30 +00004187 Diag(LLoc, diag::err_subscript_nonfragile_interface)
4188 << ResultType << BaseExpr->getSourceRange();
4189 return ExprError();
4190 }
John McCall9dd450b2009-09-21 23:43:11 +00004191 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00004192 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00004193 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00004194 VK = LHSExp->getValueKind();
4195 if (VK != VK_RValue)
4196 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00004197
Chris Lattner36d572b2007-07-16 00:14:47 +00004198 // FIXME: need to deal with const...
4199 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00004200 } else if (LHSTy->isArrayType()) {
4201 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00004202 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00004203 // wasn't promoted because of the C90 rule that doesn't
4204 // allow promoting non-lvalue arrays. Warn, then
4205 // force the promotion here.
4206 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4207 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004208 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004209 CK_ArrayToPointerDecay).get();
Eli Friedmanab2784f2009-04-25 23:46:54 +00004210 LHSTy = LHSExp->getType();
4211
4212 BaseExpr = LHSExp;
4213 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004214 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00004215 } else if (RHSTy->isArrayType()) {
4216 // Same as previous, except for 123[f().a] case
4217 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4218 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004219 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004220 CK_ArrayToPointerDecay).get();
Eli Friedmanab2784f2009-04-25 23:46:54 +00004221 RHSTy = RHSExp->getType();
4222
4223 BaseExpr = RHSExp;
4224 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004225 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00004226 } else {
Chris Lattner003af242009-04-25 22:50:55 +00004227 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4228 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004229 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00004230 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00004231 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00004232 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4233 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00004234
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00004235 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00004236 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4237 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00004238 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4239
Douglas Gregorac1fb652009-03-24 19:52:54 +00004240 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00004241 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4242 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00004243 // incomplete types are not object types.
4244 if (ResultType->isFunctionType()) {
4245 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4246 << ResultType << BaseExpr->getSourceRange();
4247 return ExprError();
4248 }
Mike Stump11289f42009-09-09 15:08:12 +00004249
David Blaikiebbafb8a2012-03-11 07:00:24 +00004250 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00004251 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00004252 Diag(LLoc, diag::ext_gnu_subscript_void_type)
4253 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00004254
4255 // C forbids expressions of unqualified void type from being l-values.
4256 // See IsCForbiddenLValueType.
4257 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00004258 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00004259 RequireCompleteType(LLoc, ResultType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004260 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregorac1fb652009-03-24 19:52:54 +00004261 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004262
John McCall4bc41ae2010-11-18 19:01:18 +00004263 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00004264 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00004265
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004266 return new (Context)
4267 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
Chris Lattnere168f762006-11-10 05:29:30 +00004268}
4269
John McCalldadc5752010-08-24 06:29:42 +00004270ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00004271 FunctionDecl *FD,
4272 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00004273 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004274 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00004275 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00004276 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004277 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00004278 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004279 return ExprError();
4280 }
4281
4282 if (Param->hasUninstantiatedDefaultArg()) {
4283 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00004284
Richard Smith505df232012-07-22 23:45:10 +00004285 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4286 Param);
4287
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004288 // Instantiate the expression.
Richard Smith47752e42013-05-03 23:46:09 +00004289 MultiLevelTemplateArgumentList MutiLevelArgList
Craig Topperc3ec1492014-05-26 06:22:03 +00004290 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00004291
Richard Smith80934652012-07-16 01:09:10 +00004292 InstantiatingTemplate Inst(*this, CallLoc, Param,
Richard Smith47752e42013-05-03 23:46:09 +00004293 MutiLevelArgList.getInnermost());
Alp Tokerd4a72d52013-10-08 08:09:04 +00004294 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004295 return ExprError();
Anders Carlsson355933d2009-08-25 03:49:14 +00004296
Nico Weber44887f62010-11-29 18:19:25 +00004297 ExprResult Result;
4298 {
4299 // C++ [dcl.fct.default]p5:
4300 // The names in the [default argument] expression are bound, and
4301 // the semantic constraints are checked, at the point where the
4302 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00004303 ContextRAII SavedContext(*this, FD);
Douglas Gregora86bc002012-02-16 21:36:18 +00004304 LocalInstantiationScope Local(*this);
Richard Smith47752e42013-05-03 23:46:09 +00004305 Result = SubstExpr(UninstExpr, MutiLevelArgList);
Nico Weber44887f62010-11-29 18:19:25 +00004306 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004307 if (Result.isInvalid())
4308 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004309
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004310 // Check the expression as an initializer for the parameter.
4311 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004312 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004313 InitializationKind Kind
4314 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004315 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004316 Expr *ResultE = Result.getAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00004317
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004318 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004319 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004320 if (Result.isInvalid())
4321 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004322
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004323 Expr *Arg = Result.getAs<Expr>();
Richard Smithc406cb72013-01-17 01:17:56 +00004324 CheckCompletedExpr(Arg, Param->getOuterLocStart());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004325 // Build the default argument expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004326 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg);
Anders Carlsson355933d2009-08-25 03:49:14 +00004327 }
4328
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004329 // If the default expression creates temporaries, we need to
4330 // push them to the current stack of expression temporaries so they'll
4331 // be properly destroyed.
4332 // FIXME: We should really be rebuilding the default argument with new
4333 // bound temporaries; see the comment in PR5810.
John McCall28fc7092011-11-10 05:35:25 +00004334 // We don't need to do that with block decls, though, because
4335 // blocks in default argument expression can never capture anything.
4336 if (isa<ExprWithCleanups>(Param->getInit())) {
4337 // Set the "needs cleanups" bit regardless of whether there are
4338 // any explicit objects.
John McCall31168b02011-06-15 23:02:42 +00004339 ExprNeedsCleanups = true;
John McCall28fc7092011-11-10 05:35:25 +00004340
4341 // Append all the objects to the cleanup list. Right now, this
4342 // should always be a no-op, because blocks in default argument
4343 // expressions should never be able to capture anything.
4344 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
4345 "default argument expression has capturing blocks?");
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00004346 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004347
4348 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00004349 // Just mark all of the declarations in this potentially-evaluated expression
4350 // as being "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +00004351 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4352 /*SkipLocalVariables=*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004353 return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004354}
4355
Richard Smith55ce3522012-06-25 20:30:08 +00004356
4357Sema::VariadicCallType
4358Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4359 Expr *Fn) {
4360 if (Proto && Proto->isVariadic()) {
4361 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4362 return VariadicConstructor;
4363 else if (Fn && Fn->getType()->isBlockPointerType())
4364 return VariadicBlock;
4365 else if (FDecl) {
4366 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4367 if (Method->isInstance())
4368 return VariadicMethod;
Richard Trieu9be9c682013-06-22 02:30:38 +00004369 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4370 return VariadicMethod;
Richard Smith55ce3522012-06-25 20:30:08 +00004371 return VariadicFunction;
4372 }
4373 return VariadicDoesNotApply;
4374}
4375
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004376namespace {
4377class FunctionCallCCC : public FunctionCallFilterCCC {
4378public:
4379 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004380 unsigned NumArgs, MemberExpr *ME)
4381 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004382 FunctionName(FuncName) {}
4383
Craig Toppere14c0f82014-03-12 04:55:44 +00004384 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004385 if (!candidate.getCorrectionSpecifier() ||
4386 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4387 return false;
4388 }
4389
4390 return FunctionCallFilterCCC::ValidateCandidate(candidate);
4391 }
4392
4393private:
4394 const IdentifierInfo *const FunctionName;
4395};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004396}
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004397
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004398static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4399 FunctionDecl *FDecl,
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004400 ArrayRef<Expr *> Args) {
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004401 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4402 DeclarationName FuncName = FDecl->getDeclName();
4403 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004404
4405 if (TypoCorrection Corrected = S.CorrectTypo(
4406 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004407 S.getScopeForContext(S.CurContext), nullptr,
4408 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4409 Args.size(), ME),
John Thompson2255f2c2014-04-23 12:57:01 +00004410 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004411 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
4412 if (Corrected.isOverloaded()) {
Richard Smith100b24a2014-04-17 01:52:14 +00004413 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004414 OverloadCandidateSet::iterator Best;
4415 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
4416 CDEnd = Corrected.end();
4417 CD != CDEnd; ++CD) {
4418 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
4419 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4420 OCS);
4421 }
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004422 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004423 case OR_Success:
4424 ND = Best->Function;
4425 Corrected.setCorrectionDecl(ND);
4426 break;
4427 default:
4428 break;
4429 }
4430 }
4431 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
4432 return Corrected;
4433 }
4434 }
4435 }
4436 return TypoCorrection();
4437}
4438
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004439/// ConvertArgumentsForCall - Converts the arguments specified in
4440/// Args/NumArgs to the parameter types of the function FDecl with
4441/// function prototype Proto. Call is the call expression itself, and
4442/// Fn is the function expression. For a C++ member function, this
4443/// routine does not attempt to convert the object argument. Returns
4444/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004445bool
4446Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004447 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004448 const FunctionProtoType *Proto,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004449 ArrayRef<Expr *> Args,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00004450 SourceLocation RParenLoc,
4451 bool IsExecConfig) {
John McCallbebede42011-02-26 05:39:39 +00004452 // Bail out early if calling a builtin with custom typechecking.
John McCallbebede42011-02-26 05:39:39 +00004453 if (FDecl)
4454 if (unsigned ID = FDecl->getBuiltinID())
4455 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4456 return false;
4457
Mike Stump4e1f26a2009-02-19 03:04:26 +00004458 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004459 // assignment, to the types of the corresponding parameter, ...
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004460 unsigned NumParams = Proto->getNumParams();
Douglas Gregorb6b99612009-01-23 21:30:56 +00004461 bool Invalid = false;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004462 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
Peter Collingbourne619a8c72011-10-02 23:49:29 +00004463 unsigned FnKind = Fn->getType()->isBlockPointerType()
4464 ? 1 /* block */
4465 : (IsExecConfig ? 3 /* kernel function (exec config) */
4466 : 0 /* function */);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004467
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004468 // If too few arguments are available (and we don't have default
4469 // arguments for the remaining parameters), don't make the call.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004470 if (Args.size() < NumParams) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004471 if (Args.size() < MinArgs) {
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004472 TypoCorrection TC;
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004473 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004474 unsigned diag_id =
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004475 MinArgs == NumParams && !Proto->isVariadic()
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004476 ? diag::err_typecheck_call_too_few_args_suggest
4477 : diag::err_typecheck_call_too_few_args_at_least_suggest;
Richard Smithf9b15102013-08-17 00:46:16 +00004478 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4479 << static_cast<unsigned>(Args.size())
Kaelyn Uhrain59baee82014-01-28 00:46:47 +00004480 << TC.getCorrectionRange());
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004481 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004482 Diag(RParenLoc,
4483 MinArgs == NumParams && !Proto->isVariadic()
4484 ? diag::err_typecheck_call_too_few_args_one
4485 : diag::err_typecheck_call_too_few_args_at_least_one)
4486 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
Richard Smith10ff50d2012-05-11 05:16:41 +00004487 else
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004488 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4489 ? diag::err_typecheck_call_too_few_args
4490 : diag::err_typecheck_call_too_few_args_at_least)
4491 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4492 << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00004493
4494 // Emit the location of the prototype.
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004495 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00004496 Diag(FDecl->getLocStart(), diag::note_callee_decl)
4497 << FDecl;
4498
4499 return true;
4500 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004501 Call->setNumArgs(Context, NumParams);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004502 }
4503
4504 // If too many are passed and not variadic, error on the extras and drop
4505 // them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004506 if (Args.size() > NumParams) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004507 if (!Proto->isVariadic()) {
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004508 TypoCorrection TC;
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004509 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004510 unsigned diag_id =
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004511 MinArgs == NumParams && !Proto->isVariadic()
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004512 ? diag::err_typecheck_call_too_many_args_suggest
4513 : diag::err_typecheck_call_too_many_args_at_most_suggest;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004514 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
Richard Smithf9b15102013-08-17 00:46:16 +00004515 << static_cast<unsigned>(Args.size())
Kaelyn Uhrain59baee82014-01-28 00:46:47 +00004516 << TC.getCorrectionRange());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004517 } else if (NumParams == 1 && FDecl &&
Richard Smithf9b15102013-08-17 00:46:16 +00004518 FDecl->getParamDecl(0)->getDeclName())
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004519 Diag(Args[NumParams]->getLocStart(),
4520 MinArgs == NumParams
4521 ? diag::err_typecheck_call_too_many_args_one
4522 : diag::err_typecheck_call_too_many_args_at_most_one)
4523 << FnKind << FDecl->getParamDecl(0)
4524 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4525 << SourceRange(Args[NumParams]->getLocStart(),
4526 Args.back()->getLocEnd());
Richard Smithd72da152012-05-15 06:21:54 +00004527 else
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004528 Diag(Args[NumParams]->getLocStart(),
4529 MinArgs == NumParams
4530 ? diag::err_typecheck_call_too_many_args
4531 : diag::err_typecheck_call_too_many_args_at_most)
4532 << FnKind << NumParams << static_cast<unsigned>(Args.size())
4533 << Fn->getSourceRange()
4534 << SourceRange(Args[NumParams]->getLocStart(),
4535 Args.back()->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00004536
4537 // Emit the location of the prototype.
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004538 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00004539 Diag(FDecl->getLocStart(), diag::note_callee_decl)
4540 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00004541
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004542 // This deletes the extra arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004543 Call->setNumArgs(Context, NumParams);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004544 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004545 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004546 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004547 SmallVector<Expr *, 8> AllArgs;
Richard Smith55ce3522012-06-25 20:30:08 +00004548 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4549
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004550 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004551 Proto, 0, Args, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004552 if (Invalid)
4553 return true;
4554 unsigned TotalNumArgs = AllArgs.size();
4555 for (unsigned i = 0; i < TotalNumArgs; ++i)
4556 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004557
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004558 return false;
4559}
Mike Stump4e1f26a2009-02-19 03:04:26 +00004560
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004561bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004562 const FunctionProtoType *Proto,
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004563 unsigned FirstParam, ArrayRef<Expr *> Args,
Craig Topper5603df42013-07-05 19:34:19 +00004564 SmallVectorImpl<Expr *> &AllArgs,
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004565 VariadicCallType CallType, bool AllowExplicit,
Richard Smith6b216962013-02-05 05:52:24 +00004566 bool IsListInitialization) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004567 unsigned NumParams = Proto->getNumParams();
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004568 bool Invalid = false;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004569 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004570 // Continue to check argument types (even if we have too few/many args).
Richard Smithd6f9e732014-05-13 19:56:21 +00004571 for (unsigned i = FirstParam; i < NumParams; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004572 QualType ProtoArgType = Proto->getParamType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004573
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004574 Expr *Arg;
Richard Smithd6f9e732014-05-13 19:56:21 +00004575 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004576 if (ArgIx < Args.size()) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004577 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004578
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004579 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedman3164fb12009-03-22 22:00:50 +00004580 ProtoArgType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004581 diag::err_call_incomplete_argument, Arg))
Eli Friedman3164fb12009-03-22 22:00:50 +00004582 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004583
John McCall4124c492011-10-17 18:40:02 +00004584 // Strip the unbridged-cast placeholder expression off, if applicable.
Fariborz Jahanian48d94c82013-07-31 18:39:08 +00004585 bool CFAudited = false;
John McCall4124c492011-10-17 18:40:02 +00004586 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4587 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4588 (!Param || !Param->hasAttr<CFConsumedAttr>()))
4589 Arg = stripARCUnbridgedCast(Arg);
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004590 else if (getLangOpts().ObjCAutoRefCount &&
4591 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
Fariborz Jahanian48d94c82013-07-31 18:39:08 +00004592 (!Param || !Param->hasAttr<CFConsumedAttr>()))
4593 CFAudited = true;
John McCall4124c492011-10-17 18:40:02 +00004594
Alp Toker9cacbab2014-01-20 20:26:09 +00004595 InitializedEntity Entity =
4596 Param ? InitializedEntity::InitializeParameter(Context, Param,
4597 ProtoArgType)
4598 : InitializedEntity::InitializeParameter(
4599 Context, ProtoArgType, Proto->isParamConsumed(i));
4600
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004601 // Remember that parameter belongs to a CF audited API.
Fariborz Jahanian48d94c82013-07-31 18:39:08 +00004602 if (CFAudited)
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004603 Entity.setParameterCFAudited();
Richard Smithd6f9e732014-05-13 19:56:21 +00004604
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004605 ExprResult ArgE = PerformCopyInitialization(
4606 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004607 if (ArgE.isInvalid())
4608 return true;
4609
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004610 Arg = ArgE.getAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004611 } else {
Richard Smithd6f9e732014-05-13 19:56:21 +00004612 assert(Param && "can't use default arguments without a known callee");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004613
John McCalldadc5752010-08-24 06:29:42 +00004614 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004615 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004616 if (ArgExpr.isInvalid())
4617 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004618
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004619 Arg = ArgExpr.getAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004620 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004621
4622 // Check for array bounds violations for each argument to the call. This
4623 // check only triggers warnings when the argument isn't a more complex Expr
4624 // with its own checking, such as a BinaryOperator.
4625 CheckArrayAccess(Arg);
4626
Peter Collingbournea48f33f2011-10-19 00:16:45 +00004627 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4628 CheckStaticArrayArgument(CallLoc, Param, Arg);
4629
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004630 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004631 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004632
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004633 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004634 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00004635 // Assume that extern "C" functions with variadic arguments that
4636 // return __unknown_anytype aren't *really* variadic.
Alp Toker314cc812014-01-25 16:55:45 +00004637 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4638 FDecl->isExternC()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004639 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
John McCallcc5788c2013-03-04 07:34:02 +00004640 QualType paramType; // ignored
4641 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
John McCall2979fe02011-04-12 00:42:48 +00004642 Invalid |= arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004643 AllArgs.push_back(arg.get());
John McCall2979fe02011-04-12 00:42:48 +00004644 }
4645
4646 // Otherwise do argument promotion, (C99 6.5.2.2p7).
4647 } else {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004648 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00004649 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
4650 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00004651 Invalid |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004652 AllArgs.push_back(Arg.get());
John McCall2979fe02011-04-12 00:42:48 +00004653 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004654 }
Ted Kremenekd41f3462011-09-26 23:36:13 +00004655
4656 // Check for array bounds violations.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004657 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
Ted Kremenekd41f3462011-09-26 23:36:13 +00004658 CheckArrayAccess(Args[i]);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004659 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00004660 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004661}
4662
Peter Collingbournea48f33f2011-10-19 00:16:45 +00004663static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4664 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
Reid Kleckner8a365022013-06-24 17:51:48 +00004665 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4666 TL = DTL.getOriginalLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00004667 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
Peter Collingbournea48f33f2011-10-19 00:16:45 +00004668 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
David Blaikie6adc78e2013-02-18 22:06:02 +00004669 << ATL.getLocalSourceRange();
Peter Collingbournea48f33f2011-10-19 00:16:45 +00004670}
4671
4672/// CheckStaticArrayArgument - If the given argument corresponds to a static
4673/// array parameter, check that it is non-null, and that if it is formed by
4674/// array-to-pointer decay, the underlying array is sufficiently large.
4675///
4676/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4677/// array type derivation, then for each call to the function, the value of the
4678/// corresponding actual argument shall provide access to the first element of
4679/// an array with at least as many elements as specified by the size expression.
4680void
4681Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4682 ParmVarDecl *Param,
4683 const Expr *ArgExpr) {
4684 // Static array parameters are not supported in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004685 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbournea48f33f2011-10-19 00:16:45 +00004686 return;
4687
4688 QualType OrigTy = Param->getOriginalType();
4689
4690 const ArrayType *AT = Context.getAsArrayType(OrigTy);
4691 if (!AT || AT->getSizeModifier() != ArrayType::Static)
4692 return;
4693
4694 if (ArgExpr->isNullPointerConstant(Context,
4695 Expr::NPC_NeverValueDependent)) {
4696 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4697 DiagnoseCalleeStaticArrayParam(*this, Param);
4698 return;
4699 }
4700
4701 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4702 if (!CAT)
4703 return;
4704
4705 const ConstantArrayType *ArgCAT =
4706 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4707 if (!ArgCAT)
4708 return;
4709
4710 if (ArgCAT->getSize().ult(CAT->getSize())) {
4711 Diag(CallLoc, diag::warn_static_array_too_small)
4712 << ArgExpr->getSourceRange()
4713 << (unsigned) ArgCAT->getSize().getZExtValue()
4714 << (unsigned) CAT->getSize().getZExtValue();
4715 DiagnoseCalleeStaticArrayParam(*this, Param);
4716 }
4717}
4718
John McCall2979fe02011-04-12 00:42:48 +00004719/// Given a function expression of unknown-any type, try to rebuild it
4720/// to have a function type.
4721static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4722
John McCall5e77d762013-04-16 07:28:30 +00004723/// Is the given type a placeholder that we need to lower out
4724/// immediately during argument processing?
4725static bool isPlaceholderToRemoveAsArg(QualType type) {
4726 // Placeholders are never sugared.
4727 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4728 if (!placeholder) return false;
4729
4730 switch (placeholder->getKind()) {
4731 // Ignore all the non-placeholder types.
4732#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4733#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4734#include "clang/AST/BuiltinTypes.def"
4735 return false;
4736
4737 // We cannot lower out overload sets; they might validly be resolved
4738 // by the call machinery.
4739 case BuiltinType::Overload:
4740 return false;
4741
4742 // Unbridged casts in ARC can be handled in some call positions and
4743 // should be left in place.
4744 case BuiltinType::ARCUnbridgedCast:
4745 return false;
4746
4747 // Pseudo-objects should be converted as soon as possible.
4748 case BuiltinType::PseudoObject:
4749 return true;
4750
4751 // The debugger mode could theoretically but currently does not try
4752 // to resolve unknown-typed arguments based on known parameter types.
4753 case BuiltinType::UnknownAny:
4754 return true;
4755
4756 // These are always invalid as call arguments and should be reported.
4757 case BuiltinType::BoundMember:
4758 case BuiltinType::BuiltinFn:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004759 case BuiltinType::OMPArraySection:
John McCall5e77d762013-04-16 07:28:30 +00004760 return true;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004761
John McCall5e77d762013-04-16 07:28:30 +00004762 }
4763 llvm_unreachable("bad builtin type kind");
4764}
4765
4766/// Check an argument list for placeholders that we won't try to
4767/// handle later.
4768static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4769 // Apply this processing to all the arguments at once instead of
4770 // dying at the first failure.
4771 bool hasInvalid = false;
4772 for (size_t i = 0, e = args.size(); i != e; i++) {
4773 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4774 ExprResult result = S.CheckPlaceholderExpr(args[i]);
4775 if (result.isInvalid()) hasInvalid = true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004776 else args[i] = result.get();
Kaelyn Takata15867822014-11-21 18:48:04 +00004777 } else if (hasInvalid) {
4778 (void)S.CorrectDelayedTyposInExpr(args[i]);
John McCall5e77d762013-04-16 07:28:30 +00004779 }
4780 }
4781 return hasInvalid;
4782}
4783
Tom Stellardb919c7d2015-03-31 16:39:02 +00004784/// If a builtin function has a pointer argument with no explicit address
4785/// space, than it should be able to accept a pointer to any address
4786/// space as input. In order to do this, we need to replace the
4787/// standard builtin declaration with one that uses the same address space
4788/// as the call.
4789///
4790/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
4791/// it does not contain any pointer arguments without
4792/// an address space qualifer. Otherwise the rewritten
4793/// FunctionDecl is returned.
4794/// TODO: Handle pointer return types.
4795static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
4796 const FunctionDecl *FDecl,
4797 MultiExprArg ArgExprs) {
4798
4799 QualType DeclType = FDecl->getType();
4800 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
4801
4802 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
4803 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
4804 return nullptr;
4805
4806 bool NeedsNewDecl = false;
4807 unsigned i = 0;
4808 SmallVector<QualType, 8> OverloadParams;
4809
4810 for (QualType ParamType : FT->param_types()) {
4811
4812 // Convert array arguments to pointer to simplify type lookup.
4813 Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get();
4814 QualType ArgType = Arg->getType();
4815 if (!ParamType->isPointerType() ||
4816 ParamType.getQualifiers().hasAddressSpace() ||
4817 !ArgType->isPointerType() ||
4818 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
4819 OverloadParams.push_back(ParamType);
4820 continue;
4821 }
4822
4823 NeedsNewDecl = true;
4824 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
4825
4826 QualType PointeeType = ParamType->getPointeeType();
4827 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
4828 OverloadParams.push_back(Context.getPointerType(PointeeType));
4829 }
4830
4831 if (!NeedsNewDecl)
4832 return nullptr;
4833
4834 FunctionProtoType::ExtProtoInfo EPI;
4835 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
4836 OverloadParams, EPI);
4837 DeclContext *Parent = Context.getTranslationUnitDecl();
4838 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
4839 FDecl->getLocation(),
4840 FDecl->getLocation(),
4841 FDecl->getIdentifier(),
4842 OverloadTy,
4843 /*TInfo=*/nullptr,
4844 SC_Extern, false,
4845 /*hasPrototype=*/true);
4846 SmallVector<ParmVarDecl*, 16> Params;
4847 FT = cast<FunctionProtoType>(OverloadTy);
4848 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
4849 QualType ParamType = FT->getParamType(i);
4850 ParmVarDecl *Parm =
4851 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
4852 SourceLocation(), nullptr, ParamType,
4853 /*TInfo=*/nullptr, SC_None, nullptr);
4854 Parm->setScopeInfo(0, i);
4855 Params.push_back(Parm);
4856 }
4857 OverloadDecl->setParams(Params);
4858 return OverloadDecl;
4859}
4860
Steve Naroff83895f72007-09-16 03:34:24 +00004861/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00004862/// This provides the location of the left/right parens and a list of comma
4863/// locations.
John McCalldadc5752010-08-24 06:29:42 +00004864ExprResult
John McCallb268a282010-08-23 23:25:46 +00004865Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004866 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00004867 Expr *ExecConfig, bool IsExecConfig) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004868 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004869 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00004870 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004871 Fn = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00004872
John McCall5e77d762013-04-16 07:28:30 +00004873 if (checkArgsForPlaceholders(*this, ArgExprs))
4874 return ExprError();
4875
David Blaikiebbafb8a2012-03-11 07:00:24 +00004876 if (getLangOpts().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00004877 // If this is a pseudo-destructor expression, build the call immediately.
4878 if (isa<CXXPseudoDestructorExpr>(Fn)) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00004879 if (!ArgExprs.empty()) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00004880 // Pseudo-destructor calls should not have any arguments.
4881 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00004882 << FixItHint::CreateRemoval(
Craig Topperd8040cf2015-10-22 01:56:16 +00004883 SourceRange(ArgExprs.front()->getLocStart(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00004884 ArgExprs.back()->getLocEnd()));
Douglas Gregorad8a3362009-09-04 17:36:40 +00004885 }
Mike Stump11289f42009-09-09 15:08:12 +00004886
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004887 return new (Context)
4888 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
Douglas Gregorad8a3362009-09-04 17:36:40 +00004889 }
John McCall5e77d762013-04-16 07:28:30 +00004890 if (Fn->getType() == Context.PseudoObjectTy) {
4891 ExprResult result = CheckPlaceholderExpr(Fn);
4892 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004893 Fn = result.get();
John McCall5e77d762013-04-16 07:28:30 +00004894 }
Mike Stump11289f42009-09-09 15:08:12 +00004895
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004896 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00004897 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00004898 // FIXME: Will need to cache the results of name lookup (including ADL) in
4899 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004900 bool Dependent = false;
4901 if (Fn->isTypeDependent())
4902 Dependent = true;
Benjamin Kramerc215e762012-08-24 11:54:20 +00004903 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004904 Dependent = true;
4905
Peter Collingbourne41f85462011-02-09 21:07:24 +00004906 if (Dependent) {
4907 if (ExecConfig) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004908 return new (Context) CUDAKernelCallExpr(
Benjamin Kramerc215e762012-08-24 11:54:20 +00004909 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004910 Context.DependentTy, VK_RValue, RParenLoc);
Peter Collingbourne41f85462011-02-09 21:07:24 +00004911 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004912 return new (Context) CallExpr(
4913 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
Peter Collingbourne41f85462011-02-09 21:07:24 +00004914 }
4915 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004916
4917 // Determine whether this is a call to an object (C++ [over.call.object]).
4918 if (Fn->getType()->isRecordType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004919 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
4920 RParenLoc);
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004921
John McCall2979fe02011-04-12 00:42:48 +00004922 if (Fn->getType() == Context.UnknownAnyTy) {
4923 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4924 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004925 Fn = result.get();
John McCall2979fe02011-04-12 00:42:48 +00004926 }
4927
John McCall0009fcc2011-04-26 20:42:42 +00004928 if (Fn->getType() == Context.BoundMemberTy) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004929 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00004930 }
John McCall0009fcc2011-04-26 20:42:42 +00004931 }
John McCall10eae182009-11-30 22:42:35 +00004932
John McCall0009fcc2011-04-26 20:42:42 +00004933 // Check for overloaded calls. This can happen even in C due to extensions.
4934 if (Fn->getType() == Context.OverloadTy) {
4935 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4936
Douglas Gregorcda22702011-10-13 18:10:35 +00004937 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregorf4a06c22011-10-13 18:26:27 +00004938 if (!find.HasFormOfMemberPointer) {
John McCall0009fcc2011-04-26 20:42:42 +00004939 OverloadExpr *ovl = find.Expression;
4940 if (isa<UnresolvedLookupExpr>(ovl)) {
4941 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004942 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
4943 RParenLoc, ExecConfig);
John McCall0009fcc2011-04-26 20:42:42 +00004944 } else {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004945 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
4946 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00004947 }
4948 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004949 }
4950
Douglas Gregore254f902009-02-04 00:32:51 +00004951 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregord8fb1e32011-12-01 01:37:36 +00004952 if (Fn->getType() == Context.UnknownAnyTy) {
4953 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4954 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004955 Fn = result.get();
Douglas Gregord8fb1e32011-12-01 01:37:36 +00004956 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004957
Eli Friedmane14b1992009-12-26 03:35:45 +00004958 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00004959
Craig Topperc3ec1492014-05-26 06:22:03 +00004960 NamedDecl *NDecl = nullptr;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00004961 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4962 if (UnOp->getOpcode() == UO_AddrOf)
4963 NakedFn = UnOp->getSubExpr()->IgnoreParens();
Tom Stellardb919c7d2015-03-31 16:39:02 +00004964
4965 if (isa<DeclRefExpr>(NakedFn)) {
John McCall57500772009-12-16 12:17:52 +00004966 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
Tom Stellardb919c7d2015-03-31 16:39:02 +00004967
4968 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
4969 if (FDecl && FDecl->getBuiltinID()) {
4970 // Rewrite the function decl for this builtin by replacing paramaters
4971 // with no explicit address space with the address space of the arguments
4972 // in ArgExprs.
4973 if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
4974 NDecl = FDecl;
4975 Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(),
4976 SourceLocation(), FDecl, false,
4977 SourceLocation(), FDecl->getType(),
4978 Fn->getValueKind(), FDecl);
4979 }
4980 }
4981 } else if (isa<MemberExpr>(NakedFn))
John McCall0009fcc2011-04-26 20:42:42 +00004982 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00004983
Nick Lewycky35a6ef42014-01-11 02:50:57 +00004984 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
4985 if (FD->hasAttr<EnableIfAttr>()) {
4986 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
4987 Diag(Fn->getLocStart(),
4988 isa<CXXMethodDecl>(FD) ?
4989 diag::err_ovl_no_viable_member_function_in_call :
4990 diag::err_ovl_no_viable_function_in_call)
4991 << FD << FD->getSourceRange();
4992 Diag(FD->getLocation(),
4993 diag::note_ovl_candidate_disabled_by_enable_if_attr)
4994 << Attr->getCond()->getSourceRange() << Attr->getMessage();
4995 }
4996 }
4997 }
4998
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004999 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5000 ExecConfig, IsExecConfig);
Peter Collingbourne41f85462011-02-09 21:07:24 +00005001}
5002
Tanya Lattner55808c12011-06-04 00:47:47 +00005003/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5004///
5005/// __builtin_astype( value, dst type )
5006///
Richard Trieuba63ce62011-09-09 01:45:06 +00005007ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00005008 SourceLocation BuiltinLoc,
5009 SourceLocation RParenLoc) {
5010 ExprValueKind VK = VK_RValue;
5011 ExprObjectKind OK = OK_Ordinary;
Richard Trieuba63ce62011-09-09 01:45:06 +00005012 QualType DstTy = GetTypeFromParser(ParsedDestTy);
5013 QualType SrcTy = E->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00005014 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5015 return ExprError(Diag(BuiltinLoc,
5016 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00005017 << DstTy
5018 << SrcTy
Richard Trieuba63ce62011-09-09 01:45:06 +00005019 << E->getSourceRange());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005020 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Tanya Lattner55808c12011-06-04 00:47:47 +00005021}
5022
Hal Finkelc4d7c822013-09-18 03:29:45 +00005023/// ActOnConvertVectorExpr - create a new convert-vector expression from the
5024/// provided arguments.
5025///
5026/// __builtin_convertvector( value, dst type )
5027///
5028ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5029 SourceLocation BuiltinLoc,
5030 SourceLocation RParenLoc) {
5031 TypeSourceInfo *TInfo;
5032 GetTypeFromParser(ParsedDestTy, &TInfo);
5033 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5034}
5035
John McCall57500772009-12-16 12:17:52 +00005036/// BuildResolvedCallExpr - Build a call to a resolved expression,
5037/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00005038/// unary-convert to an expression of function-pointer or
5039/// block-pointer type.
5040///
5041/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00005042ExprResult
John McCall2d74de92009-12-01 22:10:20 +00005043Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5044 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005045 ArrayRef<Expr *> Args,
Peter Collingbourne41f85462011-02-09 21:07:24 +00005046 SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00005047 Expr *Config, bool IsExecConfig) {
John McCall2d74de92009-12-01 22:10:20 +00005048 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
Eli Friedman34866c72012-08-31 00:14:07 +00005049 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
John McCall2d74de92009-12-01 22:10:20 +00005050
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005051 // Promote the function operand.
Eli Friedman34866c72012-08-31 00:14:07 +00005052 // We special-case function promotion here because we only allow promoting
5053 // builtin functions to function pointers in the callee of a call.
5054 ExprResult Result;
5055 if (BuiltinID &&
5056 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5057 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005058 CK_BuiltinFnToFnPtr).get();
Eli Friedman34866c72012-08-31 00:14:07 +00005059 } else {
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +00005060 Result = CallExprUnaryConversions(Fn);
Eli Friedman34866c72012-08-31 00:14:07 +00005061 }
John Wiegley01296292011-04-08 18:41:53 +00005062 if (Result.isInvalid())
5063 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005064 Fn = Result.get();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005065
Chris Lattner08464942007-12-28 05:29:59 +00005066 // Make the call expr early, before semantic checks. This guarantees cleanup
5067 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00005068 CallExpr *TheCall;
Eric Christopher13586ab2012-05-30 01:14:28 +00005069 if (Config)
Peter Collingbourne41f85462011-02-09 21:07:24 +00005070 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005071 cast<CallExpr>(Config), Args,
5072 Context.BoolTy, VK_RValue,
Peter Collingbourne41f85462011-02-09 21:07:24 +00005073 RParenLoc);
Eric Christopher13586ab2012-05-30 01:14:28 +00005074 else
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005075 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5076 VK_RValue, RParenLoc);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005077
Kaelyn Takata72d16a52015-06-23 19:13:17 +00005078 if (!getLangOpts().CPlusPlus) {
5079 // C cannot always handle TypoExpr nodes in builtin calls and direct
5080 // function calls as their argument checking don't necessarily handle
5081 // dependent types properly, so make sure any TypoExprs have been
5082 // dealt with.
5083 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5084 if (!Result.isUsable()) return ExprError();
5085 TheCall = dyn_cast<CallExpr>(Result.get());
5086 if (!TheCall) return Result;
Craig Topper882bc8d2015-11-07 06:16:16 +00005087 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
Kaelyn Takatae53f0f92015-06-23 18:42:21 +00005088 }
John McCallbebede42011-02-26 05:39:39 +00005089
Kaelyn Takata72d16a52015-06-23 19:13:17 +00005090 // Bail out early if calling a builtin with custom typechecking.
5091 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5092 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5093
John McCall31996342011-04-07 08:22:57 +00005094 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005095 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00005096 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005097 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5098 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00005099 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Craig Topperc3ec1492014-05-26 06:22:03 +00005100 if (!FuncT)
John McCallbebede42011-02-26 05:39:39 +00005101 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5102 << Fn->getType() << Fn->getSourceRange());
5103 } else if (const BlockPointerType *BPT =
5104 Fn->getType()->getAs<BlockPointerType>()) {
5105 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5106 } else {
John McCall31996342011-04-07 08:22:57 +00005107 // Handle calls to expressions of unknown-any type.
5108 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00005109 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00005110 if (rewrite.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005111 Fn = rewrite.get();
John McCall39439732011-04-09 22:50:59 +00005112 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00005113 goto retry;
5114 }
5115
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005116 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5117 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00005118 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005119
David Blaikiebbafb8a2012-03-11 07:00:24 +00005120 if (getLangOpts().CUDA) {
Peter Collingbourne4b66c472011-02-23 01:53:29 +00005121 if (Config) {
5122 // CUDA: Kernel calls must be to global functions
5123 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5124 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5125 << FDecl->getName() << Fn->getSourceRange());
5126
5127 // CUDA: Kernel function must have 'void' return type
Alp Toker314cc812014-01-25 16:55:45 +00005128 if (!FuncT->getReturnType()->isVoidType())
Peter Collingbourne4b66c472011-02-23 01:53:29 +00005129 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5130 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne34a20b02011-10-02 23:49:15 +00005131 } else {
5132 // CUDA: Calls to global functions must be configured
5133 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5134 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5135 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne4b66c472011-02-23 01:53:29 +00005136 }
5137 }
5138
Eli Friedman3164fb12009-03-22 22:00:50 +00005139 // Check for a valid return type
Alp Toker314cc812014-01-25 16:55:45 +00005140 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00005141 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00005142 return ExprError();
5143
Chris Lattner08464942007-12-28 05:29:59 +00005144 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00005145 TheCall->setType(FuncT->getCallResultType(Context));
Alp Toker314cc812014-01-25 16:55:45 +00005146 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005147
Richard Smith55ce3522012-06-25 20:30:08 +00005148 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5149 if (Proto) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005150 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5151 IsExecConfig))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005152 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00005153 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005154 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005155
Douglas Gregord8e97de2009-04-02 15:37:10 +00005156 if (FDecl) {
5157 // Check if we have too few/too many template arguments, based
5158 // on our knowledge of the function definition.
Craig Topperc3ec1492014-05-26 06:22:03 +00005159 const FunctionDecl *Def = nullptr;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005160 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
Richard Smith55ce3522012-06-25 20:30:08 +00005161 Proto = Def->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005162 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00005163 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005164 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00005165 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00005166
5167 // If the function we're calling isn't a function prototype, but we have
5168 // a function prototype from a prior declaratiom, use that prototype.
5169 if (!FDecl->hasPrototype())
5170 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00005171 }
5172
Steve Naroff0b661582007-08-28 23:30:39 +00005173 // Promote the arguments (C99 6.5.2.2p6).
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005174 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Chris Lattner08464942007-12-28 05:29:59 +00005175 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00005176
Alp Toker9cacbab2014-01-20 20:26:09 +00005177 if (Proto && i < Proto->getNumParams()) {
5178 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5179 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005180 ExprResult ArgE =
5181 PerformCopyInitialization(Entity, SourceLocation(), Arg);
Douglas Gregor8e09a722010-10-25 20:39:23 +00005182 if (ArgE.isInvalid())
5183 return true;
5184
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005185 Arg = ArgE.getAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00005186
5187 } else {
John Wiegley01296292011-04-08 18:41:53 +00005188 ExprResult ArgE = DefaultArgumentPromotion(Arg);
5189
5190 if (ArgE.isInvalid())
5191 return true;
5192
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005193 Arg = ArgE.getAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00005194 }
5195
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005196 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor83025412010-10-26 05:45:40 +00005197 Arg->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005198 diag::err_call_incomplete_argument, Arg))
Douglas Gregor83025412010-10-26 05:45:40 +00005199 return ExprError();
5200
Chris Lattner08464942007-12-28 05:29:59 +00005201 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00005202 }
Steve Naroffae4143e2007-04-26 20:39:23 +00005203 }
Chris Lattner08464942007-12-28 05:29:59 +00005204
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005205 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5206 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005207 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5208 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005209
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00005210 // Check for sentinels
5211 if (NDecl)
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005212 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
Mike Stump11289f42009-09-09 15:08:12 +00005213
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005214 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005215 if (FDecl) {
Richard Smith55ce3522012-06-25 20:30:08 +00005216 if (CheckFunctionCall(FDecl, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005217 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00005218
John McCallbebede42011-02-26 05:39:39 +00005219 if (BuiltinID)
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00005220 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005221 } else if (NDecl) {
Richard Trieu664c4c62013-06-20 21:03:13 +00005222 if (CheckPointerCall(NDecl, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005223 return ExprError();
Richard Trieu41bc0992013-06-22 00:20:41 +00005224 } else {
5225 if (CheckOtherCall(TheCall, Proto))
5226 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005227 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005228
John McCallb268a282010-08-23 23:25:46 +00005229 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00005230}
5231
John McCalldadc5752010-08-24 06:29:42 +00005232ExprResult
John McCallba7bf592010-08-24 05:47:05 +00005233Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00005234 SourceLocation RParenLoc, Expr *InitExpr) {
David Blaikie7d170102013-05-15 07:37:26 +00005235 assert(Ty && "ActOnCompoundLiteral(): missing type");
Davide Italiano99219622015-08-19 02:21:12 +00005236 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00005237
5238 TypeSourceInfo *TInfo;
5239 QualType literalType = GetTypeFromParser(Ty, &TInfo);
5240 if (!TInfo)
5241 TInfo = Context.getTrivialTypeSourceInfo(literalType);
5242
John McCallb268a282010-08-23 23:25:46 +00005243 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00005244}
5245
John McCalldadc5752010-08-24 06:29:42 +00005246ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00005247Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00005248 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00005249 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00005250
Eli Friedman37a186d2008-05-20 05:22:08 +00005251 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00005252 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005253 diag::err_illegal_decl_array_incomplete_type,
5254 SourceRange(LParenLoc,
5255 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00005256 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00005257 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005258 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuba63ce62011-09-09 01:45:06 +00005259 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00005260 } else if (!literalType->isDependentType() &&
5261 RequireCompleteType(LParenLoc, literalType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005262 diag::err_typecheck_decl_incomplete_type,
5263 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00005264 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00005265
Douglas Gregor85dabae2009-12-16 01:38:02 +00005266 InitializedEntity Entity
Jordan Rose6c0505e2013-05-06 16:48:12 +00005267 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005268 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00005269 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl0501c632012-02-12 16:37:36 +00005270 SourceRange(LParenLoc, RParenLoc),
5271 /*InitList=*/true);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005272 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005273 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5274 &literalType);
Eli Friedmana553d4a2009-12-22 02:35:53 +00005275 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005276 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00005277 LiteralExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00005278
Craig Topperc3ec1492014-05-26 06:22:03 +00005279 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
Eli Friedman4a962f02013-10-01 00:28:29 +00005280 if (isFileScope &&
5281 !LiteralExpr->isTypeDependent() &&
5282 !LiteralExpr->isValueDependent() &&
5283 !literalType->isDependentType()) { // 6.5.2.5p3
Richard Trieuba63ce62011-09-09 01:45:06 +00005284 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00005285 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00005286 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00005287
John McCall7decc9e2010-11-18 06:31:45 +00005288 // In C, compound literals are l-values for some reason.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005289 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00005290
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00005291 return MaybeBindToTemporary(
5292 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuba63ce62011-09-09 01:45:06 +00005293 VK, LiteralExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00005294}
5295
John McCalldadc5752010-08-24 06:29:42 +00005296ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00005297Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb5d49352009-01-19 22:31:54 +00005298 SourceLocation RBraceLoc) {
John McCall526ab472011-10-25 17:37:35 +00005299 // Immediately handle non-overload placeholders. Overloads can be
5300 // resolved contextually, but everything else here can't.
Benjamin Kramerc215e762012-08-24 11:54:20 +00005301 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5302 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5303 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
John McCall526ab472011-10-25 17:37:35 +00005304
5305 // Ignore failures; dropping the entire initializer list because
5306 // of one failure would be terrible for indexing/etc.
5307 if (result.isInvalid()) continue;
5308
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005309 InitArgList[I] = result.get();
John McCall526ab472011-10-25 17:37:35 +00005310 }
5311 }
5312
Steve Naroff30d242c2007-09-15 18:49:24 +00005313 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00005314 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005315
Benjamin Kramerc215e762012-08-24 11:54:20 +00005316 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5317 RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005318 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005319 return E;
Steve Narofffbd09832007-07-19 01:06:55 +00005320}
5321
John McCallcd78e802011-09-10 01:16:55 +00005322/// Do an explicit extend of the given block pointer if we're in ARC.
Douglas Gregore83b9562015-07-07 03:57:53 +00005323void Sema::maybeExtendBlockObject(ExprResult &E) {
John McCallcd78e802011-09-10 01:16:55 +00005324 assert(E.get()->getType()->isBlockPointerType());
5325 assert(E.get()->isRValue());
5326
5327 // Only do this in an r-value context.
Douglas Gregore83b9562015-07-07 03:57:53 +00005328 if (!getLangOpts().ObjCAutoRefCount) return;
John McCallcd78e802011-09-10 01:16:55 +00005329
Douglas Gregore83b9562015-07-07 03:57:53 +00005330 E = ImplicitCastExpr::Create(Context, E.get()->getType(),
John McCall2d637d22011-09-10 06:18:15 +00005331 CK_ARCExtendBlockObject, E.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005332 /*base path*/ nullptr, VK_RValue);
Douglas Gregore83b9562015-07-07 03:57:53 +00005333 ExprNeedsCleanups = true;
John McCallcd78e802011-09-10 01:16:55 +00005334}
5335
5336/// Prepare a conversion of the given expression to an ObjC object
5337/// pointer type.
5338CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5339 QualType type = E.get()->getType();
5340 if (type->isObjCObjectPointerType()) {
5341 return CK_BitCast;
5342 } else if (type->isBlockPointerType()) {
Douglas Gregore83b9562015-07-07 03:57:53 +00005343 maybeExtendBlockObject(E);
John McCallcd78e802011-09-10 01:16:55 +00005344 return CK_BlockPointerToObjCPointerCast;
5345 } else {
5346 assert(type->isPointerType());
5347 return CK_CPointerToObjCPointerCast;
5348 }
5349}
5350
John McCalld7646252010-11-14 08:17:51 +00005351/// Prepares for a scalar cast, performing all the necessary stages
5352/// except the final cast and returning the kind required.
John McCall9776e432011-10-06 23:25:11 +00005353CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00005354 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5355 // Also, callers should have filtered out the invalid cases with
5356 // pointers. Everything else should be possible.
5357
John Wiegley01296292011-04-08 18:41:53 +00005358 QualType SrcTy = Src.get()->getType();
John McCall9776e432011-10-06 23:25:11 +00005359 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00005360 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00005361
John McCall9320b872011-09-09 05:25:32 +00005362 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00005363 case Type::STK_MemberPointer:
5364 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00005365
John McCall9320b872011-09-09 05:25:32 +00005366 case Type::STK_CPointer:
5367 case Type::STK_BlockPointer:
5368 case Type::STK_ObjCObjectPointer:
John McCall8cb679e2010-11-15 09:13:47 +00005369 switch (DestTy->getScalarTypeKind()) {
David Tweede1468322013-12-11 13:39:46 +00005370 case Type::STK_CPointer: {
5371 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5372 unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5373 if (SrcAS != DestAS)
5374 return CK_AddressSpaceConversion;
John McCall9320b872011-09-09 05:25:32 +00005375 return CK_BitCast;
David Tweede1468322013-12-11 13:39:46 +00005376 }
John McCall9320b872011-09-09 05:25:32 +00005377 case Type::STK_BlockPointer:
5378 return (SrcKind == Type::STK_BlockPointer
5379 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5380 case Type::STK_ObjCObjectPointer:
5381 if (SrcKind == Type::STK_ObjCObjectPointer)
5382 return CK_BitCast;
David Blaikie8a40f702012-01-17 06:56:22 +00005383 if (SrcKind == Type::STK_CPointer)
John McCall9320b872011-09-09 05:25:32 +00005384 return CK_CPointerToObjCPointerCast;
Douglas Gregore83b9562015-07-07 03:57:53 +00005385 maybeExtendBlockObject(Src);
David Blaikie8a40f702012-01-17 06:56:22 +00005386 return CK_BlockPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00005387 case Type::STK_Bool:
5388 return CK_PointerToBoolean;
5389 case Type::STK_Integral:
5390 return CK_PointerToIntegral;
5391 case Type::STK_Floating:
5392 case Type::STK_FloatingComplex:
5393 case Type::STK_IntegralComplex:
5394 case Type::STK_MemberPointer:
5395 llvm_unreachable("illegal cast from pointer");
5396 }
David Blaikie8a40f702012-01-17 06:56:22 +00005397 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005398
John McCall8cb679e2010-11-15 09:13:47 +00005399 case Type::STK_Bool: // casting from bool is like casting from an integer
5400 case Type::STK_Integral:
5401 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00005402 case Type::STK_CPointer:
5403 case Type::STK_ObjCObjectPointer:
5404 case Type::STK_BlockPointer:
John McCall9776e432011-10-06 23:25:11 +00005405 if (Src.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005406 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00005407 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00005408 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005409 case Type::STK_Bool:
5410 return CK_IntegralToBoolean;
5411 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00005412 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00005413 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00005414 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00005415 case Type::STK_IntegralComplex:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005416 Src = ImpCastExprToType(Src.get(),
George Burgess IV45461812015-10-11 20:13:20 +00005417 DestTy->castAs<ComplexType>()->getElementType(),
5418 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00005419 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005420 case Type::STK_FloatingComplex:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005421 Src = ImpCastExprToType(Src.get(),
George Burgess IV45461812015-10-11 20:13:20 +00005422 DestTy->castAs<ComplexType>()->getElementType(),
5423 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00005424 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005425 case Type::STK_MemberPointer:
5426 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005427 }
David Blaikie8a40f702012-01-17 06:56:22 +00005428 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005429
John McCall8cb679e2010-11-15 09:13:47 +00005430 case Type::STK_Floating:
5431 switch (DestTy->getScalarTypeKind()) {
5432 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00005433 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00005434 case Type::STK_Bool:
5435 return CK_FloatingToBoolean;
5436 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00005437 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00005438 case Type::STK_FloatingComplex:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005439 Src = ImpCastExprToType(Src.get(),
John McCall9776e432011-10-06 23:25:11 +00005440 DestTy->castAs<ComplexType>()->getElementType(),
5441 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00005442 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005443 case Type::STK_IntegralComplex:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005444 Src = ImpCastExprToType(Src.get(),
John McCall9776e432011-10-06 23:25:11 +00005445 DestTy->castAs<ComplexType>()->getElementType(),
5446 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00005447 return CK_IntegralRealToComplex;
John McCall9320b872011-09-09 05:25:32 +00005448 case Type::STK_CPointer:
5449 case Type::STK_ObjCObjectPointer:
5450 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00005451 llvm_unreachable("valid float->pointer cast?");
5452 case Type::STK_MemberPointer:
5453 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005454 }
David Blaikie8a40f702012-01-17 06:56:22 +00005455 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00005456
John McCall8cb679e2010-11-15 09:13:47 +00005457 case Type::STK_FloatingComplex:
5458 switch (DestTy->getScalarTypeKind()) {
5459 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00005460 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00005461 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00005462 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00005463 case Type::STK_Floating: {
John McCall9776e432011-10-06 23:25:11 +00005464 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5465 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00005466 return CK_FloatingComplexToReal;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005467 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00005468 return CK_FloatingCast;
5469 }
John McCall8cb679e2010-11-15 09:13:47 +00005470 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00005471 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00005472 case Type::STK_Integral:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005473 Src = ImpCastExprToType(Src.get(),
John McCall9776e432011-10-06 23:25:11 +00005474 SrcTy->castAs<ComplexType>()->getElementType(),
5475 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00005476 return CK_FloatingToIntegral;
John McCall9320b872011-09-09 05:25:32 +00005477 case Type::STK_CPointer:
5478 case Type::STK_ObjCObjectPointer:
5479 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00005480 llvm_unreachable("valid complex float->pointer cast?");
5481 case Type::STK_MemberPointer:
5482 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005483 }
David Blaikie8a40f702012-01-17 06:56:22 +00005484 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00005485
John McCall8cb679e2010-11-15 09:13:47 +00005486 case Type::STK_IntegralComplex:
5487 switch (DestTy->getScalarTypeKind()) {
5488 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00005489 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005490 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00005491 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00005492 case Type::STK_Integral: {
John McCall9776e432011-10-06 23:25:11 +00005493 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5494 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00005495 return CK_IntegralComplexToReal;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005496 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00005497 return CK_IntegralCast;
5498 }
John McCall8cb679e2010-11-15 09:13:47 +00005499 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00005500 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00005501 case Type::STK_Floating:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005502 Src = ImpCastExprToType(Src.get(),
John McCall9776e432011-10-06 23:25:11 +00005503 SrcTy->castAs<ComplexType>()->getElementType(),
5504 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00005505 return CK_IntegralToFloating;
John McCall9320b872011-09-09 05:25:32 +00005506 case Type::STK_CPointer:
5507 case Type::STK_ObjCObjectPointer:
5508 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00005509 llvm_unreachable("valid complex int->pointer cast?");
5510 case Type::STK_MemberPointer:
5511 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005512 }
David Blaikie8a40f702012-01-17 06:56:22 +00005513 llvm_unreachable("Should have returned before this");
Anders Carlsson094c4592009-10-18 18:12:03 +00005514 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005515
John McCalld7646252010-11-14 08:17:51 +00005516 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson094c4592009-10-18 18:12:03 +00005517}
5518
Fariborz Jahanian328a7c42014-03-06 22:47:09 +00005519static bool breakDownVectorType(QualType type, uint64_t &len,
5520 QualType &eltType) {
5521 // Vectors are simple.
5522 if (const VectorType *vecType = type->getAs<VectorType>()) {
5523 len = vecType->getNumElements();
5524 eltType = vecType->getElementType();
5525 assert(eltType->isScalarType());
5526 return true;
5527 }
5528
5529 // We allow lax conversion to and from non-vector types, but only if
5530 // they're real types (i.e. non-complex, non-pointer scalar types).
5531 if (!type->isRealType()) return false;
5532
5533 len = 1;
5534 eltType = type;
5535 return true;
5536}
5537
John McCall1c78f082015-07-23 23:54:07 +00005538/// Are the two types lax-compatible vector types? That is, given
5539/// that one of them is a vector, do they have equal storage sizes,
5540/// where the storage size is the number of elements times the element
5541/// size?
5542///
5543/// This will also return false if either of the types is neither a
5544/// vector nor a real type.
5545bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5546 assert(destTy->isVectorType() || srcTy->isVectorType());
Stephen Canonca8eefd2015-09-15 00:21:56 +00005547
5548 // Disallow lax conversions between scalars and ExtVectors (these
5549 // conversions are allowed for other vector types because common headers
5550 // depend on them). Most scalar OP ExtVector cases are handled by the
5551 // splat path anyway, which does what we want (convert, not bitcast).
5552 // What this rules out for ExtVectors is crazy things like char4*float.
5553 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5554 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
John McCall1c78f082015-07-23 23:54:07 +00005555
Fariborz Jahanian328a7c42014-03-06 22:47:09 +00005556 uint64_t srcLen, destLen;
Vedant Kumar55c21442015-10-09 01:47:26 +00005557 QualType srcEltTy, destEltTy;
5558 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5559 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
Fariborz Jahanian328a7c42014-03-06 22:47:09 +00005560
5561 // ASTContext::getTypeSize will return the size rounded up to a
5562 // power of 2, so instead of using that, we need to use the raw
5563 // element size multiplied by the element count.
Vedant Kumar55c21442015-10-09 01:47:26 +00005564 uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5565 uint64_t destEltSize = Context.getTypeSize(destEltTy);
Fariborz Jahanian328a7c42014-03-06 22:47:09 +00005566
5567 return (srcLen * srcEltSize == destLen * destEltSize);
5568}
5569
John McCall1c78f082015-07-23 23:54:07 +00005570/// Is this a legal conversion between two types, one of which is
5571/// known to be a vector type?
Fariborz Jahanian328a7c42014-03-06 22:47:09 +00005572bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5573 assert(destTy->isVectorType() || srcTy->isVectorType());
5574
5575 if (!Context.getLangOpts().LaxVectorConversions)
5576 return false;
John McCall1c78f082015-07-23 23:54:07 +00005577 return areLaxCompatibleVectorTypes(srcTy, destTy);
Fariborz Jahanian328a7c42014-03-06 22:47:09 +00005578}
5579
Anders Carlsson525b76b2009-10-16 02:48:28 +00005580bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00005581 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00005582 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005583
John McCall1c78f082015-07-23 23:54:07 +00005584 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5585 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
Anders Carlssonde71adf2007-11-27 05:51:55 +00005586 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00005587 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00005588 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00005589 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005590 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005591 } else
5592 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00005593 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005594 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005595
John McCalle3027922010-08-25 11:45:40 +00005596 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005597 return false;
5598}
5599
John Wiegley01296292011-04-08 18:41:53 +00005600ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5601 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00005602 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005603
Anders Carlsson43d70f82009-10-16 05:23:41 +00005604 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005605
Nate Begemanc8961a42009-06-27 22:05:55 +00005606 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5607 // an ExtVectorType.
Tobias Grosser766bcc22011-09-22 13:03:14 +00005608 // In OpenCL, casts between vectors of different types are not allowed.
5609 // (See OpenCL 6.2).
Nate Begemanc69b7402009-06-26 00:50:28 +00005610 if (SrcTy->isVectorType()) {
John McCall1c78f082015-07-23 23:54:07 +00005611 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
David Blaikiebbafb8a2012-03-11 07:00:24 +00005612 || (getLangOpts().OpenCL &&
Tobias Grosser766bcc22011-09-22 13:03:14 +00005613 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005614 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00005615 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00005616 return ExprError();
5617 }
John McCalle3027922010-08-25 11:45:40 +00005618 Kind = CK_BitCast;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005619 return CastExpr;
Nate Begemanc69b7402009-06-26 00:50:28 +00005620 }
5621
Nate Begemanbd956c42009-06-28 02:36:38 +00005622 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00005623 // conversion will take place first from scalar to elt type, and then
5624 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00005625 if (SrcTy->isPointerType())
5626 return Diag(R.getBegin(),
5627 diag::err_invalid_conversion_between_vector_and_scalar)
5628 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00005629
5630 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005631 ExprResult CastExprRes = CastExpr;
John McCall9776e432011-10-06 23:25:11 +00005632 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley01296292011-04-08 18:41:53 +00005633 if (CastExprRes.isInvalid())
5634 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005635 CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005636
John McCalle3027922010-08-25 11:45:40 +00005637 Kind = CK_VectorSplat;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005638 return CastExpr;
Nate Begemanc69b7402009-06-26 00:50:28 +00005639}
5640
John McCalldadc5752010-08-24 06:29:42 +00005641ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00005642Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5643 Declarator &D, ParsedType &Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00005644 SourceLocation RParenLoc, Expr *CastExpr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005645 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00005646 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00005647
Richard Trieuba63ce62011-09-09 01:45:06 +00005648 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00005649 if (D.isInvalidType())
5650 return ExprError();
5651
David Blaikiebbafb8a2012-03-11 07:00:24 +00005652 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00005653 // Check that there are no default arguments (C++ only).
5654 CheckExtraCXXDefaultArguments(D);
Kaelyn Takata13da33f2014-11-24 21:46:59 +00005655 } else {
5656 // Make sure any TypoExprs have been dealt with.
5657 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
5658 if (!Res.isUsable())
5659 return ExprError();
5660 CastExpr = Res.get();
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00005661 }
5662
John McCall42856de2011-10-01 05:17:03 +00005663 checkUnusedDeclAttributes(D);
5664
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00005665 QualType castType = castTInfo->getType();
5666 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00005667
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005668 bool isVectorLiteral = false;
5669
5670 // Check for an altivec or OpenCL literal,
5671 // i.e. all the elements are integer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00005672 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5673 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00005674 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
Tobias Grosser0a3a22f2011-09-21 18:28:29 +00005675 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005676 if (PLE && PLE->getNumExprs() == 0) {
5677 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5678 return ExprError();
5679 }
5680 if (PE || PLE->getNumExprs() == 1) {
5681 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5682 if (!E->getType()->isVectorType())
5683 isVectorLiteral = true;
5684 }
5685 else
5686 isVectorLiteral = true;
5687 }
5688
5689 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5690 // then handle it as such.
5691 if (isVectorLiteral)
Richard Trieuba63ce62011-09-09 01:45:06 +00005692 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005693
Nate Begeman5ec4b312009-08-10 23:49:36 +00005694 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005695 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5696 // sequence of BinOp comma operators.
Richard Trieuba63ce62011-09-09 01:45:06 +00005697 if (isa<ParenListExpr>(CastExpr)) {
5698 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005699 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005700 CastExpr = Result.get();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005701 }
John McCallebe54742010-01-15 18:56:44 +00005702
Alp Toker15ab3732013-12-12 12:47:48 +00005703 if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
5704 !getSourceManager().isInSystemMacro(LParenLoc))
5705 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00005706
5707 CheckTollFreeBridgeCast(castType, CastExpr);
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00005708
5709 CheckObjCBridgeRelatedCast(castType, CastExpr);
5710
Richard Trieuba63ce62011-09-09 01:45:06 +00005711 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallebe54742010-01-15 18:56:44 +00005712}
5713
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005714ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5715 SourceLocation RParenLoc, Expr *E,
5716 TypeSourceInfo *TInfo) {
5717 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5718 "Expected paren or paren list expression");
5719
5720 Expr **exprs;
5721 unsigned numExprs;
5722 Expr *subExpr;
Richard Smith9ca91012013-02-05 05:55:57 +00005723 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005724 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
Richard Smith9ca91012013-02-05 05:55:57 +00005725 LiteralLParenLoc = PE->getLParenLoc();
5726 LiteralRParenLoc = PE->getRParenLoc();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005727 exprs = PE->getExprs();
5728 numExprs = PE->getNumExprs();
Richard Smith9ca91012013-02-05 05:55:57 +00005729 } else { // isa<ParenExpr> by assertion at function entrance
5730 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5731 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005732 subExpr = cast<ParenExpr>(E)->getSubExpr();
5733 exprs = &subExpr;
5734 numExprs = 1;
5735 }
5736
5737 QualType Ty = TInfo->getType();
5738 assert(Ty->isVectorType() && "Expected vector type");
5739
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005740 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00005741 const VectorType *VTy = Ty->getAs<VectorType>();
5742 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5743
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005744 // '(...)' form of vector initialization in AltiVec: the number of
5745 // initializers must be one or must match the size of the vector.
5746 // If a single value is specified in the initializer then it will be
5747 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00005748 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005749 // The number of initializers must be one or must match the size of the
5750 // vector. If a single value is specified in the initializer then it will
5751 // be replicated to all the components of the vector
5752 if (numExprs == 1) {
5753 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00005754 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5755 if (Literal.isInvalid())
5756 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005757 Literal = ImpCastExprToType(Literal.get(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00005758 PrepareScalarCast(Literal, ElemTy));
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005759 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005760 }
5761 else if (numExprs < numElems) {
5762 Diag(E->getExprLoc(),
5763 diag::err_incorrect_number_of_vector_initializers);
5764 return ExprError();
5765 }
5766 else
Benjamin Kramer8001f742012-02-14 12:06:21 +00005767 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005768 }
Tanya Lattner83559382011-07-15 23:07:01 +00005769 else {
5770 // For OpenCL, when the number of initializers is a single value,
5771 // it will be replicated to all components of the vector.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005772 if (getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +00005773 VTy->getVectorKind() == VectorType::GenericVector &&
5774 numExprs == 1) {
5775 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00005776 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5777 if (Literal.isInvalid())
5778 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005779 Literal = ImpCastExprToType(Literal.get(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00005780 PrepareScalarCast(Literal, ElemTy));
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005781 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
Tanya Lattner83559382011-07-15 23:07:01 +00005782 }
5783
Benjamin Kramer8001f742012-02-14 12:06:21 +00005784 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner83559382011-07-15 23:07:01 +00005785 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005786 // FIXME: This means that pretty-printing the final AST will produce curly
5787 // braces instead of the original commas.
Richard Smith9ca91012013-02-05 05:55:57 +00005788 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
5789 initExprs, LiteralRParenLoc);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005790 initE->setType(Ty);
5791 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
5792}
5793
Sebastian Redla9351792012-02-11 23:51:47 +00005794/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
5795/// the ParenListExpr into a sequence of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00005796ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00005797Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
5798 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005799 if (!E)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005800 return OrigExpr;
Mike Stump11289f42009-09-09 15:08:12 +00005801
John McCalldadc5752010-08-24 06:29:42 +00005802 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00005803
Nate Begeman5ec4b312009-08-10 23:49:36 +00005804 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00005805 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5806 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00005807
John McCallb268a282010-08-23 23:25:46 +00005808 if (Result.isInvalid()) return ExprError();
5809
5810 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005811}
5812
Sebastian Redla9351792012-02-11 23:51:47 +00005813ExprResult Sema::ActOnParenListExpr(SourceLocation L,
5814 SourceLocation R,
5815 MultiExprArg Val) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00005816 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005817 return expr;
Nate Begeman5ec4b312009-08-10 23:49:36 +00005818}
5819
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005820/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005821/// constant and the other is not a pointer. Returns true if a diagnostic is
5822/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00005823bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005824 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00005825 Expr *NullExpr = LHSExpr;
5826 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005827 Expr::NullPointerConstantKind NullKind =
5828 NullExpr->isNullPointerConstant(Context,
5829 Expr::NPC_ValueDependentIsNotNull);
5830
5831 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00005832 NullExpr = RHSExpr;
5833 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005834 NullKind =
5835 NullExpr->isNullPointerConstant(Context,
5836 Expr::NPC_ValueDependentIsNotNull);
5837 }
5838
5839 if (NullKind == Expr::NPCK_NotNull)
5840 return false;
5841
David Blaikie1c7c8f72012-08-08 17:33:31 +00005842 if (NullKind == Expr::NPCK_ZeroExpression)
5843 return false;
5844
5845 if (NullKind == Expr::NPCK_ZeroLiteral) {
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005846 // In this case, check to make sure that we got here from a "NULL"
5847 // string in the source code.
5848 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00005849 SourceLocation loc = NullExpr->getExprLoc();
5850 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005851 return false;
5852 }
5853
Richard Smith89645bc2013-01-02 12:01:23 +00005854 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005855 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5856 << NonPointerExpr->getType() << DiagType
5857 << NonPointerExpr->getSourceRange();
5858 return true;
5859}
5860
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005861/// \brief Return false if the condition expression is valid, true otherwise.
Sameer Sahasrabuddhee8d2aaf2015-02-04 06:38:18 +00005862static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005863 QualType CondTy = Cond->getType();
5864
Sameer Sahasrabuddhee8d2aaf2015-02-04 06:38:18 +00005865 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
5866 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
5867 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
5868 << CondTy << Cond->getSourceRange();
5869 return true;
5870 }
5871
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005872 // C99 6.5.15p2
5873 if (CondTy->isScalarType()) return false;
5874
Sameer Sahasrabuddhee8d2aaf2015-02-04 06:38:18 +00005875 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
5876 << CondTy << Cond->getSourceRange();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005877 return true;
5878}
5879
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005880/// \brief Handle when one or both operands are void type.
5881static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5882 ExprResult &RHS) {
5883 Expr *LHSExpr = LHS.get();
5884 Expr *RHSExpr = RHS.get();
5885
5886 if (!LHSExpr->getType()->isVoidType())
5887 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5888 << RHSExpr->getSourceRange();
5889 if (!RHSExpr->getType()->isVoidType())
5890 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5891 << LHSExpr->getSourceRange();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005892 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
5893 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005894 return S.Context.VoidTy;
5895}
5896
5897/// \brief Return false if the NullExpr can be promoted to PointerTy,
5898/// true otherwise.
5899static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5900 QualType PointerTy) {
5901 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5902 !NullExpr.get()->isNullPointerConstant(S.Context,
5903 Expr::NPC_ValueDependentIsNull))
5904 return true;
5905
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005906 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005907 return false;
5908}
5909
5910/// \brief Checks compatibility between two pointers and return the resulting
5911/// type.
5912static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5913 ExprResult &RHS,
5914 SourceLocation Loc) {
5915 QualType LHSTy = LHS.get()->getType();
5916 QualType RHSTy = RHS.get()->getType();
5917
5918 if (S.Context.hasSameType(LHSTy, RHSTy)) {
5919 // Two identical pointers types are always compatible.
5920 return LHSTy;
5921 }
5922
5923 QualType lhptee, rhptee;
5924
5925 // Get the pointee types.
Fariborz Jahanian1edacec2013-06-07 16:07:38 +00005926 bool IsBlockPointer = false;
John McCall9320b872011-09-09 05:25:32 +00005927 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5928 lhptee = LHSBTy->getPointeeType();
5929 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanian1edacec2013-06-07 16:07:38 +00005930 IsBlockPointer = true;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005931 } else {
John McCall9320b872011-09-09 05:25:32 +00005932 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5933 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005934 }
5935
Eli Friedman57a75392012-04-05 22:30:04 +00005936 // C99 6.5.15p6: If both operands are pointers to compatible types or to
5937 // differently qualified versions of compatible types, the result type is
5938 // a pointer to an appropriately qualified version of the composite
5939 // type.
5940
5941 // Only CVR-qualifiers exist in the standard, and the differently-qualified
5942 // clause doesn't make sense for our extensions. E.g. address space 2 should
5943 // be incompatible with address space 3: they may live on different devices or
5944 // anything.
5945 Qualifiers lhQual = lhptee.getQualifiers();
5946 Qualifiers rhQual = rhptee.getQualifiers();
5947
5948 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5949 lhQual.removeCVRQualifiers();
5950 rhQual.removeCVRQualifiers();
5951
5952 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5953 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5954
5955 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5956
5957 if (CompositeTy.isNull()) {
Richard Smith1b98ccc2014-07-19 01:39:17 +00005958 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005959 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5960 << RHS.get()->getSourceRange();
5961 // In this situation, we assume void* type. No especially good
5962 // reason, but this is what gcc does, and we do have to pick
5963 // to get a consistent AST.
5964 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005965 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
5966 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005967 return incompatTy;
5968 }
5969
5970 // The pointer types are compatible.
Eli Friedman57a75392012-04-05 22:30:04 +00005971 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
Fariborz Jahanian1edacec2013-06-07 16:07:38 +00005972 if (IsBlockPointer)
Fariborz Jahanian44d23b82013-06-07 00:48:14 +00005973 ResultTy = S.Context.getBlockPointerType(ResultTy);
5974 else
5975 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005976
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005977 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast);
5978 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast);
Eli Friedman57a75392012-04-05 22:30:04 +00005979 return ResultTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005980}
5981
5982/// \brief Return the resulting type when the operands are both block pointers.
5983static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5984 ExprResult &LHS,
5985 ExprResult &RHS,
5986 SourceLocation Loc) {
5987 QualType LHSTy = LHS.get()->getType();
5988 QualType RHSTy = RHS.get()->getType();
5989
5990 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5991 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5992 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005993 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5994 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005995 return destType;
5996 }
5997 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5998 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5999 << RHS.get()->getSourceRange();
6000 return QualType();
6001 }
6002
6003 // We have 2 block pointer types.
6004 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6005}
6006
6007/// \brief Return the resulting type when the operands are both pointers.
6008static QualType
6009checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6010 ExprResult &RHS,
6011 SourceLocation Loc) {
6012 // get the pointer types
6013 QualType LHSTy = LHS.get()->getType();
6014 QualType RHSTy = RHS.get()->getType();
6015
6016 // get the "pointed to" types
6017 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6018 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6019
6020 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6021 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6022 // Figure out necessary qualifiers (C99 6.5.15p6)
6023 QualType destPointee
6024 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6025 QualType destType = S.Context.getPointerType(destPointee);
6026 // Add qualifiers if necessary.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006027 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006028 // Promote to void*.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006029 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006030 return destType;
6031 }
6032 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6033 QualType destPointee
6034 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6035 QualType destType = S.Context.getPointerType(destPointee);
6036 // Add qualifiers if necessary.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006037 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006038 // Promote to void*.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006039 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006040 return destType;
6041 }
6042
6043 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6044}
6045
6046/// \brief Return false if the first expression is not an integer and the second
6047/// expression is not a pointer, true otherwise.
6048static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6049 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006050 bool IsIntFirstExpr) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006051 if (!PointerExpr->getType()->isPointerType() ||
6052 !Int.get()->getType()->isIntegerType())
6053 return false;
6054
Richard Trieuba63ce62011-09-09 01:45:06 +00006055 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6056 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006057
Richard Smith1b98ccc2014-07-19 01:39:17 +00006058 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006059 << Expr1->getType() << Expr2->getType()
6060 << Expr1->getSourceRange() << Expr2->getSourceRange();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006061 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006062 CK_IntegralToPointer);
6063 return true;
6064}
6065
Sameer Sahasrabuddhee8d2aaf2015-02-04 06:38:18 +00006066/// \brief Simple conversion between integer and floating point types.
6067///
6068/// Used when handling the OpenCL conditional operator where the
6069/// condition is a vector while the other operands are scalar.
6070///
6071/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6072/// types are either integer or floating type. Between the two
6073/// operands, the type with the higher rank is defined as the "result
6074/// type". The other operand needs to be promoted to the same type. No
6075/// other type promotion is allowed. We cannot use
6076/// UsualArithmeticConversions() for this purpose, since it always
6077/// promotes promotable types.
6078static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6079 ExprResult &RHS,
6080 SourceLocation QuestionLoc) {
6081 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6082 if (LHS.isInvalid())
6083 return QualType();
6084 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6085 if (RHS.isInvalid())
6086 return QualType();
6087
6088 // For conversion purposes, we ignore any qualifiers.
6089 // For example, "const float" and "float" are equivalent.
6090 QualType LHSType =
6091 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6092 QualType RHSType =
6093 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6094
6095 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6096 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6097 << LHSType << LHS.get()->getSourceRange();
6098 return QualType();
6099 }
6100
6101 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6102 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6103 << RHSType << RHS.get()->getSourceRange();
6104 return QualType();
6105 }
6106
6107 // If both types are identical, no conversion is needed.
6108 if (LHSType == RHSType)
6109 return LHSType;
6110
6111 // Now handle "real" floating types (i.e. float, double, long double).
6112 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6113 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6114 /*IsCompAssign = */ false);
6115
6116 // Finally, we have two differing integer types.
6117 return handleIntegerConversion<doIntegralCast, doIntegralCast>
6118 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6119}
6120
6121/// \brief Convert scalar operands to a vector that matches the
6122/// condition in length.
6123///
6124/// Used when handling the OpenCL conditional operator where the
6125/// condition is a vector while the other operands are scalar.
6126///
6127/// We first compute the "result type" for the scalar operands
6128/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6129/// into a vector of that type where the length matches the condition
6130/// vector type. s6.11.6 requires that the element types of the result
6131/// and the condition must have the same number of bits.
6132static QualType
6133OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6134 QualType CondTy, SourceLocation QuestionLoc) {
6135 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6136 if (ResTy.isNull()) return QualType();
6137
6138 const VectorType *CV = CondTy->getAs<VectorType>();
6139 assert(CV);
6140
6141 // Determine the vector result type
6142 unsigned NumElements = CV->getNumElements();
6143 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6144
6145 // Ensure that all types have the same number of bits
6146 if (S.Context.getTypeSize(CV->getElementType())
6147 != S.Context.getTypeSize(ResTy)) {
6148 // Since VectorTy is created internally, it does not pretty print
6149 // with an OpenCL name. Instead, we just print a description.
6150 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6151 SmallString<64> Str;
6152 llvm::raw_svector_ostream OS(Str);
6153 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6154 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6155 << CondTy << OS.str();
6156 return QualType();
6157 }
6158
6159 // Convert operands to the vector result type
6160 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6161 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6162
6163 return VectorTy;
6164}
6165
6166/// \brief Return false if this is a valid OpenCL condition vector
6167static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6168 SourceLocation QuestionLoc) {
6169 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6170 // integral type.
6171 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6172 assert(CondTy);
6173 QualType EleTy = CondTy->getElementType();
6174 if (EleTy->isIntegerType()) return false;
6175
6176 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6177 << Cond->getType() << Cond->getSourceRange();
6178 return true;
6179}
6180
6181/// \brief Return false if the vector condition type and the vector
6182/// result type are compatible.
6183///
6184/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6185/// number of elements, and their element types have the same number
6186/// of bits.
6187static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6188 SourceLocation QuestionLoc) {
6189 const VectorType *CV = CondTy->getAs<VectorType>();
6190 const VectorType *RV = VecResTy->getAs<VectorType>();
6191 assert(CV && RV);
6192
6193 if (CV->getNumElements() != RV->getNumElements()) {
6194 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6195 << CondTy << VecResTy;
6196 return true;
6197 }
6198
6199 QualType CVE = CV->getElementType();
6200 QualType RVE = RV->getElementType();
6201
6202 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6203 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6204 << CondTy << VecResTy;
6205 return true;
6206 }
6207
6208 return false;
6209}
6210
6211/// \brief Return the resulting type for the conditional operator in
6212/// OpenCL (aka "ternary selection operator", OpenCL v1.1
6213/// s6.3.i) when the condition is a vector type.
6214static QualType
6215OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6216 ExprResult &LHS, ExprResult &RHS,
6217 SourceLocation QuestionLoc) {
6218 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6219 if (Cond.isInvalid())
6220 return QualType();
6221 QualType CondTy = Cond.get()->getType();
6222
6223 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6224 return QualType();
6225
6226 // If either operand is a vector then find the vector type of the
6227 // result as specified in OpenCL v1.1 s6.3.i.
6228 if (LHS.get()->getType()->isVectorType() ||
6229 RHS.get()->getType()->isVectorType()) {
6230 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00006231 /*isCompAssign*/false,
6232 /*AllowBothBool*/true,
6233 /*AllowBoolConversions*/false);
Sameer Sahasrabuddhee8d2aaf2015-02-04 06:38:18 +00006234 if (VecResTy.isNull()) return QualType();
6235 // The result type must match the condition type as specified in
6236 // OpenCL v1.1 s6.11.6.
6237 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6238 return QualType();
6239 return VecResTy;
6240 }
6241
6242 // Both operands are scalar.
6243 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6244}
6245
Richard Trieud33e46e2011-09-06 20:06:39 +00006246/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6247/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00006248/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00006249QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6250 ExprResult &RHS, ExprValueKind &VK,
6251 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00006252 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00006253
Richard Trieud33e46e2011-09-06 20:06:39 +00006254 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6255 if (!LHSResult.isUsable()) return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006256 LHS = LHSResult;
Douglas Gregor0124e9b2010-11-09 21:07:58 +00006257
Richard Trieud33e46e2011-09-06 20:06:39 +00006258 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6259 if (!RHSResult.isUsable()) return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006260 RHS = RHSResult;
Douglas Gregor0124e9b2010-11-09 21:07:58 +00006261
Sebastian Redl1a99f442009-04-16 17:51:27 +00006262 // C++ is sufficiently different to merit its own checker.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006263 if (getLangOpts().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00006264 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00006265
6266 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00006267 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006268
Sameer Sahasrabuddhee8d2aaf2015-02-04 06:38:18 +00006269 // The OpenCL operator with a vector condition is sufficiently
6270 // different to merit its own checker.
6271 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6272 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6273
Jin-Gu Kang09c22132013-09-02 20:32:37 +00006274 // First, check the condition.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006275 Cond = UsualUnaryConversions(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00006276 if (Cond.isInvalid())
6277 return QualType();
Sameer Sahasrabuddhee8d2aaf2015-02-04 06:38:18 +00006278 if (checkCondition(*this, Cond.get(), QuestionLoc))
Jin-Gu Kang09c22132013-09-02 20:32:37 +00006279 return QualType();
6280
6281 // Now check the two expressions.
6282 if (LHS.get()->getType()->isVectorType() ||
6283 RHS.get()->getType()->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00006284 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6285 /*AllowBothBool*/true,
6286 /*AllowBoolConversions*/false);
Jin-Gu Kang09c22132013-09-02 20:32:37 +00006287
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006288 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
Eli Friedmane6d33952013-07-08 20:20:06 +00006289 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006290 return QualType();
6291
John Wiegley01296292011-04-08 18:41:53 +00006292 QualType LHSTy = LHS.get()->getType();
6293 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00006294
Chris Lattnere2949f42008-01-06 22:42:25 +00006295 // If both operands have arithmetic type, do the usual arithmetic conversions
6296 // to find a common type: C99 6.5.15p3,5.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006297 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6298 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6299 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6300
6301 return ResTy;
6302 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006303
Chris Lattnere2949f42008-01-06 22:42:25 +00006304 // If both operands are the same structure or union type, the result is that
6305 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006306 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
6307 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00006308 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00006309 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00006310 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00006311 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00006312 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00006313 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006314
Chris Lattnere2949f42008-01-06 22:42:25 +00006315 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00006316 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00006317 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006318 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00006319 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006320
Steve Naroff039ad3c2008-01-08 01:11:38 +00006321 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6322 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006323 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6324 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006325
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006326 // All objective-c pointer type analysis is done here.
6327 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6328 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00006329 if (LHS.isInvalid() || RHS.isInvalid())
6330 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006331 if (!compositeType.isNull())
6332 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006333
6334
Steve Naroff05efa972009-07-01 14:36:47 +00006335 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006336 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6337 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6338 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006339
Steve Naroff05efa972009-07-01 14:36:47 +00006340 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006341 if (LHSTy->isPointerType() && RHSTy->isPointerType())
6342 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6343 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006344
John McCalle84af4e2010-11-13 01:35:44 +00006345 // GCC compatibility: soften pointer/integer mismatch. Note that
6346 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006347 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6348 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00006349 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006350 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6351 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00006352 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00006353
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00006354 // Emit a better diagnostic if one of the expressions is a null pointer
6355 // constant and the other is not a pointer type. In this case, the user most
6356 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00006357 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00006358 return QualType();
6359
Chris Lattnere2949f42008-01-06 22:42:25 +00006360 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00006361 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00006362 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6363 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00006364 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00006365}
6366
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006367/// FindCompositeObjCPointerType - Helper method to find composite type of
6368/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00006369QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006370 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00006371 QualType LHSTy = LHS.get()->getType();
6372 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006373
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006374 // Handle things like Class and struct objc_class*. Here we case the result
6375 // to the pseudo-builtin, because that will be implicitly cast back to the
6376 // redefinition type if an attempt is made to access its fields.
6377 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00006378 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006379 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006380 return LHSTy;
6381 }
6382 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00006383 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006384 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006385 return RHSTy;
6386 }
6387 // And the same for struct objc_object* / id
6388 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00006389 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006390 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006391 return LHSTy;
6392 }
6393 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00006394 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006395 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006396 return RHSTy;
6397 }
6398 // And the same for struct objc_selector* / SEL
6399 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00006400 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006401 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006402 return LHSTy;
6403 }
6404 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00006405 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006406 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006407 return RHSTy;
6408 }
6409 // Check constraints for Objective-C object pointers types.
6410 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006411
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006412 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6413 // Two identical object pointer types are always compatible.
6414 return LHSTy;
6415 }
John McCall9320b872011-09-09 05:25:32 +00006416 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6417 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006418 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006419
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006420 // If both operands are interfaces and either operand can be
6421 // assigned to the other, use that type as the composite
6422 // type. This allows
6423 // xxx ? (A*) a : (B*) b
6424 // where B is a subclass of A.
6425 //
6426 // Additionally, as for assignment, if either type is 'id'
6427 // allow silent coercion. Finally, if the types are
6428 // incompatible then make sure to use 'id' as the composite
6429 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006430
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006431 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6432 // It could return the composite type.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006433 if (!(compositeType =
6434 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6435 // Nothing more to do.
6436 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006437 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6438 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6439 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6440 } else if ((LHSTy->isObjCQualifiedIdType() ||
6441 RHSTy->isObjCQualifiedIdType()) &&
6442 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6443 // Need to handle "id<xx>" explicitly.
6444 // GCC allows qualified id and any Objective-C type to devolve to
6445 // id. Currently localizing to here until clear this should be
6446 // part of ObjCQualifiedIdTypesAreCompatible.
6447 compositeType = Context.getObjCIdType();
6448 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6449 compositeType = Context.getObjCIdType();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006450 } else {
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006451 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6452 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00006453 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006454 QualType incompatTy = Context.getObjCIdType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006455 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6456 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006457 return incompatTy;
6458 }
6459 // The object pointer types are compatible.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006460 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6461 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006462 return compositeType;
6463 }
6464 // Check Objective-C object pointer types and 'void *'
6465 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006466 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00006467 // ARC forbids the implicit conversion of object pointers to 'void *',
6468 // so these types are not compatible.
6469 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6470 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6471 LHS = RHS = true;
6472 return QualType();
6473 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006474 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6475 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6476 QualType destPointee
6477 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6478 QualType destType = Context.getPointerType(destPointee);
6479 // Add qualifiers if necessary.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006480 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006481 // Promote to void*.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006482 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006483 return destType;
6484 }
6485 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006486 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00006487 // ARC forbids the implicit conversion of object pointers to 'void *',
6488 // so these types are not compatible.
6489 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6490 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6491 LHS = RHS = true;
6492 return QualType();
6493 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006494 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6495 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6496 QualType destPointee
6497 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6498 QualType destType = Context.getPointerType(destPointee);
6499 // Add qualifiers if necessary.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006500 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006501 // Promote to void*.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006502 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006503 return destType;
6504 }
6505 return QualType();
6506}
6507
Chandler Carruthb00e8c02011-06-16 01:05:14 +00006508/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006509/// ParenRange in parentheses.
6510static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00006511 const PartialDiagnostic &Note,
6512 SourceRange ParenRange) {
Craig Topper07fa1762015-11-15 02:31:46 +00006513 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
Chandler Carruthb00e8c02011-06-16 01:05:14 +00006514 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6515 EndLoc.isValid()) {
6516 Self.Diag(Loc, Note)
6517 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6518 << FixItHint::CreateInsertion(EndLoc, ")");
6519 } else {
6520 // We can't display the parentheses, so just show the bare note.
6521 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006522 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006523}
6524
6525static bool IsArithmeticOp(BinaryOperatorKind Opc) {
Craig Topperb0dfa7a2015-12-13 05:41:37 +00006526 return BinaryOperator::isAdditiveOp(Opc) ||
6527 BinaryOperator::isMultiplicativeOp(Opc) ||
6528 BinaryOperator::isShiftOp(Opc);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006529}
6530
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006531/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6532/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00006533/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6534/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006535static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00006536 Expr **RHSExprs) {
Hans Wennborgbe207b32011-09-12 12:07:30 +00006537 // Don't strip parenthesis: we should not warn if E is in parenthesis.
6538 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006539 E = E->IgnoreConversionOperator();
Hans Wennborgbe207b32011-09-12 12:07:30 +00006540 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006541
6542 // Built-in binary operator.
6543 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6544 if (IsArithmeticOp(OP->getOpcode())) {
6545 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00006546 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006547 return true;
6548 }
6549 }
6550
6551 // Overloaded operator.
6552 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6553 if (Call->getNumArgs() != 2)
6554 return false;
6555
6556 // Make sure this is really a binary operator that is safe to pass into
6557 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6558 OverloadedOperatorKind OO = Call->getOperator();
Benjamin Kramer0345f9f2013-03-30 11:56:00 +00006559 if (OO < OO_Plus || OO > OO_Arrow ||
6560 OO == OO_PlusPlus || OO == OO_MinusMinus)
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006561 return false;
6562
6563 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6564 if (IsArithmeticOp(OpKind)) {
6565 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00006566 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006567 return true;
6568 }
6569 }
6570
6571 return false;
6572}
6573
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006574/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6575/// or is a logical expression such as (x==y) which has int type, but is
6576/// commonly interpreted as boolean.
6577static bool ExprLooksBoolean(Expr *E) {
6578 E = E->IgnoreParenImpCasts();
6579
6580 if (E->getType()->isBooleanType())
6581 return true;
6582 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
Craig Topperb0dfa7a2015-12-13 05:41:37 +00006583 return OP->isComparisonOp() || OP->isLogicalOp();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006584 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6585 return OP->getOpcode() == UO_LNot;
Hans Wennborgb60dfbe2015-01-22 22:11:56 +00006586 if (E->getType()->isPointerType())
6587 return true;
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006588
6589 return false;
6590}
6591
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006592/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6593/// and binary operator are mixed in a way that suggests the programmer assumed
6594/// the conditional operator has higher precedence, for example:
6595/// "int x = a + someBinaryCondition ? 1 : 2".
6596static void DiagnoseConditionalPrecedence(Sema &Self,
6597 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00006598 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00006599 Expr *LHSExpr,
6600 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006601 BinaryOperatorKind CondOpcode;
6602 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006603
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00006604 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006605 return;
6606 if (!ExprLooksBoolean(CondRHS))
6607 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006608
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006609 // The condition is an arithmetic binary expression, with a right-
6610 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006611
Chandler Carruthb00e8c02011-06-16 01:05:14 +00006612 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00006613 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006614 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006615
Chandler Carruthb00e8c02011-06-16 01:05:14 +00006616 SuggestParentheses(Self, OpLoc,
David Blaikiedac86fd2012-10-08 01:19:49 +00006617 Self.PDiag(diag::note_precedence_silence)
Chandler Carruthb00e8c02011-06-16 01:05:14 +00006618 << BinaryOperator::getOpcodeStr(CondOpcode),
6619 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00006620
6621 SuggestParentheses(Self, OpLoc,
6622 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00006623 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006624}
6625
Steve Naroff83895f72007-09-16 03:34:24 +00006626/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00006627/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00006628ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00006629 SourceLocation ColonLoc,
6630 Expr *CondExpr, Expr *LHSExpr,
6631 Expr *RHSExpr) {
Kaelyn Takata05f40502015-01-27 18:26:18 +00006632 if (!getLangOpts().CPlusPlus) {
6633 // C cannot handle TypoExpr nodes in the condition because it
6634 // doesn't handle dependent types properly, so make sure any TypoExprs have
6635 // been dealt with before checking the operands.
6636 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
6637 if (!CondResult.isUsable()) return ExprError();
6638 CondExpr = CondResult.get();
6639 }
6640
Chris Lattner2ab40a62007-11-26 01:40:58 +00006641 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6642 // was the condition.
Craig Topperc3ec1492014-05-26 06:22:03 +00006643 OpaqueValueExpr *opaqueValue = nullptr;
6644 Expr *commonExpr = nullptr;
6645 if (!LHSExpr) {
John McCallc07a0c72011-02-17 10:25:35 +00006646 commonExpr = CondExpr;
Fariborz Jahanian3caab6c2013-05-17 16:29:36 +00006647 // Lower out placeholder types first. This is important so that we don't
6648 // try to capture a placeholder. This happens in few cases in C++; such
6649 // as Objective-C++'s dictionary subscripting syntax.
6650 if (commonExpr->hasPlaceholderType()) {
6651 ExprResult result = CheckPlaceholderExpr(commonExpr);
6652 if (!result.isUsable()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006653 commonExpr = result.get();
Fariborz Jahanian3caab6c2013-05-17 16:29:36 +00006654 }
John McCallc07a0c72011-02-17 10:25:35 +00006655 // We usually want to apply unary conversions *before* saving, except
6656 // in the special case of a C++ l-value conditional.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006657 if (!(getLangOpts().CPlusPlus
John McCallc07a0c72011-02-17 10:25:35 +00006658 && !commonExpr->isTypeDependent()
6659 && commonExpr->getValueKind() == RHSExpr->getValueKind()
6660 && commonExpr->isGLValue()
6661 && commonExpr->isOrdinaryOrBitFieldObject()
6662 && RHSExpr->isOrdinaryOrBitFieldObject()
6663 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00006664 ExprResult commonRes = UsualUnaryConversions(commonExpr);
6665 if (commonRes.isInvalid())
6666 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006667 commonExpr = commonRes.get();
John McCallc07a0c72011-02-17 10:25:35 +00006668 }
6669
6670 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6671 commonExpr->getType(),
6672 commonExpr->getValueKind(),
Douglas Gregor2d5aea02012-02-23 22:17:26 +00006673 commonExpr->getObjectKind(),
6674 commonExpr);
John McCallc07a0c72011-02-17 10:25:35 +00006675 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00006676 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00006677
John McCall7decc9e2010-11-18 06:31:45 +00006678 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00006679 ExprObjectKind OK = OK_Ordinary;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006680 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
John Wiegley01296292011-04-08 18:41:53 +00006681 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00006682 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00006683 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6684 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00006685 return ExprError();
6686
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006687 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
6688 RHS.get());
6689
Richard Trieucbab79a2015-05-20 23:29:18 +00006690 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
6691
John McCallc07a0c72011-02-17 10:25:35 +00006692 if (!commonExpr)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006693 return new (Context)
6694 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
6695 RHS.get(), result, VK, OK);
John McCallc07a0c72011-02-17 10:25:35 +00006696
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006697 return new (Context) BinaryConditionalOperator(
6698 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
6699 ColonLoc, result, VK, OK);
Chris Lattnere168f762006-11-10 05:29:30 +00006700}
6701
John McCallaba90822011-01-31 23:13:11 +00006702// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00006703// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00006704// routine is it effectively iqnores the qualifiers on the top level pointee.
6705// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6706// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00006707static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00006708checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
6709 assert(LHSType.isCanonical() && "LHS not canonicalized!");
6710 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006711
Steve Naroff1f4d7272007-05-11 04:00:31 +00006712 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00006713 const Type *lhptee, *rhptee;
6714 Qualifiers lhq, rhq;
Benjamin Kramercef536e2014-03-02 13:18:22 +00006715 std::tie(lhptee, lhq) =
6716 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
6717 std::tie(rhptee, rhq) =
6718 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006719
John McCallaba90822011-01-31 23:13:11 +00006720 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006721
6722 // C99 6.5.16.1p1: This following citation is common to constraints
6723 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6724 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00006725
John McCall31168b02011-06-15 23:02:42 +00006726 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
6727 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
6728 lhq.compatiblyIncludesObjCLifetime(rhq)) {
6729 // Ignore lifetime for further calculation.
6730 lhq.removeObjCLifetime();
6731 rhq.removeObjCLifetime();
6732 }
6733
John McCall4fff8f62011-02-01 00:10:29 +00006734 if (!lhq.compatiblyIncludes(rhq)) {
6735 // Treat address-space mismatches as fatal. TODO: address subspaces
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00006736 if (!lhq.isAddressSpaceSupersetOf(rhq))
John McCall4fff8f62011-02-01 00:10:29 +00006737 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6738
John McCall31168b02011-06-15 23:02:42 +00006739 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00006740 // and from void*.
John McCall18ce25e2012-02-08 00:46:36 +00006741 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCall31168b02011-06-15 23:02:42 +00006742 .compatiblyIncludes(
John McCall18ce25e2012-02-08 00:46:36 +00006743 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall78535952011-03-26 02:56:45 +00006744 && (lhptee->isVoidType() || rhptee->isVoidType()))
6745 ; // keep old
6746
John McCall31168b02011-06-15 23:02:42 +00006747 // Treat lifetime mismatches as fatal.
6748 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6749 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6750
John McCall4fff8f62011-02-01 00:10:29 +00006751 // For GCC compatibility, other qualifier mismatches are treated
6752 // as still compatible in C.
6753 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6754 }
Steve Naroff3f597292007-05-11 22:18:03 +00006755
Mike Stump4e1f26a2009-02-19 03:04:26 +00006756 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6757 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00006758 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00006759 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006760 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00006761 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006762
Chris Lattner0a788432008-01-03 22:56:36 +00006763 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006764 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00006765 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00006766 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006767
Chris Lattner0a788432008-01-03 22:56:36 +00006768 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006769 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00006770 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00006771
6772 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006773 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00006774 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00006775 }
John McCall4fff8f62011-02-01 00:10:29 +00006776
Mike Stump4e1f26a2009-02-19 03:04:26 +00006777 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00006778 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00006779 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6780 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00006781 // Check if the pointee types are compatible ignoring the sign.
6782 // We explicitly check for char so that we catch "char" vs
6783 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00006784 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00006785 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006786 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00006787 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006788
Chris Lattnerec3a1562009-10-17 20:33:28 +00006789 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00006790 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006791 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00006792 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00006793
John McCall4fff8f62011-02-01 00:10:29 +00006794 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00006795 // Types are compatible ignoring the sign. Qualifier incompatibility
6796 // takes priority over sign incompatibility because the sign
6797 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00006798 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00006799 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00006800
John McCallaba90822011-01-31 23:13:11 +00006801 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00006802 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006803
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006804 // If we are a multi-level pointer, it's possible that our issue is simply
6805 // one of qualification - e.g. char ** -> const char ** is not allowed. If
6806 // the eventual target type is the same and the pointers have the same
6807 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00006808 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006809 do {
John McCall4fff8f62011-02-01 00:10:29 +00006810 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6811 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00006812 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006813
John McCall4fff8f62011-02-01 00:10:29 +00006814 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00006815 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006816 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006817
Eli Friedman80160bd2009-03-22 23:59:44 +00006818 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00006819 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00006820 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00006821 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian48c69102011-10-05 00:05:34 +00006822 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
6823 return Sema::IncompatiblePointer;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006824 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00006825}
6826
John McCallaba90822011-01-31 23:13:11 +00006827/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00006828/// block pointer types are compatible or whether a block and normal pointer
6829/// are compatible. It is more restrict than comparing two function pointer
6830// types.
John McCallaba90822011-01-31 23:13:11 +00006831static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00006832checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
6833 QualType RHSType) {
6834 assert(LHSType.isCanonical() && "LHS not canonicalized!");
6835 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00006836
Steve Naroff081c7422008-09-04 15:10:53 +00006837 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006838
Steve Naroff081c7422008-09-04 15:10:53 +00006839 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00006840 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
6841 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006842
John McCallaba90822011-01-31 23:13:11 +00006843 // In C++, the types have to match exactly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006844 if (S.getLangOpts().CPlusPlus)
John McCallaba90822011-01-31 23:13:11 +00006845 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006846
John McCallaba90822011-01-31 23:13:11 +00006847 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006848
Steve Naroff081c7422008-09-04 15:10:53 +00006849 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00006850 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6851 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006852
Richard Trieua871b972011-09-06 20:21:22 +00006853 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00006854 return Sema::IncompatibleBlockPointer;
6855
Steve Naroff081c7422008-09-04 15:10:53 +00006856 return ConvTy;
6857}
6858
John McCallaba90822011-01-31 23:13:11 +00006859/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006860/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00006861static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00006862checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
6863 QualType RHSType) {
6864 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
6865 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00006866
Richard Trieua871b972011-09-06 20:21:22 +00006867 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006868 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00006869 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
6870 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00006871 return Sema::IncompatiblePointer;
6872 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006873 }
Richard Trieua871b972011-09-06 20:21:22 +00006874 if (RHSType->isObjCBuiltinType()) {
Richard Trieua871b972011-09-06 20:21:22 +00006875 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
6876 !LHSType->isObjCQualifiedClassType())
Fariborz Jahaniand923eb02011-09-15 20:40:18 +00006877 return Sema::IncompatiblePointer;
John McCallaba90822011-01-31 23:13:11 +00006878 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006879 }
Richard Trieua871b972011-09-06 20:21:22 +00006880 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6881 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006882
Fariborz Jahaniane74d47e2012-01-12 22:12:08 +00006883 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
6884 // make an exception for id<P>
6885 !LHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00006886 return Sema::CompatiblePointerDiscardsQualifiers;
6887
Richard Trieua871b972011-09-06 20:21:22 +00006888 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00006889 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00006890 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00006891 return Sema::IncompatibleObjCQualifiedId;
6892 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006893}
6894
John McCall29600e12010-11-16 02:32:08 +00006895Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00006896Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00006897 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00006898 // Fake up an opaque expression. We don't actually care about what
6899 // cast operations are required, so if CheckAssignmentConstraints
6900 // adds casts to this they'll be wasted, but fortunately that doesn't
6901 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00006902 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
6903 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00006904 CastKind K = CK_Invalid;
6905
George Burgess IV45461812015-10-11 20:13:20 +00006906 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
John McCall29600e12010-11-16 02:32:08 +00006907}
6908
Mike Stump4e1f26a2009-02-19 03:04:26 +00006909/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6910/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00006911/// pointers. Here are some objectionable examples that GCC considers warnings:
6912///
6913/// int a, *pint;
6914/// short *pshort;
6915/// struct foo *pfoo;
6916///
6917/// pint = pshort; // warning: assignment from incompatible pointer type
6918/// a = pint; // warning: assignment makes integer from pointer without a cast
6919/// pint = a; // warning: assignment makes pointer from integer without a cast
6920/// pint = pfoo; // warning: assignment from incompatible pointer type
6921///
6922/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00006923/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00006924///
John McCall8cb679e2010-11-15 09:13:47 +00006925/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00006926Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00006927Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
George Burgess IV45461812015-10-11 20:13:20 +00006928 CastKind &Kind, bool ConvertRHS) {
Richard Trieude4958f2011-09-06 20:30:53 +00006929 QualType RHSType = RHS.get()->getType();
6930 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00006931
Chris Lattnera52c2f22008-01-04 23:18:45 +00006932 // Get canonical types. We're not formatting these types, just comparing
6933 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00006934 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
6935 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00006936
John McCalle5255932011-01-31 22:28:28 +00006937 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00006938 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00006939 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00006940 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00006941 }
6942
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006943 // If we have an atomic type, try a non-atomic assignment, then just add an
6944 // atomic qualification step.
David Chisnallfa35df62012-01-16 17:27:18 +00006945 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006946 Sema::AssignConvertType result =
6947 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
6948 if (result != Compatible)
6949 return result;
George Burgess IV45461812015-10-11 20:13:20 +00006950 if (Kind != CK_NoOp && ConvertRHS)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006951 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006952 Kind = CK_NonAtomicToAtomic;
6953 return Compatible;
David Chisnallfa35df62012-01-16 17:27:18 +00006954 }
6955
Douglas Gregor6b754842008-10-28 00:22:11 +00006956 // If the left-hand side is a reference type, then we are in a
6957 // (rare!) case where we've allowed the use of references in C,
6958 // e.g., as a parameter type in a built-in function. In this case,
6959 // just make sure that the type referenced is compatible with the
6960 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00006961 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00006962 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00006963 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
6964 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006965 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00006966 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006967 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00006968 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00006969 }
John McCalle5255932011-01-31 22:28:28 +00006970
Nate Begemanbd956c42009-06-28 02:36:38 +00006971 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6972 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00006973 if (LHSType->isExtVectorType()) {
6974 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00006975 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00006976 if (RHSType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00006977 // CK_VectorSplat does T -> vector T, so first cast to the
6978 // element type.
Richard Trieude4958f2011-09-06 20:30:53 +00006979 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
George Burgess IV45461812015-10-11 20:13:20 +00006980 if (elType != RHSType && ConvertRHS) {
John McCall9776e432011-10-06 23:25:11 +00006981 Kind = PrepareScalarCast(RHS, elType);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006982 RHS = ImpCastExprToType(RHS.get(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00006983 }
6984 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00006985 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006986 }
Nate Begemanbd956c42009-06-28 02:36:38 +00006987 }
Mike Stump11289f42009-09-09 15:08:12 +00006988
John McCalle5255932011-01-31 22:28:28 +00006989 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00006990 if (LHSType->isVectorType() || RHSType->isVectorType()) {
6991 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00006992 // Allow assignments of an AltiVec vector type to an equivalent GCC
6993 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00006994 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00006995 Kind = CK_BitCast;
6996 return Compatible;
6997 }
6998
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006999 // If we are allowing lax vector conversions, and LHS and RHS are both
7000 // vectors, the total size only needs to be the same. This is a bitcast;
7001 // no bits are changed but the result type is different.
John McCall9b595db2014-02-04 23:58:19 +00007002 if (isLaxVectorConversion(RHSType, LHSType)) {
John McCall3065d042010-11-15 10:08:00 +00007003 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00007004 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00007005 }
Chris Lattner881a2122008-01-04 23:32:24 +00007006 }
7007 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007008 }
Eli Friedman3360d892008-05-30 18:07:22 +00007009
John McCalle5255932011-01-31 22:28:28 +00007010 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00007011 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007012 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
George Burgess IV45461812015-10-11 20:13:20 +00007013 if (ConvertRHS)
7014 Kind = PrepareScalarCast(RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00007015 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00007016 }
Eli Friedman3360d892008-05-30 18:07:22 +00007017
John McCalle5255932011-01-31 22:28:28 +00007018 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00007019 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00007020 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00007021 if (isa<PointerType>(RHSType)) {
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00007022 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7023 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7024 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00007025 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00007026 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007027
John McCalle5255932011-01-31 22:28:28 +00007028 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00007029 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00007030 Kind = CK_IntegralToPointer; // FIXME: null?
7031 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007032 }
John McCalle5255932011-01-31 22:28:28 +00007033
7034 // C pointers are not compatible with ObjC object pointers,
7035 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00007036 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00007037 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00007038 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall9320b872011-09-09 05:25:32 +00007039 Kind = CK_BitCast;
John McCalle5255932011-01-31 22:28:28 +00007040 return Compatible;
7041 }
7042
7043 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00007044 if (RHSType->isObjCClassType() &&
7045 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00007046 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00007047 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00007048 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00007049 }
Douglas Gregor486b74e2011-09-27 16:10:05 +00007050
John McCalle5255932011-01-31 22:28:28 +00007051 Kind = CK_BitCast;
7052 return IncompatiblePointer;
7053 }
7054
7055 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00007056 if (RHSType->getAs<BlockPointerType>()) {
7057 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00007058 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00007059 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00007060 }
Steve Naroff32d072c2008-09-29 18:10:17 +00007061 }
John McCalle5255932011-01-31 22:28:28 +00007062
Steve Naroff081c7422008-09-04 15:10:53 +00007063 return Incompatible;
7064 }
7065
John McCalle5255932011-01-31 22:28:28 +00007066 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00007067 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00007068 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00007069 if (RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00007070 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00007071 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00007072 }
7073
7074 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00007075 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00007076 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00007077 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00007078 }
7079
John McCalle5255932011-01-31 22:28:28 +00007080 // id -> T^
David Blaikiebbafb8a2012-03-11 07:00:24 +00007081 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00007082 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00007083 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00007084 }
Steve Naroff32d072c2008-09-29 18:10:17 +00007085
John McCalle5255932011-01-31 22:28:28 +00007086 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00007087 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00007088 if (RHSPT->getPointeeType()->isVoidType()) {
7089 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00007090 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00007091 }
John McCall8cb679e2010-11-15 09:13:47 +00007092
Chris Lattnera52c2f22008-01-04 23:18:45 +00007093 return Incompatible;
7094 }
7095
John McCalle5255932011-01-31 22:28:28 +00007096 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00007097 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00007098 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00007099 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00007100 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00007101 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00007102 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikiebbafb8a2012-03-11 07:00:24 +00007103 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00007104 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00007105 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00007106 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00007107 return result;
John McCalle5255932011-01-31 22:28:28 +00007108 }
7109
7110 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00007111 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00007112 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00007113 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00007114 }
7115
John McCalle5255932011-01-31 22:28:28 +00007116 // In general, C pointers are not compatible with ObjC object pointers,
7117 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00007118 if (isa<PointerType>(RHSType)) {
John McCall9320b872011-09-09 05:25:32 +00007119 Kind = CK_CPointerToObjCPointerCast;
7120
John McCalle5255932011-01-31 22:28:28 +00007121 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00007122 if (RHSType->isVoidPointerType()) {
Steve Naroffaccc4882009-07-20 17:56:53 +00007123 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00007124 }
7125
7126 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00007127 if (LHSType->isObjCClassType() &&
7128 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00007129 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00007130 return Compatible;
7131 }
7132
Steve Naroffaccc4882009-07-20 17:56:53 +00007133 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007134 }
John McCalle5255932011-01-31 22:28:28 +00007135
Fariborz Jahanian7ea91b22014-06-09 21:42:01 +00007136 // Only under strict condition T^ is compatible with an Objective-C pointer.
Douglas Gregore9d95f12015-07-07 03:57:35 +00007137 if (RHSType->isBlockPointerType() &&
7138 LHSType->isBlockCompatibleObjCPointerType(Context)) {
George Burgess IV45461812015-10-11 20:13:20 +00007139 if (ConvertRHS)
7140 maybeExtendBlockObject(RHS);
John McCall9320b872011-09-09 05:25:32 +00007141 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007142 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00007143 }
7144
Steve Naroff7cae42b2009-07-10 23:34:53 +00007145 return Incompatible;
7146 }
John McCalle5255932011-01-31 22:28:28 +00007147
7148 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00007149 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00007150 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00007151 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00007152 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00007153 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00007154 }
Eli Friedman3360d892008-05-30 18:07:22 +00007155
John McCalle5255932011-01-31 22:28:28 +00007156 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00007157 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00007158 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00007159 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00007160 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007161
Chris Lattnera52c2f22008-01-04 23:18:45 +00007162 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00007163 }
John McCalle5255932011-01-31 22:28:28 +00007164
7165 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00007166 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00007167 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00007168 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00007169 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007170 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00007171 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007172
John McCalle5255932011-01-31 22:28:28 +00007173 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00007174 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00007175 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007176 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00007177 }
7178
Steve Naroff7cae42b2009-07-10 23:34:53 +00007179 return Incompatible;
7180 }
Eli Friedman3360d892008-05-30 18:07:22 +00007181
John McCalle5255932011-01-31 22:28:28 +00007182 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00007183 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7184 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00007185 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00007186 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00007187 }
Bill Wendling216423b2007-05-30 06:30:29 +00007188 }
John McCalle5255932011-01-31 22:28:28 +00007189
Steve Naroff98cf3e92007-06-06 18:38:38 +00007190 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00007191}
7192
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007193/// \brief Constructs a transparent union from an expression that is
7194/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00007195static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7196 ExprResult &EResult, QualType UnionType,
7197 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007198 // Build an initializer list that designates the appropriate member
7199 // of the transparent union.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007200 Expr *E = EResult.get();
Ted Kremenekac034612010-04-13 23:39:13 +00007201 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00007202 E, SourceLocation());
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007203 Initializer->setType(UnionType);
7204 Initializer->setInitializedFieldInUnion(Field);
7205
7206 // Build a compound literal constructing a value of the transparent
7207 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00007208 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007209 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7210 VK_RValue, Initializer, false);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007211}
7212
7213Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00007214Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00007215 ExprResult &RHS) {
7216 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007217
Mike Stump11289f42009-09-09 15:08:12 +00007218 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007219 // transparent_union GCC extension.
7220 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00007221 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007222 return Incompatible;
7223
7224 // The field to initialize within the transparent union.
7225 RecordDecl *UD = UT->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00007226 FieldDecl *InitField = nullptr;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007227 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007228 for (auto *it : UD->fields()) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007229 if (it->getType()->isPointerType()) {
7230 // If the transparent union contains a pointer type, we allow:
7231 // 1) void pointer
7232 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00007233 if (RHSType->isPointerType())
John McCall9320b872011-09-09 05:25:32 +00007234 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007235 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007236 InitField = it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007237 break;
7238 }
Mike Stump11289f42009-09-09 15:08:12 +00007239
Richard Trieueb299142011-09-06 20:40:12 +00007240 if (RHS.get()->isNullPointerConstant(Context,
7241 Expr::NPC_ValueDependentIsNull)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007242 RHS = ImpCastExprToType(RHS.get(), it->getType(),
Richard Trieueb299142011-09-06 20:40:12 +00007243 CK_NullToPointer);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007244 InitField = it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007245 break;
7246 }
7247 }
7248
John McCall8cb679e2010-11-15 09:13:47 +00007249 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00007250 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007251 == Compatible) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007252 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007253 InitField = it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007254 break;
7255 }
7256 }
7257
7258 if (!InitField)
7259 return Incompatible;
7260
Richard Trieueb299142011-09-06 20:40:12 +00007261 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007262 return Compatible;
7263}
7264
Chris Lattner9bad62c2008-01-04 18:04:52 +00007265Sema::AssignConvertType
George Burgess IV45461812015-10-11 20:13:20 +00007266Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
Fariborz Jahanian25eef192013-07-31 21:40:51 +00007267 bool Diagnose,
George Burgess IV45461812015-10-11 20:13:20 +00007268 bool DiagnoseCFAudited,
7269 bool ConvertRHS) {
7270 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7271 // we can't avoid *all* modifications at the moment, so we need some somewhere
7272 // to put the updated value.
7273 ExprResult LocalRHS = CallerRHS;
7274 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7275
David Blaikiebbafb8a2012-03-11 07:00:24 +00007276 if (getLangOpts().CPlusPlus) {
Eli Friedman0dfb8892011-10-06 23:00:33 +00007277 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00007278 // C++ 5.17p3: If the left operand is not of class type, the
7279 // expression is implicitly converted (C++ 4) to the
7280 // cv-unqualified type of the left operand.
Sebastian Redlcc152642011-10-16 18:19:06 +00007281 ExprResult Res;
7282 if (Diagnose) {
7283 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7284 AA_Assigning);
7285 } else {
7286 ImplicitConversionSequence ICS =
7287 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7288 /*SuppressUserConversions=*/false,
7289 /*AllowExplicit=*/false,
7290 /*InOverloadResolution=*/false,
7291 /*CStyle=*/false,
7292 /*AllowObjCWritebackConversion=*/false);
7293 if (ICS.isFailure())
7294 return Incompatible;
7295 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7296 ICS, AA_Assigning);
7297 }
John Wiegley01296292011-04-08 18:41:53 +00007298 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00007299 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00007300 Sema::AssignConvertType result = Compatible;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007301 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieueb299142011-09-06 20:40:12 +00007302 !CheckObjCARCUnavailableWeakConversion(LHSType,
7303 RHS.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00007304 result = IncompatibleObjCWeakRef;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007305 RHS = Res;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00007306 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00007307 }
7308
7309 // FIXME: Currently, we fall through and treat C++ classes like C
7310 // structures.
Eli Friedman0dfb8892011-10-06 23:00:33 +00007311 // FIXME: We also fall through for atomics; not sure what should
7312 // happen there, though.
George Burgess IV5f21c712015-10-12 19:57:04 +00007313 } else if (RHS.get()->getType() == Context.OverloadTy) {
7314 // As a set of extensions to C, we support overloading on functions. These
7315 // functions need to be resolved here.
7316 DeclAccessPair DAP;
7317 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7318 RHS.get(), LHSType, /*Complain=*/false, DAP))
7319 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7320 else
7321 return Incompatible;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007322 }
Douglas Gregor9a657932008-10-21 23:43:52 +00007323
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00007324 // C99 6.5.16.1p1: the left operand is a pointer and the right is
7325 // a null pointer constant.
Richard Smithe934d7c2013-11-21 01:53:02 +00007326 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7327 LHSType->isBlockPointerType()) &&
7328 RHS.get()->isNullPointerConstant(Context,
7329 Expr::NPC_ValueDependentIsNull)) {
7330 CastKind Kind;
7331 CXXCastPath Path;
7332 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
George Burgess IV45461812015-10-11 20:13:20 +00007333 if (ConvertRHS)
7334 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00007335 return Compatible;
7336 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007337
Chris Lattnere6dcd502007-10-16 02:55:40 +00007338 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007339 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00007340 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00007341 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00007342 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00007343 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00007344 if (!LHSType->isReferenceType()) {
George Burgess IV45461812015-10-11 20:13:20 +00007345 // FIXME: We potentially allocate here even if ConvertRHS is false.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007346 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
Richard Trieueb299142011-09-06 20:40:12 +00007347 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007348 return Incompatible;
7349 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00007350
Fariborz Jahaniana57d91c22014-07-25 19:45:01 +00007351 Expr *PRE = RHS.get()->IgnoreParenCasts();
7352 if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) {
7353 ObjCProtocolDecl *PDecl = OPE->getProtocol();
7354 if (PDecl && !PDecl->hasDefinition()) {
7355 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7356 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7357 }
7358 }
7359
John McCall8cb679e2010-11-15 09:13:47 +00007360 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007361 Sema::AssignConvertType result =
George Burgess IV45461812015-10-11 20:13:20 +00007362 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007363
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00007364 // C99 6.5.16.1p2: The value of the right operand is converted to the
7365 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00007366 // CheckAssignmentConstraints allows the left-hand side to be a reference,
7367 // so that we can use references in built-in functions even in C.
7368 // The getNonReferenceType() call makes sure that the resulting expression
7369 // does not have reference type.
Fariborz Jahanian374089e2013-07-31 17:12:26 +00007370 if (result != Incompatible && RHS.get()->getType() != LHSType) {
7371 QualType Ty = LHSType.getNonLValueExprType(Context);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007372 Expr *E = RHS.get();
Fariborz Jahanian374089e2013-07-31 17:12:26 +00007373 if (getLangOpts().ObjCAutoRefCount)
Fariborz Jahanian25eef192013-07-31 21:40:51 +00007374 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7375 DiagnoseCFAudited);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00007376 if (getLangOpts().ObjC1 &&
Fariborz Jahanian283bf892013-12-18 21:04:43 +00007377 (CheckObjCBridgeRelatedConversions(E->getLocStart(),
7378 LHSType, E->getType(), E) ||
7379 ConversionToObjCStringLiteralCheck(LHSType, E))) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007380 RHS = E;
Fariborz Jahanian381edf52013-12-16 22:54:37 +00007381 return Compatible;
7382 }
7383
George Burgess IV45461812015-10-11 20:13:20 +00007384 if (ConvertRHS)
7385 RHS = ImpCastExprToType(E, Ty, Kind);
Fariborz Jahanian374089e2013-07-31 17:12:26 +00007386 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00007387 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007388}
7389
Richard Trieueb299142011-09-06 20:40:12 +00007390QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7391 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007392 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00007393 << LHS.get()->getType() << RHS.get()->getType()
7394 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00007395 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00007396}
7397
Stephen Canon3ba640d2014-04-03 10:33:25 +00007398/// Try to convert a value of non-vector type to a vector type by converting
7399/// the type to the element type of the vector and then performing a splat.
7400/// If the language is OpenCL, we only use conversions that promote scalar
7401/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7402/// for float->int.
John McCall9b595db2014-02-04 23:58:19 +00007403///
7404/// \param scalar - if non-null, actually perform the conversions
7405/// \return true if the operation fails (but without diagnosing the failure)
Stephen Canon3ba640d2014-04-03 10:33:25 +00007406static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
John McCall9b595db2014-02-04 23:58:19 +00007407 QualType scalarTy,
7408 QualType vectorEltTy,
7409 QualType vectorTy) {
7410 // The conversion to apply to the scalar before splatting it,
7411 // if necessary.
7412 CastKind scalarCast = CK_Invalid;
Stephen Canon3ba640d2014-04-03 10:33:25 +00007413
John McCall9b595db2014-02-04 23:58:19 +00007414 if (vectorEltTy->isIntegralType(S.Context)) {
Stephen Canon3ba640d2014-04-03 10:33:25 +00007415 if (!scalarTy->isIntegralType(S.Context))
7416 return true;
7417 if (S.getLangOpts().OpenCL &&
7418 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
7419 return true;
7420 scalarCast = CK_IntegralCast;
John McCall9b595db2014-02-04 23:58:19 +00007421 } else if (vectorEltTy->isRealFloatingType()) {
7422 if (scalarTy->isRealFloatingType()) {
Stephen Canon3ba640d2014-04-03 10:33:25 +00007423 if (S.getLangOpts().OpenCL &&
7424 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
7425 return true;
7426 scalarCast = CK_FloatingCast;
John McCall9b595db2014-02-04 23:58:19 +00007427 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00007428 else if (scalarTy->isIntegralType(S.Context))
7429 scalarCast = CK_IntegralToFloating;
7430 else
7431 return true;
John McCall9b595db2014-02-04 23:58:19 +00007432 } else {
7433 return true;
7434 }
7435
7436 // Adjust scalar if desired.
7437 if (scalar) {
7438 if (scalarCast != CK_Invalid)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007439 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
7440 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
John McCall9b595db2014-02-04 23:58:19 +00007441 }
7442 return false;
7443}
7444
Richard Trieu859d23f2011-09-06 21:01:04 +00007445QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00007446 SourceLocation Loc, bool IsCompAssign,
7447 bool AllowBothBool,
7448 bool AllowBoolConversions) {
Richard Smith508ebf32011-10-28 03:31:48 +00007449 if (!IsCompAssign) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007450 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
Richard Smith508ebf32011-10-28 03:31:48 +00007451 if (LHS.isInvalid())
7452 return QualType();
7453 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007454 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
Richard Smith508ebf32011-10-28 03:31:48 +00007455 if (RHS.isInvalid())
7456 return QualType();
7457
Mike Stump4e1f26a2009-02-19 03:04:26 +00007458 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00007459 // For example, "const float" and "float" are equivalent.
John McCall9b595db2014-02-04 23:58:19 +00007460 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
7461 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007462
John McCall9b595db2014-02-04 23:58:19 +00007463 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
7464 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
7465 assert(LHSVecType || RHSVecType);
7466
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00007467 // AltiVec-style "vector bool op vector bool" combinations are allowed
7468 // for some operators but not others.
7469 if (!AllowBothBool &&
7470 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
7471 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
7472 return InvalidOperands(Loc, LHS, RHS);
7473
7474 // If the vector types are identical, return.
7475 if (Context.hasSameType(LHSType, RHSType))
7476 return LHSType;
7477
John McCall9b595db2014-02-04 23:58:19 +00007478 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
7479 if (LHSVecType && RHSVecType &&
Richard Trieu859d23f2011-09-06 21:01:04 +00007480 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
John McCall9b595db2014-02-04 23:58:19 +00007481 if (isa<ExtVectorType>(LHSVecType)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007482 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
Richard Trieu859d23f2011-09-06 21:01:04 +00007483 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00007484 }
7485
Richard Trieuba63ce62011-09-09 01:45:06 +00007486 if (!IsCompAssign)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007487 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
Richard Trieu859d23f2011-09-06 21:01:04 +00007488 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007489 }
7490
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00007491 // AllowBoolConversions says that bool and non-bool AltiVec vectors
7492 // can be mixed, with the result being the non-bool type. The non-bool
7493 // operand must have integer element type.
7494 if (AllowBoolConversions && LHSVecType && RHSVecType &&
7495 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
7496 (Context.getTypeSize(LHSVecType->getElementType()) ==
7497 Context.getTypeSize(RHSVecType->getElementType()))) {
7498 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
7499 LHSVecType->getElementType()->isIntegerType() &&
7500 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
7501 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
7502 return LHSType;
7503 }
7504 if (!IsCompAssign &&
7505 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
7506 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
7507 RHSVecType->getElementType()->isIntegerType()) {
7508 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
7509 return RHSType;
7510 }
7511 }
7512
Stephen Canon3ba640d2014-04-03 10:33:25 +00007513 // If there's an ext-vector type and a scalar, try to convert the scalar to
7514 // the vector element type and splat.
7515 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
7516 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
7517 LHSVecType->getElementType(), LHSType))
7518 return LHSType;
7519 }
7520 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007521 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
7522 LHSType, RHSVecType->getElementType(),
7523 RHSType))
Stephen Canon3ba640d2014-04-03 10:33:25 +00007524 return RHSType;
7525 }
7526
John McCall9b595db2014-02-04 23:58:19 +00007527 // If we're allowing lax vector conversions, only the total (data) size
7528 // needs to be the same.
7529 // FIXME: Should we really be allowing this?
7530 // FIXME: We really just pick the LHS type arbitrarily?
7531 if (isLaxVectorConversion(RHSType, LHSType)) {
7532 QualType resultType = LHSType;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007533 RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast);
John McCall9b595db2014-02-04 23:58:19 +00007534 return resultType;
Eli Friedman1408bc92011-06-23 18:10:35 +00007535 }
7536
John McCall9b595db2014-02-04 23:58:19 +00007537 // Okay, the expression is invalid.
7538
7539 // If there's a non-vector, non-real operand, diagnose that.
7540 if ((!RHSVecType && !RHSType->isRealType()) ||
7541 (!LHSVecType && !LHSType->isRealType())) {
Argyrios Kyrtzidisd07dcdb2014-01-07 07:59:31 +00007542 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
John McCall9b595db2014-02-04 23:58:19 +00007543 << LHSType << RHSType
7544 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Argyrios Kyrtzidisd07dcdb2014-01-07 07:59:31 +00007545 return QualType();
7546 }
7547
Alexey Baderf961e752015-08-30 18:06:39 +00007548 // OpenCL V1.1 6.2.6.p1:
7549 // If the operands are of more than one vector type, then an error shall
7550 // occur. Implicit conversions between vector types are not permitted, per
7551 // section 6.2.1.
7552 if (getLangOpts().OpenCL &&
7553 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
7554 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
7555 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
7556 << RHSType;
7557 return QualType();
7558 }
7559
John McCall9b595db2014-02-04 23:58:19 +00007560 // Otherwise, use the generic diagnostic.
Chris Lattner377d1f82008-11-18 22:52:51 +00007561 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John McCall9b595db2014-02-04 23:58:19 +00007562 << LHSType << RHSType
Richard Trieu859d23f2011-09-06 21:01:04 +00007563 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00007564 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00007565}
7566
Richard Trieuf8916e12011-09-16 00:53:10 +00007567// checkArithmeticNull - Detect when a NULL constant is used improperly in an
7568// expression. These are mainly cases where the null pointer is used as an
7569// integer instead of a pointer.
7570static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
7571 SourceLocation Loc, bool IsCompare) {
7572 // The canonical way to check for a GNU null is with isNullPointerConstant,
7573 // but we use a bit of a hack here for speed; this is a relatively
7574 // hot path, and isNullPointerConstant is slow.
7575 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
7576 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
7577
7578 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
7579
7580 // Avoid analyzing cases where the result will either be invalid (and
7581 // diagnosed as such) or entirely valid and not something to warn about.
7582 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
7583 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
7584 return;
7585
7586 // Comparison operations would not make sense with a null pointer no matter
7587 // what the other expression is.
7588 if (!IsCompare) {
7589 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
7590 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
7591 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
7592 return;
7593 }
7594
7595 // The rest of the operations only make sense with a null pointer
7596 // if the other expression is a pointer.
7597 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
7598 NonNullType->canDecayToPointerType())
7599 return;
7600
7601 S.Diag(Loc, diag::warn_null_in_comparison_operation)
7602 << LHSNull /* LHS is NULL */ << NonNullType
7603 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7604}
7605
Davide Italianof76da1d2015-08-01 10:13:39 +00007606static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
7607 ExprResult &RHS,
7608 SourceLocation Loc, bool IsDiv) {
7609 // Check for division/remainder by zero.
Davide Italianof76da1d2015-08-01 10:13:39 +00007610 llvm::APSInt RHSValue;
7611 if (!RHS.get()->isValueDependent() &&
7612 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
7613 S.DiagRuntimeBehavior(Loc, RHS.get(),
Craig Topperda7b27f2015-11-17 05:40:09 +00007614 S.PDiag(diag::warn_remainder_division_by_zero)
7615 << IsDiv << RHS.get()->getSourceRange());
Davide Italianof76da1d2015-08-01 10:13:39 +00007616}
7617
Richard Trieu859d23f2011-09-06 21:01:04 +00007618QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00007619 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007620 bool IsCompAssign, bool IsDiv) {
Richard Trieuf8916e12011-09-16 00:53:10 +00007621 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7622
Richard Trieu859d23f2011-09-06 21:01:04 +00007623 if (LHS.get()->getType()->isVectorType() ||
7624 RHS.get()->getType()->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00007625 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
7626 /*AllowBothBool*/getLangOpts().AltiVec,
7627 /*AllowBoolConversions*/false);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007628
Richard Trieuba63ce62011-09-09 01:45:06 +00007629 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00007630 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007631 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007632
David Chisnallfa35df62012-01-16 17:27:18 +00007633
Eli Friedman93ee5ca2012-06-16 02:19:17 +00007634 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu859d23f2011-09-06 21:01:04 +00007635 return InvalidOperands(Loc, LHS, RHS);
Davide Italianof76da1d2015-08-01 10:13:39 +00007636 if (IsDiv)
7637 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
Chris Lattnerfaa54172010-01-12 21:23:57 +00007638 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00007639}
7640
Chris Lattnerfaa54172010-01-12 21:23:57 +00007641QualType Sema::CheckRemainderOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00007642 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00007643 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7644
Richard Trieu859d23f2011-09-06 21:01:04 +00007645 if (LHS.get()->getType()->isVectorType() ||
7646 RHS.get()->getType()->isVectorType()) {
7647 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7648 RHS.get()->getType()->hasIntegerRepresentation())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00007649 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
7650 /*AllowBothBool*/getLangOpts().AltiVec,
7651 /*AllowBoolConversions*/false);
Richard Trieu859d23f2011-09-06 21:01:04 +00007652 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00007653 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007654
Richard Trieuba63ce62011-09-09 01:45:06 +00007655 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00007656 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007657 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007658
Eli Friedman93ee5ca2012-06-16 02:19:17 +00007659 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu859d23f2011-09-06 21:01:04 +00007660 return InvalidOperands(Loc, LHS, RHS);
Davide Italianof76da1d2015-08-01 10:13:39 +00007661 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
Chris Lattnerfaa54172010-01-12 21:23:57 +00007662 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007663}
7664
Chandler Carruthc9332212011-06-27 08:02:19 +00007665/// \brief Diagnose invalid arithmetic on two void pointers.
7666static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00007667 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007668 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00007669 ? diag::err_typecheck_pointer_arith_void_type
7670 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00007671 << 1 /* two pointers */ << LHSExpr->getSourceRange()
7672 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00007673}
7674
7675/// \brief Diagnose invalid arithmetic on a void pointer.
7676static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
7677 Expr *Pointer) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007678 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00007679 ? diag::err_typecheck_pointer_arith_void_type
7680 : diag::ext_gnu_void_ptr)
7681 << 0 /* one pointer */ << Pointer->getSourceRange();
7682}
7683
7684/// \brief Diagnose invalid arithmetic on two function pointers.
7685static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
7686 Expr *LHS, Expr *RHS) {
7687 assert(LHS->getType()->isAnyPointerType());
7688 assert(RHS->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00007689 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00007690 ? diag::err_typecheck_pointer_arith_function_type
7691 : diag::ext_gnu_ptr_func_arith)
7692 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
7693 // We only show the second type if it differs from the first.
7694 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
7695 RHS->getType())
7696 << RHS->getType()->getPointeeType()
7697 << LHS->getSourceRange() << RHS->getSourceRange();
7698}
7699
7700/// \brief Diagnose invalid arithmetic on a function pointer.
7701static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
7702 Expr *Pointer) {
7703 assert(Pointer->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00007704 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00007705 ? diag::err_typecheck_pointer_arith_function_type
7706 : diag::ext_gnu_ptr_func_arith)
7707 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
7708 << 0 /* one pointer, so only one type */
7709 << Pointer->getSourceRange();
7710}
7711
Richard Trieu993f3ab2011-09-12 18:08:02 +00007712/// \brief Emit error if Operand is incomplete pointer type
Richard Trieuaba22802011-09-02 02:15:37 +00007713///
7714/// \returns True if pointer has incomplete type
7715static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
7716 Expr *Operand) {
David Majnemercf7d1642015-02-12 21:07:34 +00007717 QualType ResType = Operand->getType();
7718 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7719 ResType = ResAtomicType->getValueType();
7720
7721 assert(ResType->isAnyPointerType() && !ResType->isDependentType());
7722 QualType PointeeTy = ResType->getPointeeType();
John McCallf2538342012-07-31 05:14:30 +00007723 return S.RequireCompleteType(Loc, PointeeTy,
7724 diag::err_typecheck_arithmetic_incomplete_type,
7725 PointeeTy, Operand->getSourceRange());
Richard Trieuaba22802011-09-02 02:15:37 +00007726}
7727
Chandler Carruthc9332212011-06-27 08:02:19 +00007728/// \brief Check the validity of an arithmetic pointer operand.
7729///
7730/// If the operand has pointer type, this code will check for pointer types
7731/// which are invalid in arithmetic operations. These will be diagnosed
7732/// appropriately, including whether or not the use is supported as an
7733/// extension.
7734///
7735/// \returns True when the operand is valid to use (even if as an extension).
7736static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
7737 Expr *Operand) {
David Majnemercf7d1642015-02-12 21:07:34 +00007738 QualType ResType = Operand->getType();
7739 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7740 ResType = ResAtomicType->getValueType();
Chandler Carruthc9332212011-06-27 08:02:19 +00007741
David Majnemercf7d1642015-02-12 21:07:34 +00007742 if (!ResType->isAnyPointerType()) return true;
7743
7744 QualType PointeeTy = ResType->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00007745 if (PointeeTy->isVoidType()) {
7746 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00007747 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00007748 }
7749 if (PointeeTy->isFunctionType()) {
7750 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00007751 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00007752 }
7753
Richard Trieuaba22802011-09-02 02:15:37 +00007754 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00007755
7756 return true;
7757}
7758
7759/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
7760/// operands.
7761///
7762/// This routine will diagnose any invalid arithmetic on pointer operands much
7763/// like \see checkArithmeticOpPointerOperand. However, it has special logic
7764/// for emitting a single diagnostic even for operations where both LHS and RHS
7765/// are (potentially problematic) pointers.
7766///
7767/// \returns True when the operand is valid to use (even if as an extension).
7768static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00007769 Expr *LHSExpr, Expr *RHSExpr) {
7770 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
7771 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00007772 if (!isLHSPointer && !isRHSPointer) return true;
7773
7774 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00007775 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
7776 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00007777
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00007778 // if both are pointers check if operation is valid wrt address spaces
Anastasia Stulovae6e08232015-09-30 13:49:55 +00007779 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00007780 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
7781 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
7782 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
7783 S.Diag(Loc,
7784 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7785 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
7786 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
7787 return false;
7788 }
7789 }
7790
Chandler Carruthc9332212011-06-27 08:02:19 +00007791 // Check for arithmetic on pointers to incomplete types.
7792 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
7793 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
7794 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00007795 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
7796 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
7797 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00007798
David Blaikiebbafb8a2012-03-11 07:00:24 +00007799 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00007800 }
7801
7802 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
7803 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
7804 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00007805 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
7806 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
7807 RHSExpr);
7808 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00007809
David Blaikiebbafb8a2012-03-11 07:00:24 +00007810 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00007811 }
7812
John McCallf2538342012-07-31 05:14:30 +00007813 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
7814 return false;
7815 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
7816 return false;
Richard Trieuaba22802011-09-02 02:15:37 +00007817
Chandler Carruthc9332212011-06-27 08:02:19 +00007818 return true;
7819}
7820
Nico Weberccec40d2012-03-02 22:01:22 +00007821/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
7822/// literal.
7823static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
7824 Expr *LHSExpr, Expr *RHSExpr) {
7825 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
7826 Expr* IndexExpr = RHSExpr;
7827 if (!StrExpr) {
7828 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
7829 IndexExpr = LHSExpr;
7830 }
7831
7832 bool IsStringPlusInt = StrExpr &&
7833 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
David Majnemer7e217452014-12-15 10:00:35 +00007834 if (!IsStringPlusInt || IndexExpr->isValueDependent())
Nico Weberccec40d2012-03-02 22:01:22 +00007835 return;
7836
7837 llvm::APSInt index;
7838 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
7839 unsigned StrLenWithNull = StrExpr->getLength() + 1;
7840 if (index.isNonNegative() &&
7841 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
7842 index.isUnsigned()))
7843 return;
7844 }
7845
7846 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7847 Self.Diag(OpLoc, diag::warn_string_plus_int)
7848 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
7849
7850 // Only print a fixit for "str" + int, not for int + "str".
7851 if (IndexExpr == RHSExpr) {
Craig Topper07fa1762015-11-15 02:31:46 +00007852 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
Jordan Rose55659412013-10-25 16:52:00 +00007853 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
Nico Weberccec40d2012-03-02 22:01:22 +00007854 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7855 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7856 << FixItHint::CreateInsertion(EndLoc, "]");
7857 } else
Jordan Rose55659412013-10-25 16:52:00 +00007858 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7859}
7860
7861/// \brief Emit a warning when adding a char literal to a string.
7862static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
7863 Expr *LHSExpr, Expr *RHSExpr) {
Daniel Marjamaki36859002014-12-15 20:22:33 +00007864 const Expr *StringRefExpr = LHSExpr;
Jordan Rose55659412013-10-25 16:52:00 +00007865 const CharacterLiteral *CharExpr =
7866 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
Daniel Marjamaki36859002014-12-15 20:22:33 +00007867
7868 if (!CharExpr) {
Jordan Rose55659412013-10-25 16:52:00 +00007869 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
Daniel Marjamaki36859002014-12-15 20:22:33 +00007870 StringRefExpr = RHSExpr;
Jordan Rose55659412013-10-25 16:52:00 +00007871 }
7872
7873 if (!CharExpr || !StringRefExpr)
7874 return;
7875
7876 const QualType StringType = StringRefExpr->getType();
7877
7878 // Return if not a PointerType.
7879 if (!StringType->isAnyPointerType())
7880 return;
7881
7882 // Return if not a CharacterType.
7883 if (!StringType->getPointeeType()->isAnyCharacterType())
7884 return;
7885
7886 ASTContext &Ctx = Self.getASTContext();
7887 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7888
7889 const QualType CharType = CharExpr->getType();
7890 if (!CharType->isAnyCharacterType() &&
7891 CharType->isIntegerType() &&
7892 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
7893 Self.Diag(OpLoc, diag::warn_string_plus_char)
7894 << DiagRange << Ctx.CharTy;
7895 } else {
7896 Self.Diag(OpLoc, diag::warn_string_plus_char)
7897 << DiagRange << CharExpr->getType();
7898 }
7899
7900 // Only print a fixit for str + char, not for char + str.
7901 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
Craig Topper07fa1762015-11-15 02:31:46 +00007902 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
Jordan Rose55659412013-10-25 16:52:00 +00007903 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7904 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7905 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7906 << FixItHint::CreateInsertion(EndLoc, "]");
7907 } else {
7908 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7909 }
Nico Weberccec40d2012-03-02 22:01:22 +00007910}
7911
Richard Trieu993f3ab2011-09-12 18:08:02 +00007912/// \brief Emit error when two pointers are incompatible.
Richard Trieub10c6312011-09-01 22:53:23 +00007913static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00007914 Expr *LHSExpr, Expr *RHSExpr) {
7915 assert(LHSExpr->getType()->isAnyPointerType());
7916 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00007917 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00007918 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
7919 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00007920}
7921
Craig Toppera92ffb02015-12-10 08:51:49 +00007922// C99 6.5.6
7923QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
7924 SourceLocation Loc, BinaryOperatorKind Opc,
7925 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00007926 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7927
Richard Trieu4ae7e972011-09-06 21:13:51 +00007928 if (LHS.get()->getType()->isVectorType() ||
7929 RHS.get()->getType()->isVectorType()) {
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00007930 QualType compType = CheckVectorOperands(
7931 LHS, RHS, Loc, CompLHSTy,
7932 /*AllowBothBool*/getLangOpts().AltiVec,
7933 /*AllowBoolConversions*/getLangOpts().ZVector);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007934 if (CompLHSTy) *CompLHSTy = compType;
7935 return compType;
7936 }
Steve Naroff7a5af782007-07-13 16:58:59 +00007937
Richard Trieu4ae7e972011-09-06 21:13:51 +00007938 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7939 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007940 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00007941
Jordan Rose55659412013-10-25 16:52:00 +00007942 // Diagnose "string literal" '+' int and string '+' "char literal".
7943 if (Opc == BO_Add) {
Nico Weberccec40d2012-03-02 22:01:22 +00007944 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
Jordan Rose55659412013-10-25 16:52:00 +00007945 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
7946 }
Nico Weberccec40d2012-03-02 22:01:22 +00007947
Steve Naroffe4718892007-04-27 18:30:00 +00007948 // handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00007949 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007950 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007951 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007952 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00007953
John McCallf2538342012-07-31 05:14:30 +00007954 // Type-checking. Ultimately the pointer's going to be in PExp;
7955 // note that we bias towards the LHS being the pointer.
7956 Expr *PExp = LHS.get(), *IExp = RHS.get();
Eli Friedman8e122982008-05-18 18:08:51 +00007957
John McCallf2538342012-07-31 05:14:30 +00007958 bool isObjCPointer;
7959 if (PExp->getType()->isPointerType()) {
7960 isObjCPointer = false;
7961 } else if (PExp->getType()->isObjCObjectPointerType()) {
7962 isObjCPointer = true;
7963 } else {
7964 std::swap(PExp, IExp);
7965 if (PExp->getType()->isPointerType()) {
7966 isObjCPointer = false;
7967 } else if (PExp->getType()->isObjCObjectPointerType()) {
7968 isObjCPointer = true;
7969 } else {
7970 return InvalidOperands(Loc, LHS, RHS);
7971 }
7972 }
7973 assert(PExp->getType()->isAnyPointerType());
Chandler Carruthc9332212011-06-27 08:02:19 +00007974
Richard Trieub420bca2011-09-12 18:37:54 +00007975 if (!IExp->getType()->isIntegerType())
7976 return InvalidOperands(Loc, LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00007977
Richard Trieub420bca2011-09-12 18:37:54 +00007978 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
7979 return QualType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007980
John McCallf2538342012-07-31 05:14:30 +00007981 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
Richard Trieub420bca2011-09-12 18:37:54 +00007982 return QualType();
7983
7984 // Check array bounds for pointer arithemtic
7985 CheckArrayAccess(PExp, IExp);
7986
7987 if (CompLHSTy) {
7988 QualType LHSTy = Context.isPromotableBitField(LHS.get());
7989 if (LHSTy.isNull()) {
7990 LHSTy = LHS.get()->getType();
7991 if (LHSTy->isPromotableIntegerType())
7992 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00007993 }
Richard Trieub420bca2011-09-12 18:37:54 +00007994 *CompLHSTy = LHSTy;
Eli Friedman8e122982008-05-18 18:08:51 +00007995 }
7996
Richard Trieub420bca2011-09-12 18:37:54 +00007997 return PExp->getType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00007998}
7999
Chris Lattner2a3569b2008-04-07 05:30:13 +00008000// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00008001QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00008002 SourceLocation Loc,
8003 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00008004 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8005
Richard Trieu4ae7e972011-09-06 21:13:51 +00008006 if (LHS.get()->getType()->isVectorType() ||
8007 RHS.get()->getType()->isVectorType()) {
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00008008 QualType compType = CheckVectorOperands(
8009 LHS, RHS, Loc, CompLHSTy,
8010 /*AllowBothBool*/getLangOpts().AltiVec,
8011 /*AllowBoolConversions*/getLangOpts().ZVector);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008012 if (CompLHSTy) *CompLHSTy = compType;
8013 return compType;
8014 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008015
Richard Trieu4ae7e972011-09-06 21:13:51 +00008016 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8017 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00008018 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00008019
Chris Lattner4d62f422007-12-09 21:53:25 +00008020 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008021
Chris Lattner4d62f422007-12-09 21:53:25 +00008022 // Handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00008023 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008024 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00008025 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008026 }
Mike Stump11289f42009-09-09 15:08:12 +00008027
Chris Lattner4d62f422007-12-09 21:53:25 +00008028 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00008029 if (LHS.get()->getType()->isAnyPointerType()) {
8030 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00008031
Chris Lattner12bdebb2009-04-24 23:50:08 +00008032 // Diagnose bad cases where we step over interface counts.
John McCallf2538342012-07-31 05:14:30 +00008033 if (LHS.get()->getType()->isObjCObjectPointerType() &&
8034 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00008035 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00008036
Chris Lattner4d62f422007-12-09 21:53:25 +00008037 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00008038 if (RHS.get()->getType()->isIntegerType()) {
8039 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00008040 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00008041
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008042 // Check array bounds for pointer arithemtic
Craig Topperc3ec1492014-05-26 06:22:03 +00008043 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
Richard Smith13f67182011-12-16 19:31:14 +00008044 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008045
Richard Trieu4ae7e972011-09-06 21:13:51 +00008046 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8047 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00008048 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008049
Chris Lattner4d62f422007-12-09 21:53:25 +00008050 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00008051 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00008052 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00008053 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00008054
David Blaikiebbafb8a2012-03-11 07:00:24 +00008055 if (getLangOpts().CPlusPlus) {
Eli Friedman168fe152009-05-16 13:54:38 +00008056 // Pointee types must be the same: C++ [expr.add]
8057 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00008058 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00008059 }
8060 } else {
8061 // Pointee types must be compatible C99 6.5.6p3
8062 if (!Context.typesAreCompatible(
8063 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8064 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00008065 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00008066 return QualType();
8067 }
Chris Lattner4d62f422007-12-09 21:53:25 +00008068 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008069
Chandler Carruthc9332212011-06-27 08:02:19 +00008070 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00008071 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00008072 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008073
Richard Smith84c6b3d2013-09-10 21:34:14 +00008074 // The pointee type may have zero size. As an extension, a structure or
8075 // union may have zero size or an array may have zero length. In this
8076 // case subtraction does not make sense.
8077 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8078 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8079 if (ElementSize.isZero()) {
8080 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8081 << rpointee.getUnqualifiedType()
8082 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8083 }
8084 }
8085
Richard Trieu4ae7e972011-09-06 21:13:51 +00008086 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00008087 return Context.getPointerDiffType();
8088 }
8089 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008090
Richard Trieu4ae7e972011-09-06 21:13:51 +00008091 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008092}
8093
Douglas Gregor0bf31402010-10-08 23:50:27 +00008094static bool isScopedEnumerationType(QualType T) {
Richard Smith43d3f552015-01-14 00:33:10 +00008095 if (const EnumType *ET = T->getAs<EnumType>())
Douglas Gregor0bf31402010-10-08 23:50:27 +00008096 return ET->getDecl()->isScoped();
8097 return false;
8098}
8099
Richard Trieue4a19fb2011-09-06 21:21:28 +00008100static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Craig Toppera92ffb02015-12-10 08:51:49 +00008101 SourceLocation Loc, BinaryOperatorKind Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00008102 QualType LHSType) {
David Tweed042e0882013-01-07 16:43:27 +00008103 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8104 // so skip remaining warnings as we don't want to modify values within Sema.
8105 if (S.getLangOpts().OpenCL)
8106 return;
8107
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008108 llvm::APSInt Right;
8109 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00008110 if (RHS.get()->isValueDependent() ||
Davide Italiano346048a2015-03-26 21:37:49 +00008111 !RHS.get()->EvaluateAsInt(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008112 return;
8113
8114 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00008115 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00008116 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00008117 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008118 return;
8119 }
8120 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00008121 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008122 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00008123 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00008124 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00008125 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008126 return;
8127 }
8128 if (Opc != BO_Shl)
8129 return;
8130
8131 // When left shifting an ICE which is signed, we can check for overflow which
8132 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8133 // integers have defined behavior modulo one more than the maximum value
8134 // representable in the result type, so never warn for those.
8135 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00008136 if (LHS.get()->isValueDependent() ||
Davide Italianobf0f7752015-07-06 18:02:09 +00008137 LHSType->hasUnsignedIntegerRepresentation() ||
8138 !LHS.get()->EvaluateAsInt(Left, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008139 return;
Davide Italianobf0f7752015-07-06 18:02:09 +00008140
8141 // If LHS does not have a signed type and non-negative value
8142 // then, the behavior is undefined. Warn about it.
8143 if (Left.isNegative()) {
8144 S.DiagRuntimeBehavior(Loc, LHS.get(),
8145 S.PDiag(diag::warn_shift_lhs_negative)
8146 << LHS.get()->getSourceRange());
8147 return;
8148 }
8149
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008150 llvm::APInt ResultBits =
8151 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8152 if (LeftBits.uge(ResultBits))
8153 return;
8154 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8155 Result = Result.shl(Right);
8156
Ted Kremenek70f05fd2011-06-15 00:54:52 +00008157 // Print the bit representation of the signed integer as an unsigned
8158 // hexadecimal number.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008159 SmallString<40> HexResult;
Ted Kremenek70f05fd2011-06-15 00:54:52 +00008160 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8161
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008162 // If we are only missing a sign bit, this is less likely to result in actual
8163 // bugs -- if the result is cast back to an unsigned type, it will have the
8164 // expected value. Thus we place this behind a different warning that can be
8165 // turned off separately if needed.
8166 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00008167 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Yaron Keren92e1b622015-03-18 10:17:07 +00008168 << HexResult << LHSType
Richard Trieue4a19fb2011-09-06 21:21:28 +00008169 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008170 return;
8171 }
8172
8173 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00008174 << HexResult.str() << Result.getMinSignedBits() << LHSType
8175 << Left.getBitWidth() << LHS.get()->getSourceRange()
8176 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008177}
8178
Sameer Sahasrabuddhea75db662015-02-25 05:48:23 +00008179/// \brief Return the resulting type when an OpenCL vector is shifted
8180/// by a scalar or vector shift amount.
8181static QualType checkOpenCLVectorShift(Sema &S,
8182 ExprResult &LHS, ExprResult &RHS,
8183 SourceLocation Loc, bool IsCompAssign) {
8184 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8185 if (!LHS.get()->getType()->isVectorType()) {
8186 S.Diag(Loc, diag::err_shift_rhs_only_vector)
8187 << RHS.get()->getType() << LHS.get()->getType()
8188 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8189 return QualType();
8190 }
8191
8192 if (!IsCompAssign) {
8193 LHS = S.UsualUnaryConversions(LHS.get());
8194 if (LHS.isInvalid()) return QualType();
8195 }
8196
8197 RHS = S.UsualUnaryConversions(RHS.get());
8198 if (RHS.isInvalid()) return QualType();
8199
8200 QualType LHSType = LHS.get()->getType();
8201 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
8202 QualType LHSEleType = LHSVecTy->getElementType();
8203
8204 // Note that RHS might not be a vector.
8205 QualType RHSType = RHS.get()->getType();
8206 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8207 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8208
8209 // OpenCL v1.1 s6.3.j says that the operands need to be integers.
8210 if (!LHSEleType->isIntegerType()) {
8211 S.Diag(Loc, diag::err_typecheck_expect_int)
8212 << LHS.get()->getType() << LHS.get()->getSourceRange();
8213 return QualType();
8214 }
8215
8216 if (!RHSEleType->isIntegerType()) {
8217 S.Diag(Loc, diag::err_typecheck_expect_int)
8218 << RHS.get()->getType() << RHS.get()->getSourceRange();
8219 return QualType();
8220 }
8221
8222 if (RHSVecTy) {
8223 // OpenCL v1.1 s6.3.j says that for vector types, the operators
8224 // are applied component-wise. So if RHS is a vector, then ensure
8225 // that the number of elements is the same as LHS...
8226 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8227 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8228 << LHS.get()->getType() << RHS.get()->getType()
8229 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8230 return QualType();
8231 }
8232 } else {
8233 // ...else expand RHS to match the number of elements in LHS.
8234 QualType VecTy =
8235 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8236 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8237 }
8238
8239 return LHSType;
8240}
8241
Chris Lattner2a3569b2008-04-07 05:30:13 +00008242// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00008243QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Craig Toppera92ffb02015-12-10 08:51:49 +00008244 SourceLocation Loc, BinaryOperatorKind Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008245 bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00008246 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8247
Nate Begemane46ee9a2009-10-25 02:26:48 +00008248 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00008249 if (LHS.get()->getType()->isVectorType() ||
Sameer Sahasrabuddhea75db662015-02-25 05:48:23 +00008250 RHS.get()->getType()->isVectorType()) {
8251 if (LangOpts.OpenCL)
8252 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00008253 if (LangOpts.ZVector) {
8254 // The shift operators for the z vector extensions work basically
8255 // like OpenCL shifts, except that neither the LHS nor the RHS is
8256 // allowed to be a "vector bool".
8257 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8258 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8259 return InvalidOperands(Loc, LHS, RHS);
8260 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8261 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8262 return InvalidOperands(Loc, LHS, RHS);
8263 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8264 }
8265 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8266 /*AllowBothBool*/true,
8267 /*AllowBoolConversions*/false);
Sameer Sahasrabuddhea75db662015-02-25 05:48:23 +00008268 }
Nate Begemane46ee9a2009-10-25 02:26:48 +00008269
Chris Lattner5c11c412007-12-12 05:47:28 +00008270 // Shifts don't perform usual arithmetic conversions, they just do integer
8271 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008272
John McCall57cdd882010-12-16 19:28:59 +00008273 // For the LHS, do usual unary conversions, but then reset them away
8274 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00008275 ExprResult OldLHS = LHS;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008276 LHS = UsualUnaryConversions(LHS.get());
Richard Trieue4a19fb2011-09-06 21:21:28 +00008277 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00008278 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00008279 QualType LHSType = LHS.get()->getType();
Richard Trieuba63ce62011-09-09 01:45:06 +00008280 if (IsCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00008281
8282 // The RHS is simpler.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008283 RHS = UsualUnaryConversions(RHS.get());
Richard Trieue4a19fb2011-09-06 21:21:28 +00008284 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00008285 return QualType();
Douglas Gregor8997dac2013-04-16 15:41:08 +00008286 QualType RHSType = RHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00008287
Douglas Gregor8997dac2013-04-16 15:41:08 +00008288 // C99 6.5.7p2: Each of the operands shall have integer type.
8289 if (!LHSType->hasIntegerRepresentation() ||
8290 !RHSType->hasIntegerRepresentation())
8291 return InvalidOperands(Loc, LHS, RHS);
8292
8293 // C++0x: Don't allow scoped enums. FIXME: Use something better than
8294 // hasIntegerRepresentation() above instead of this.
8295 if (isScopedEnumerationType(LHSType) ||
8296 isScopedEnumerationType(RHSType)) {
8297 return InvalidOperands(Loc, LHS, RHS);
8298 }
Ryan Flynnf53fab82009-08-07 16:20:20 +00008299 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00008300 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00008301
Chris Lattner5c11c412007-12-12 05:47:28 +00008302 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00008303 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00008304}
8305
Chandler Carruth17773fc2010-07-10 12:30:03 +00008306static bool IsWithinTemplateSpecialization(Decl *D) {
8307 if (DeclContext *DC = D->getDeclContext()) {
8308 if (isa<ClassTemplateSpecializationDecl>(DC))
8309 return true;
8310 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8311 return FD->isFunctionTemplateSpecialization();
8312 }
8313 return false;
8314}
8315
Richard Trieueea56f72011-09-02 03:48:46 +00008316/// If two different enums are compared, raise a warning.
Ted Kremenekf2ca8ec2013-01-30 19:10:21 +00008317static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8318 Expr *RHS) {
8319 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8320 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00008321
8322 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8323 if (!LHSEnumType)
8324 return;
8325 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8326 if (!RHSEnumType)
8327 return;
8328
8329 // Ignore anonymous enums.
8330 if (!LHSEnumType->getDecl()->getIdentifier())
8331 return;
8332 if (!RHSEnumType->getDecl()->getIdentifier())
8333 return;
8334
8335 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8336 return;
8337
8338 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8339 << LHSStrippedType << RHSStrippedType
Ted Kremenekf2ca8ec2013-01-30 19:10:21 +00008340 << LHS->getSourceRange() << RHS->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00008341}
8342
Richard Trieudd82a5c2011-09-02 02:55:45 +00008343/// \brief Diagnose bad pointer comparisons.
8344static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00008345 ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00008346 bool IsError) {
8347 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieudd82a5c2011-09-02 02:55:45 +00008348 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00008349 << LHS.get()->getType() << RHS.get()->getType()
8350 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00008351}
8352
8353/// \brief Returns false if the pointers are converted to a composite type,
8354/// true otherwise.
8355static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00008356 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00008357 // C++ [expr.rel]p2:
8358 // [...] Pointer conversions (4.10) and qualification
8359 // conversions (4.4) are performed on pointer operands (or on
8360 // a pointer operand and a null pointer constant) to bring
8361 // them to their composite pointer type. [...]
8362 //
8363 // C++ [expr.eq]p1 uses the same notion for (in)equality
8364 // comparisons of pointers.
8365
8366 // C++ [expr.eq]p2:
8367 // In addition, pointers to members can be compared, or a pointer to
8368 // member and a null pointer constant. Pointer to member conversions
8369 // (4.11) and qualification conversions (4.4) are performed to bring
8370 // them to a common type. If one operand is a null pointer constant,
8371 // the common type is the type of the other operand. Otherwise, the
8372 // common type is a pointer to member type similar (4.4) to the type
8373 // of one of the operands, with a cv-qualification signature (4.4)
8374 // that is the union of the cv-qualification signatures of the operand
8375 // types.
8376
Richard Trieu1762d7c2011-09-06 21:27:33 +00008377 QualType LHSType = LHS.get()->getType();
8378 QualType RHSType = RHS.get()->getType();
8379 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
8380 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieudd82a5c2011-09-02 02:55:45 +00008381
8382 bool NonStandardCompositeType = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00008383 bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
Richard Trieu1762d7c2011-09-06 21:27:33 +00008384 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00008385 if (T.isNull()) {
Richard Trieu1762d7c2011-09-06 21:27:33 +00008386 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieudd82a5c2011-09-02 02:55:45 +00008387 return true;
8388 }
8389
8390 if (NonStandardCompositeType)
8391 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieu1762d7c2011-09-06 21:27:33 +00008392 << LHSType << RHSType << T << LHS.get()->getSourceRange()
8393 << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00008394
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008395 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
8396 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00008397 return false;
8398}
8399
8400static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00008401 ExprResult &LHS,
8402 ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00008403 bool IsError) {
8404 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
8405 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00008406 << LHS.get()->getType() << RHS.get()->getType()
8407 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00008408}
8409
Jordan Rosed49a33e2012-06-08 21:14:25 +00008410static bool isObjCObjectLiteral(ExprResult &E) {
Jordan Rosee2028132012-11-09 23:55:21 +00008411 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
Jordan Rosed49a33e2012-06-08 21:14:25 +00008412 case Stmt::ObjCArrayLiteralClass:
8413 case Stmt::ObjCDictionaryLiteralClass:
8414 case Stmt::ObjCStringLiteralClass:
8415 case Stmt::ObjCBoxedExprClass:
8416 return true;
8417 default:
8418 // Note that ObjCBoolLiteral is NOT an object literal!
8419 return false;
8420 }
8421}
8422
Jordan Rose7660f782012-07-17 17:46:40 +00008423static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
Benjamin Kramer25c05102013-02-15 15:17:50 +00008424 const ObjCObjectPointerType *Type =
8425 LHS->getType()->getAs<ObjCObjectPointerType>();
8426
8427 // If this is not actually an Objective-C object, bail out.
8428 if (!Type)
Jordan Rose7660f782012-07-17 17:46:40 +00008429 return false;
Benjamin Kramer25c05102013-02-15 15:17:50 +00008430
8431 // Get the LHS object's interface type.
8432 QualType InterfaceType = Type->getPointeeType();
Jordan Rose7660f782012-07-17 17:46:40 +00008433
8434 // If the RHS isn't an Objective-C object, bail out.
8435 if (!RHS->getType()->isObjCObjectPointerType())
8436 return false;
8437
8438 // Try to find the -isEqual: method.
8439 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
8440 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
8441 InterfaceType,
8442 /*instance=*/true);
8443 if (!Method) {
8444 if (Type->isObjCIdType()) {
8445 // For 'id', just check the global pool.
8446 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
Fariborz Jahanian890803f2015-04-15 17:26:21 +00008447 /*receiverId=*/true);
Jordan Rose7660f782012-07-17 17:46:40 +00008448 } else {
8449 // Check protocols.
Benjamin Kramer25c05102013-02-15 15:17:50 +00008450 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
Jordan Rose7660f782012-07-17 17:46:40 +00008451 /*instance=*/true);
8452 }
8453 }
8454
8455 if (!Method)
8456 return false;
8457
Alp Toker03376dc2014-07-07 09:02:20 +00008458 QualType T = Method->parameters()[0]->getType();
Jordan Rose7660f782012-07-17 17:46:40 +00008459 if (!T->isObjCObjectPointerType())
8460 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008461
8462 QualType R = Method->getReturnType();
Jordan Rose7660f782012-07-17 17:46:40 +00008463 if (!R->isScalarType())
8464 return false;
8465
8466 return true;
8467}
8468
Ted Kremenek01a33f82012-12-21 21:59:36 +00008469Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
8470 FromE = FromE->IgnoreParenImpCasts();
8471 switch (FromE->getStmtClass()) {
8472 default:
8473 break;
8474 case Stmt::ObjCStringLiteralClass:
8475 // "string literal"
8476 return LK_String;
8477 case Stmt::ObjCArrayLiteralClass:
8478 // "array literal"
8479 return LK_Array;
8480 case Stmt::ObjCDictionaryLiteralClass:
8481 // "dictionary literal"
8482 return LK_Dictionary;
Ted Kremenek64873352012-12-21 22:46:35 +00008483 case Stmt::BlockExprClass:
8484 return LK_Block;
Ted Kremenek01a33f82012-12-21 21:59:36 +00008485 case Stmt::ObjCBoxedExprClass: {
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008486 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
Ted Kremenek01a33f82012-12-21 21:59:36 +00008487 switch (Inner->getStmtClass()) {
8488 case Stmt::IntegerLiteralClass:
8489 case Stmt::FloatingLiteralClass:
8490 case Stmt::CharacterLiteralClass:
8491 case Stmt::ObjCBoolLiteralExprClass:
8492 case Stmt::CXXBoolLiteralExprClass:
8493 // "numeric literal"
8494 return LK_Numeric;
8495 case Stmt::ImplicitCastExprClass: {
8496 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
8497 // Boolean literals can be represented by implicit casts.
8498 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
8499 return LK_Numeric;
8500 break;
8501 }
8502 default:
8503 break;
8504 }
8505 return LK_Boxed;
8506 }
8507 }
8508 return LK_None;
8509}
8510
Jordan Rose7660f782012-07-17 17:46:40 +00008511static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
8512 ExprResult &LHS, ExprResult &RHS,
8513 BinaryOperator::Opcode Opc){
Jordan Rose63ffaa82012-07-17 17:46:48 +00008514 Expr *Literal;
8515 Expr *Other;
8516 if (isObjCObjectLiteral(LHS)) {
8517 Literal = LHS.get();
8518 Other = RHS.get();
8519 } else {
8520 Literal = RHS.get();
8521 Other = LHS.get();
8522 }
8523
8524 // Don't warn on comparisons against nil.
8525 Other = Other->IgnoreParenCasts();
8526 if (Other->isNullPointerConstant(S.getASTContext(),
8527 Expr::NPC_ValueDependentIsNotNull))
8528 return;
Jordan Rosed49a33e2012-06-08 21:14:25 +00008529
Jordan Roseea70bf72012-07-17 17:46:44 +00008530 // This should be kept in sync with warn_objc_literal_comparison.
Ted Kremenek01a33f82012-12-21 21:59:36 +00008531 // LK_String should always be after the other literals, since it has its own
8532 // warning flag.
8533 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
Ted Kremenek64873352012-12-21 22:46:35 +00008534 assert(LiteralKind != Sema::LK_Block);
Ted Kremenek01a33f82012-12-21 21:59:36 +00008535 if (LiteralKind == Sema::LK_None) {
Jordan Rosed49a33e2012-06-08 21:14:25 +00008536 llvm_unreachable("Unknown Objective-C object literal kind");
8537 }
8538
Ted Kremenek01a33f82012-12-21 21:59:36 +00008539 if (LiteralKind == Sema::LK_String)
Jordan Roseea70bf72012-07-17 17:46:44 +00008540 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
8541 << Literal->getSourceRange();
8542 else
8543 S.Diag(Loc, diag::warn_objc_literal_comparison)
8544 << LiteralKind << Literal->getSourceRange();
Jordan Rosed49a33e2012-06-08 21:14:25 +00008545
Jordan Rose7660f782012-07-17 17:46:40 +00008546 if (BinaryOperator::isEqualityOp(Opc) &&
8547 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
8548 SourceLocation Start = LHS.get()->getLocStart();
Craig Topper07fa1762015-11-15 02:31:46 +00008549 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
Fariborz Jahanian4dca1d32013-02-01 20:04:49 +00008550 CharSourceRange OpRange =
Craig Topper07fa1762015-11-15 02:31:46 +00008551 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
Jordan Rosef9198032012-07-09 16:54:44 +00008552
Jordan Rose7660f782012-07-17 17:46:40 +00008553 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
8554 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
Fariborz Jahanian4dca1d32013-02-01 20:04:49 +00008555 << FixItHint::CreateReplacement(OpRange, " isEqual:")
Jordan Rose7660f782012-07-17 17:46:40 +00008556 << FixItHint::CreateInsertion(End, "]");
Jordan Rosed49a33e2012-06-08 21:14:25 +00008557 }
Jordan Rosed49a33e2012-06-08 21:14:25 +00008558}
8559
Richard Trieubb4b8942013-06-10 18:52:07 +00008560static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
8561 ExprResult &RHS,
8562 SourceLocation Loc,
Craig Toppera92ffb02015-12-10 08:51:49 +00008563 BinaryOperatorKind Opc) {
Richard Trieubb4b8942013-06-10 18:52:07 +00008564 // Check that left hand side is !something.
Richard Trieu949abc32013-07-04 00:50:18 +00008565 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
Richard Trieubb4b8942013-06-10 18:52:07 +00008566 if (!UO || UO->getOpcode() != UO_LNot) return;
8567
8568 // Only check if the right hand side is non-bool arithmetic type.
Richard Trieu1cd076e2015-08-19 21:33:54 +00008569 if (RHS.get()->isKnownToHaveBooleanValue()) return;
Richard Trieubb4b8942013-06-10 18:52:07 +00008570
8571 // Make sure that the something in !something is not bool.
8572 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
Richard Trieu1cd076e2015-08-19 21:33:54 +00008573 if (SubExpr->isKnownToHaveBooleanValue()) return;
Richard Trieubb4b8942013-06-10 18:52:07 +00008574
8575 // Emit warning.
8576 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
8577 << Loc;
8578
8579 // First note suggest !(x < y)
8580 SourceLocation FirstOpen = SubExpr->getLocStart();
8581 SourceLocation FirstClose = RHS.get()->getLocEnd();
Craig Topper07fa1762015-11-15 02:31:46 +00008582 FirstClose = S.getLocForEndOfToken(FirstClose);
Eli Friedmanef0b4a32013-07-22 23:09:39 +00008583 if (FirstClose.isInvalid())
8584 FirstOpen = SourceLocation();
Richard Trieubb4b8942013-06-10 18:52:07 +00008585 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
8586 << FixItHint::CreateInsertion(FirstOpen, "(")
8587 << FixItHint::CreateInsertion(FirstClose, ")");
8588
8589 // Second note suggests (!x) < y
8590 SourceLocation SecondOpen = LHS.get()->getLocStart();
8591 SourceLocation SecondClose = LHS.get()->getLocEnd();
Craig Topper07fa1762015-11-15 02:31:46 +00008592 SecondClose = S.getLocForEndOfToken(SecondClose);
Eli Friedmanef0b4a32013-07-22 23:09:39 +00008593 if (SecondClose.isInvalid())
8594 SecondOpen = SourceLocation();
Richard Trieubb4b8942013-06-10 18:52:07 +00008595 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
8596 << FixItHint::CreateInsertion(SecondOpen, "(")
8597 << FixItHint::CreateInsertion(SecondClose, ")");
8598}
8599
Eli Friedman5a722e92013-09-06 03:13:09 +00008600// Get the decl for a simple expression: a reference to a variable,
8601// an implicit C++ field reference, or an implicit ObjC ivar reference.
8602static ValueDecl *getCompareDecl(Expr *E) {
8603 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
8604 return DR->getDecl();
8605 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
8606 if (Ivar->isFreeIvar())
8607 return Ivar->getDecl();
8608 }
8609 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
8610 if (Mem->isImplicitAccess())
8611 return Mem->getMemberDecl();
8612 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008613 return nullptr;
Eli Friedman5a722e92013-09-06 03:13:09 +00008614}
8615
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00008616// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00008617QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Craig Toppera92ffb02015-12-10 08:51:49 +00008618 SourceLocation Loc, BinaryOperatorKind Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008619 bool IsRelational) {
Richard Trieuf8916e12011-09-16 00:53:10 +00008620 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
8621
Chris Lattner9a152e22009-12-05 05:40:13 +00008622 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00008623 if (LHS.get()->getType()->isVectorType() ||
8624 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00008625 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008626
Richard Trieub80728f2011-09-06 21:43:51 +00008627 QualType LHSType = LHS.get()->getType();
8628 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00008629
Richard Trieub80728f2011-09-06 21:43:51 +00008630 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
8631 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00008632
Ted Kremenekf2ca8ec2013-01-30 19:10:21 +00008633 checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
Craig Toppera92ffb02015-12-10 08:51:49 +00008634 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc);
Chandler Carruth712563b2011-02-17 08:37:06 +00008635
Richard Trieub80728f2011-09-06 21:43:51 +00008636 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuba63ce62011-09-09 01:45:06 +00008637 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieub80728f2011-09-06 21:43:51 +00008638 !LHS.get()->getLocStart().isMacroID() &&
Richard Trieu30bfa362013-11-02 02:11:23 +00008639 !RHS.get()->getLocStart().isMacroID() &&
8640 ActiveTemplateInstantiations.empty()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00008641 // For non-floating point types, check for self-comparisons of the form
8642 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
8643 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00008644 //
8645 // NOTE: Don't warn about comparison expressions resulting from macro
8646 // expansion. Also don't warn about comparisons which are only self
8647 // comparisons within a template specialization. The warnings should catch
8648 // obvious cases in the definition of the template anyways. The idea is to
8649 // warn when the typed comparison operator will always evaluate to the same
8650 // result.
Eli Friedman5a722e92013-09-06 03:13:09 +00008651 ValueDecl *DL = getCompareDecl(LHSStripped);
8652 ValueDecl *DR = getCompareDecl(RHSStripped);
8653 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008654 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
Eli Friedman5a722e92013-09-06 03:13:09 +00008655 << 0 // self-
8656 << (Opc == BO_EQ
8657 || Opc == BO_LE
8658 || Opc == BO_GE));
8659 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
8660 !DL->getType()->isReferenceType() &&
8661 !DR->getType()->isReferenceType()) {
8662 // what is it always going to eval to?
8663 char always_evals_to;
8664 switch(Opc) {
8665 case BO_EQ: // e.g. array1 == array2
8666 always_evals_to = 0; // false
8667 break;
8668 case BO_NE: // e.g. array1 != array2
8669 always_evals_to = 1; // true
8670 break;
8671 default:
8672 // best we can say is 'a constant'
8673 always_evals_to = 2; // e.g. array1 <= array2
8674 break;
Douglas Gregorec170db2010-06-08 19:50:34 +00008675 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008676 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
Eli Friedman5a722e92013-09-06 03:13:09 +00008677 << 1 // array
8678 << always_evals_to);
Chandler Carruth17773fc2010-07-10 12:30:03 +00008679 }
Mike Stump11289f42009-09-09 15:08:12 +00008680
Chris Lattner222b8bd2009-03-08 19:39:53 +00008681 if (isa<CastExpr>(LHSStripped))
8682 LHSStripped = LHSStripped->IgnoreParenCasts();
8683 if (isa<CastExpr>(RHSStripped))
8684 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00008685
Chris Lattner222b8bd2009-03-08 19:39:53 +00008686 // Warn about comparisons against a string constant (unless the other
8687 // operand is null), the user probably wants strcmp.
Craig Topperc3ec1492014-05-26 06:22:03 +00008688 Expr *literalString = nullptr;
8689 Expr *literalStringStripped = nullptr;
Chris Lattner222b8bd2009-03-08 19:39:53 +00008690 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008691 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00008692 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00008693 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008694 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00008695 } else if ((isa<StringLiteral>(RHSStripped) ||
8696 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008697 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00008698 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00008699 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008700 literalStringStripped = RHSStripped;
8701 }
8702
8703 if (literalString) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008704 DiagRuntimeBehavior(Loc, nullptr,
Douglas Gregor49862b82010-01-12 23:18:54 +00008705 PDiag(diag::warn_stringcompare)
8706 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00008707 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008708 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00008709 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008710
Douglas Gregorec170db2010-06-08 19:50:34 +00008711 // C99 6.5.8p3 / C99 6.5.9p4
Eli Friedmane6d33952013-07-08 20:20:06 +00008712 UsualArithmeticConversions(LHS, RHS);
8713 if (LHS.isInvalid() || RHS.isInvalid())
8714 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00008715
Richard Trieub80728f2011-09-06 21:43:51 +00008716 LHSType = LHS.get()->getType();
8717 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00008718
Douglas Gregorca63811b2008-11-19 03:25:36 +00008719 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008720 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00008721
Richard Trieuba63ce62011-09-09 01:45:06 +00008722 if (IsRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00008723 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00008724 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00008725 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00008726 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00008727 if (LHSType->hasFloatingRepresentation())
8728 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00008729
Richard Trieub80728f2011-09-06 21:43:51 +00008730 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00008731 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00008732 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008733
Richard Trieu3bb8b562014-02-26 02:36:06 +00008734 const Expr::NullPointerConstantKind LHSNullKind =
8735 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
8736 const Expr::NullPointerConstantKind RHSNullKind =
8737 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
8738 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
8739 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
8740
8741 if (!IsRelational && LHSIsNull != RHSIsNull) {
8742 bool IsEquality = Opc == BO_EQ;
8743 if (RHSIsNull)
8744 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
8745 RHS.get()->getSourceRange());
8746 else
8747 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
8748 LHS.get()->getSourceRange());
8749 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008750
Douglas Gregorf267edd2010-06-15 21:38:40 +00008751 // All of the following pointer-related warnings are GCC extensions, except
8752 // when handling null pointer constants.
Richard Trieub80728f2011-09-06 21:43:51 +00008753 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00008754 QualType LCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00008755 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattner3a0702e2008-04-03 05:07:25 +00008756 QualType RCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00008757 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00008758
David Blaikiebbafb8a2012-03-11 07:00:24 +00008759 if (getLangOpts().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00008760 if (LCanPointeeTy == RCanPointeeTy)
8761 return ResultTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00008762 if (!IsRelational &&
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00008763 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8764 // Valid unless comparison between non-null pointer and function pointer
8765 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00008766 // In a SFINAE context, we treat this as a hard error to maintain
8767 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00008768 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
8769 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00008770 diagnoseFunctionPointerToVoidComparison(
David Blaikie3a3c4e02013-02-21 06:05:05 +00008771 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00008772
8773 if (isSFINAEContext())
8774 return QualType();
8775
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008776 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00008777 return ResultTy;
8778 }
8779 }
Anders Carlssona95069c2010-11-04 03:17:43 +00008780
Richard Trieub80728f2011-09-06 21:43:51 +00008781 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00008782 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00008783 else
8784 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00008785 }
Eli Friedman16c209612009-08-23 00:27:47 +00008786 // C99 6.5.9p2 and C99 6.5.8p2
8787 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
8788 RCanPointeeTy.getUnqualifiedType())) {
8789 // Valid unless a relational comparison of function pointers
Richard Trieuba63ce62011-09-09 01:45:06 +00008790 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman16c209612009-08-23 00:27:47 +00008791 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00008792 << LHSType << RHSType << LHS.get()->getSourceRange()
8793 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00008794 }
Richard Trieuba63ce62011-09-09 01:45:06 +00008795 } else if (!IsRelational &&
Eli Friedman16c209612009-08-23 00:27:47 +00008796 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8797 // Valid unless comparison between non-null pointer and function pointer
8798 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00008799 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00008800 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00008801 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00008802 } else {
8803 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00008804 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00008805 }
John McCall7684dde2011-03-11 04:25:25 +00008806 if (LCanPointeeTy != RCanPointeeTy) {
Anastasia Stulova2446b8b2015-12-11 17:41:19 +00008807 // Treat NULL constant as a special case in OpenCL.
8808 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
Anastasia Stulovae6e08232015-09-30 13:49:55 +00008809 const PointerType *LHSPtr = LHSType->getAs<PointerType>();
8810 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
8811 Diag(Loc,
8812 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8813 << LHSType << RHSType << 0 /* comparison */
8814 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8815 }
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00008816 }
David Tweede1468322013-12-11 13:39:46 +00008817 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
8818 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
8819 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
8820 : CK_BitCast;
John McCall7684dde2011-03-11 04:25:25 +00008821 if (LHSIsNull && !RHSIsNull)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008822 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
John McCall7684dde2011-03-11 04:25:25 +00008823 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008824 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
John McCall7684dde2011-03-11 04:25:25 +00008825 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00008826 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00008827 }
Mike Stump11289f42009-09-09 15:08:12 +00008828
David Blaikiebbafb8a2012-03-11 07:00:24 +00008829 if (getLangOpts().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00008830 // Comparison of nullptr_t with itself.
Richard Trieub80728f2011-09-06 21:43:51 +00008831 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlssona95069c2010-11-04 03:17:43 +00008832 return ResultTy;
8833
Mike Stump11289f42009-09-09 15:08:12 +00008834 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00008835 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00008836 if (RHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00008837 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00008838 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00008839 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008840 RHS = ImpCastExprToType(RHS.get(), LHSType,
Richard Trieub80728f2011-09-06 21:43:51 +00008841 LHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00008842 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00008843 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00008844 return ResultTy;
8845 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00008846 if (LHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00008847 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00008848 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00008849 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008850 LHS = ImpCastExprToType(LHS.get(), RHSType,
Richard Trieub80728f2011-09-06 21:43:51 +00008851 RHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00008852 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00008853 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00008854 return ResultTy;
8855 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00008856
8857 // Comparison of member pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00008858 if (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00008859 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
8860 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00008861 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00008862 else
8863 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00008864 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00008865
8866 // Handle scoped enumeration types specifically, since they don't promote
8867 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00008868 if (LHS.get()->getType()->isEnumeralType() &&
8869 Context.hasSameUnqualifiedType(LHS.get()->getType(),
8870 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00008871 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00008872 }
Mike Stump11289f42009-09-09 15:08:12 +00008873
Steve Naroff081c7422008-09-04 15:10:53 +00008874 // Handle block pointer types.
Richard Trieuba63ce62011-09-09 01:45:06 +00008875 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieub80728f2011-09-06 21:43:51 +00008876 RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00008877 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
8878 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00008879
Steve Naroff081c7422008-09-04 15:10:53 +00008880 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00008881 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00008882 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00008883 << LHSType << RHSType << LHS.get()->getSourceRange()
8884 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00008885 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008886 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00008887 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00008888 }
John Wiegley01296292011-04-08 18:41:53 +00008889
Steve Naroffe18f94c2008-09-28 01:11:11 +00008890 // Allow block pointers to be compared with null pointer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00008891 if (!IsRelational
Richard Trieub80728f2011-09-06 21:43:51 +00008892 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
8893 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00008894 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00008895 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00008896 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00008897 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00008898 ->getPointeeType()->isVoidType())))
8899 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00008900 << LHSType << RHSType << LHS.get()->getSourceRange()
8901 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00008902 }
John McCall7684dde2011-03-11 04:25:25 +00008903 if (LHSIsNull && !RHSIsNull)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008904 LHS = ImpCastExprToType(LHS.get(), RHSType,
John McCall9320b872011-09-09 05:25:32 +00008905 RHSType->isPointerType() ? CK_BitCast
8906 : CK_AnyPointerToBlockPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00008907 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008908 RHS = ImpCastExprToType(RHS.get(), LHSType,
John McCall9320b872011-09-09 05:25:32 +00008909 LHSType->isPointerType() ? CK_BitCast
8910 : CK_AnyPointerToBlockPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00008911 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00008912 }
Steve Naroff081c7422008-09-04 15:10:53 +00008913
Richard Trieub80728f2011-09-06 21:43:51 +00008914 if (LHSType->isObjCObjectPointerType() ||
8915 RHSType->isObjCObjectPointerType()) {
8916 const PointerType *LPT = LHSType->getAs<PointerType>();
8917 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00008918 if (LPT || RPT) {
8919 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
8920 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008921
Steve Naroff753567f2008-11-17 19:49:16 +00008922 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00008923 !Context.typesAreCompatible(LHSType, RHSType)) {
8924 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00008925 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00008926 }
Fariborz Jahanian374089e2013-07-31 17:12:26 +00008927 if (LHSIsNull && !RHSIsNull) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008928 Expr *E = LHS.get();
Fariborz Jahanian374089e2013-07-31 17:12:26 +00008929 if (getLangOpts().ObjCAutoRefCount)
8930 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
8931 LHS = ImpCastExprToType(E, RHSType,
John McCall9320b872011-09-09 05:25:32 +00008932 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Fariborz Jahanian374089e2013-07-31 17:12:26 +00008933 }
8934 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008935 Expr *E = RHS.get();
Fariborz Jahanian374089e2013-07-31 17:12:26 +00008936 if (getLangOpts().ObjCAutoRefCount)
Fariborz Jahanianc03ef572014-06-18 23:52:49 +00008937 CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false,
8938 Opc);
Fariborz Jahanian374089e2013-07-31 17:12:26 +00008939 RHS = ImpCastExprToType(E, LHSType,
John McCall9320b872011-09-09 05:25:32 +00008940 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Fariborz Jahanian374089e2013-07-31 17:12:26 +00008941 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00008942 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00008943 }
Richard Trieub80728f2011-09-06 21:43:51 +00008944 if (LHSType->isObjCObjectPointerType() &&
8945 RHSType->isObjCObjectPointerType()) {
8946 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
8947 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00008948 /*isError*/false);
Jordan Rosed49a33e2012-06-08 21:14:25 +00008949 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
Jordan Rose7660f782012-07-17 17:46:40 +00008950 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
Jordan Rosed49a33e2012-06-08 21:14:25 +00008951
John McCall7684dde2011-03-11 04:25:25 +00008952 if (LHSIsNull && !RHSIsNull)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008953 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00008954 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008955 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00008956 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00008957 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00008958 }
Richard Trieub80728f2011-09-06 21:43:51 +00008959 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
8960 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00008961 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00008962 bool isError = false;
Douglas Gregor0064c592012-09-14 04:35:37 +00008963 if (LangOpts.DebuggerSupport) {
8964 // Under a debugger, allow the comparison of pointers to integers,
8965 // since users tend to want to compare addresses.
8966 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
Richard Trieub80728f2011-09-06 21:43:51 +00008967 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008968 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00008969 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008970 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00008971 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008972 else if (getLangOpts().CPlusPlus) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00008973 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
8974 isError = true;
8975 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00008976 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00008977
Chris Lattnerd99bd522009-08-23 00:03:44 +00008978 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00008979 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00008980 << LHSType << RHSType << LHS.get()->getSourceRange()
8981 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00008982 if (isError)
8983 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00008984 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00008985
Richard Trieub80728f2011-09-06 21:43:51 +00008986 if (LHSType->isIntegerType())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008987 LHS = ImpCastExprToType(LHS.get(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00008988 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00008989 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008990 RHS = ImpCastExprToType(RHS.get(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00008991 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00008992 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00008993 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00008994
Steve Naroff4b191572008-09-04 16:56:14 +00008995 // Handle block pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00008996 if (!IsRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00008997 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008998 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00008999 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00009000 }
Richard Trieuba63ce62011-09-09 01:45:06 +00009001 if (!IsRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00009002 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009003 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00009004 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00009005 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00009006
Richard Trieub80728f2011-09-06 21:43:51 +00009007 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00009008}
9009
Tanya Lattner20248222012-01-16 21:02:28 +00009010
9011// Return a signed type that is of identical size and number of elements.
9012// For floating point vectors, return an integer type of identical size
9013// and number of elements.
9014QualType Sema::GetSignedVectorType(QualType V) {
9015 const VectorType *VTy = V->getAs<VectorType>();
9016 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9017 if (TypeSize == Context.getTypeSize(Context.CharTy))
9018 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9019 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9020 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9021 else if (TypeSize == Context.getTypeSize(Context.IntTy))
9022 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9023 else if (TypeSize == Context.getTypeSize(Context.LongTy))
9024 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9025 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9026 "Unhandled vector element size in vector compare");
9027 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9028}
9029
Nate Begeman191a6b12008-07-14 18:02:46 +00009030/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00009031/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00009032/// like a scalar comparison, a vector comparison produces a vector of integer
9033/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00009034QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00009035 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009036 bool IsRelational) {
Nate Begeman191a6b12008-07-14 18:02:46 +00009037 // Check to make sure we're operating on vectors of the same type and width,
9038 // Allowing one side to be a scalar of element type.
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00009039 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9040 /*AllowBothBool*/true,
9041 /*AllowBoolConversions*/getLangOpts().ZVector);
Nate Begeman191a6b12008-07-14 18:02:46 +00009042 if (vType.isNull())
9043 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009044
Richard Trieubcce2f72011-09-07 01:19:57 +00009045 QualType LHSType = LHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00009046
Anton Yartsev530deb92011-03-27 15:36:07 +00009047 // If AltiVec, the comparison results in a numeric type, i.e.
9048 // bool for C++, int for C
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00009049 if (getLangOpts().AltiVec &&
9050 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00009051 return Context.getLogicalOperationType();
9052
Nate Begeman191a6b12008-07-14 18:02:46 +00009053 // For non-floating point types, check for self-comparisons of the form
9054 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
9055 // often indicate logic errors in the program.
Richard Trieu30bfa362013-11-02 02:11:23 +00009056 if (!LHSType->hasFloatingRepresentation() &&
9057 ActiveTemplateInstantiations.empty()) {
Richard Smith508ebf32011-10-28 03:31:48 +00009058 if (DeclRefExpr* DRL
9059 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9060 if (DeclRefExpr* DRR
9061 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begeman191a6b12008-07-14 18:02:46 +00009062 if (DRL->getDecl() == DRR->getDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00009063 DiagRuntimeBehavior(Loc, nullptr,
Douglas Gregorec170db2010-06-08 19:50:34 +00009064 PDiag(diag::warn_comparison_always)
9065 << 0 // self-
9066 << 2 // "a constant"
9067 );
Nate Begeman191a6b12008-07-14 18:02:46 +00009068 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009069
Nate Begeman191a6b12008-07-14 18:02:46 +00009070 // Check for comparisons of floating point operands using != and ==.
Richard Trieuba63ce62011-09-09 01:45:06 +00009071 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikieca043222012-01-16 05:16:03 +00009072 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieubcce2f72011-09-07 01:19:57 +00009073 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00009074 }
Tanya Lattner20248222012-01-16 21:02:28 +00009075
9076 // Return a signed type for the vector.
9077 return GetSignedVectorType(LHSType);
9078}
Mike Stump4e1f26a2009-02-19 03:04:26 +00009079
Tanya Lattner3dd33b22012-01-19 01:16:16 +00009080QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9081 SourceLocation Loc) {
Tanya Lattner20248222012-01-16 21:02:28 +00009082 // Ensure that either both operands are of the same vector type, or
9083 // one operand is of a vector type and the other is of its element type.
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00009084 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9085 /*AllowBothBool*/true,
9086 /*AllowBoolConversions*/false);
Joey Gouly7d00f002013-02-21 11:49:56 +00009087 if (vType.isNull())
9088 return InvalidOperands(Loc, LHS, RHS);
9089 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9090 vType->hasFloatingRepresentation())
Tanya Lattner20248222012-01-16 21:02:28 +00009091 return InvalidOperands(Loc, LHS, RHS);
9092
9093 return GetSignedVectorType(LHS.get()->getType());
Nate Begeman191a6b12008-07-14 18:02:46 +00009094}
9095
Steve Naroff218bc2b2007-05-04 21:54:46 +00009096inline QualType Sema::CheckBitwiseOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00009097 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00009098 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9099
Richard Trieubcce2f72011-09-07 01:19:57 +00009100 if (LHS.get()->getType()->isVectorType() ||
9101 RHS.get()->getType()->isVectorType()) {
9102 if (LHS.get()->getType()->hasIntegerRepresentation() &&
9103 RHS.get()->getType()->hasIntegerRepresentation())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00009104 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9105 /*AllowBothBool*/true,
9106 /*AllowBoolConversions*/getLangOpts().ZVector);
Richard Trieubcce2f72011-09-07 01:19:57 +00009107 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00009108 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00009109
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009110 ExprResult LHSResult = LHS, RHSResult = RHS;
Richard Trieubcce2f72011-09-07 01:19:57 +00009111 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuba63ce62011-09-09 01:45:06 +00009112 IsCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00009113 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00009114 return QualType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009115 LHS = LHSResult.get();
9116 RHS = RHSResult.get();
Mike Stump4e1f26a2009-02-19 03:04:26 +00009117
Eli Friedman93ee5ca2012-06-16 02:19:17 +00009118 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00009119 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00009120 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00009121}
9122
Craig Toppera92ffb02015-12-10 08:51:49 +00009123// C99 6.5.[13,14]
9124inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9125 SourceLocation Loc,
9126 BinaryOperatorKind Opc) {
Tanya Lattner20248222012-01-16 21:02:28 +00009127 // Check vector operands differently.
9128 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9129 return CheckVectorLogicalOperands(LHS, RHS, Loc);
9130
Chris Lattner8406c512010-07-13 19:41:32 +00009131 // Diagnose cases where the user write a logical and/or but probably meant a
9132 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
9133 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00009134 if (LHS.get()->getType()->isIntegerType() &&
9135 !LHS.get()->getType()->isBooleanType() &&
9136 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00009137 // Don't warn in macros or template instantiations.
9138 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00009139 // If the RHS can be constant folded, and if it constant folds to something
9140 // that isn't 0 or 1 (which indicate a potential logical operation that
9141 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00009142 // Parens on the RHS are ignored.
Richard Smith00ab3ae2011-10-16 23:01:09 +00009143 llvm::APSInt Result;
9144 if (RHS.get()->EvaluateAsInt(Result, Context))
Argyrios Kyrtzidisd6eb2b92014-04-28 00:20:16 +00009145 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9146 !RHS.get()->getExprLoc().isMacroID()) ||
Richard Smith00ab3ae2011-10-16 23:01:09 +00009147 (Result != 0 && Result != 1)) {
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00009148 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00009149 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00009150 << (Opc == BO_LAnd ? "&&" : "||");
9151 // Suggest replacing the logical operator with the bitwise version
9152 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9153 << (Opc == BO_LAnd ? "&" : "|")
9154 << FixItHint::CreateReplacement(SourceRange(
Craig Topper07fa1762015-11-15 02:31:46 +00009155 Loc, getLocForEndOfToken(Loc)),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00009156 Opc == BO_LAnd ? "&" : "|");
9157 if (Opc == BO_LAnd)
9158 // Suggest replacing "Foo() && kNonZero" with "Foo()"
9159 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9160 << FixItHint::CreateRemoval(
Craig Topper07fa1762015-11-15 02:31:46 +00009161 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9162 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00009163 }
Chris Lattner938533d2010-07-24 01:10:11 +00009164 }
Joey Gouly7d00f002013-02-21 11:49:56 +00009165
David Blaikiebbafb8a2012-03-11 07:00:24 +00009166 if (!Context.getLangOpts().CPlusPlus) {
Joey Gouly7d00f002013-02-21 11:49:56 +00009167 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9168 // not operate on the built-in scalar and vector float types.
9169 if (Context.getLangOpts().OpenCL &&
9170 Context.getLangOpts().OpenCLVersion < 120) {
9171 if (LHS.get()->getType()->isFloatingType() ||
9172 RHS.get()->getType()->isFloatingType())
9173 return InvalidOperands(Loc, LHS, RHS);
9174 }
9175
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009176 LHS = UsualUnaryConversions(LHS.get());
Richard Trieubcce2f72011-09-07 01:19:57 +00009177 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00009178 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00009179
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009180 RHS = UsualUnaryConversions(RHS.get());
Richard Trieubcce2f72011-09-07 01:19:57 +00009181 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00009182 return QualType();
9183
Richard Trieubcce2f72011-09-07 01:19:57 +00009184 if (!LHS.get()->getType()->isScalarType() ||
9185 !RHS.get()->getType()->isScalarType())
9186 return InvalidOperands(Loc, LHS, RHS);
Fariborz Jahanian3365bfc2014-11-11 21:54:19 +00009187
Anders Carlsson2e7bc112009-11-23 21:47:44 +00009188 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00009189 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009190
John McCall4a2429a2010-06-04 00:29:51 +00009191 // The following is safe because we only use this method for
9192 // non-overloadable operands.
9193
Anders Carlsson2e7bc112009-11-23 21:47:44 +00009194 // C++ [expr.log.and]p1
9195 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00009196 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00009197 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9198 if (LHSRes.isInvalid())
9199 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009200 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00009201
Richard Trieubcce2f72011-09-07 01:19:57 +00009202 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9203 if (RHSRes.isInvalid())
9204 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009205 RHS = RHSRes;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009206
Anders Carlsson2e7bc112009-11-23 21:47:44 +00009207 // C++ [expr.log.and]p2
9208 // C++ [expr.log.or]p2
9209 // The result is a bool.
9210 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00009211}
9212
Fariborz Jahanian071caef2011-03-26 19:48:30 +00009213static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00009214 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9215 if (!ME) return false;
9216 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9217 ObjCMessageExpr *Base =
9218 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
9219 if (!Base) return false;
Craig Topperc3ec1492014-05-26 06:22:03 +00009220 return Base->getMethodDecl() != nullptr;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00009221}
9222
John McCall5fa2ef42012-03-13 00:37:01 +00009223/// Is the given expression (which must be 'const') a reference to a
9224/// variable which was originally non-const, but which has become
9225/// 'const' due to being captured within a block?
9226enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9227static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9228 assert(E->isLValue() && E->getType().isConstQualified());
9229 E = E->IgnoreParens();
9230
9231 // Must be a reference to a declaration from an enclosing scope.
9232 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9233 if (!DRE) return NCCK_None;
Alexey Bataev19acc3d2015-01-12 10:17:46 +00009234 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
John McCall5fa2ef42012-03-13 00:37:01 +00009235
9236 // The declaration must be a variable which is not declared 'const'.
9237 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9238 if (!var) return NCCK_None;
9239 if (var->getType().isConstQualified()) return NCCK_None;
9240 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9241
9242 // Decide whether the first capture was for a block or a lambda.
Craig Topperc3ec1492014-05-26 06:22:03 +00009243 DeclContext *DC = S.CurContext, *Prev = nullptr;
Richard Smith75e3f692013-09-28 04:31:26 +00009244 while (DC != var->getDeclContext()) {
9245 Prev = DC;
John McCall5fa2ef42012-03-13 00:37:01 +00009246 DC = DC->getParent();
Richard Smith75e3f692013-09-28 04:31:26 +00009247 }
9248 // Unless we have an init-capture, we've gone one step too far.
9249 if (!var->isInitCapture())
9250 DC = Prev;
John McCall5fa2ef42012-03-13 00:37:01 +00009251 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9252}
9253
Richard Trieuaf7d76c2015-04-11 01:53:13 +00009254static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9255 Ty = Ty.getNonReferenceType();
9256 if (IsDereference && Ty->isPointerType())
9257 Ty = Ty->getPointeeType();
9258 return !Ty.isConstQualified();
9259}
9260
9261/// Emit the "read-only variable not assignable" error and print notes to give
9262/// more information about why the variable is not assignable, such as pointing
9263/// to the declaration of a const variable, showing that a method is const, or
9264/// that the function is returning a const reference.
9265static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9266 SourceLocation Loc) {
9267 // Update err_typecheck_assign_const and note_typecheck_assign_const
9268 // when this enum is changed.
9269 enum {
9270 ConstFunction,
9271 ConstVariable,
9272 ConstMember,
9273 ConstMethod,
9274 ConstUnknown, // Keep as last element
9275 };
9276
9277 SourceRange ExprRange = E->getSourceRange();
9278
9279 // Only emit one error on the first const found. All other consts will emit
9280 // a note to the error.
9281 bool DiagnosticEmitted = false;
9282
9283 // Track if the current expression is the result of a derefence, and if the
9284 // next checked expression is the result of a derefence.
9285 bool IsDereference = false;
9286 bool NextIsDereference = false;
9287
9288 // Loop to process MemberExpr chains.
9289 while (true) {
9290 IsDereference = NextIsDereference;
9291 NextIsDereference = false;
9292
9293 E = E->IgnoreParenImpCasts();
9294 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9295 NextIsDereference = ME->isArrow();
9296 const ValueDecl *VD = ME->getMemberDecl();
9297 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9298 // Mutable fields can be modified even if the class is const.
9299 if (Field->isMutable()) {
9300 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9301 break;
9302 }
9303
9304 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9305 if (!DiagnosticEmitted) {
9306 S.Diag(Loc, diag::err_typecheck_assign_const)
9307 << ExprRange << ConstMember << false /*static*/ << Field
9308 << Field->getType();
9309 DiagnosticEmitted = true;
9310 }
9311 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9312 << ConstMember << false /*static*/ << Field << Field->getType()
9313 << Field->getSourceRange();
9314 }
9315 E = ME->getBase();
9316 continue;
9317 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
9318 if (VDecl->getType().isConstQualified()) {
9319 if (!DiagnosticEmitted) {
9320 S.Diag(Loc, diag::err_typecheck_assign_const)
9321 << ExprRange << ConstMember << true /*static*/ << VDecl
9322 << VDecl->getType();
9323 DiagnosticEmitted = true;
9324 }
9325 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9326 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
9327 << VDecl->getSourceRange();
9328 }
9329 // Static fields do not inherit constness from parents.
9330 break;
9331 }
9332 break;
9333 } // End MemberExpr
9334 break;
9335 }
9336
9337 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9338 // Function calls
9339 const FunctionDecl *FD = CE->getDirectCallee();
David Majnemerd39bcae2015-08-26 05:13:19 +00009340 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
Richard Trieuaf7d76c2015-04-11 01:53:13 +00009341 if (!DiagnosticEmitted) {
9342 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9343 << ConstFunction << FD;
9344 DiagnosticEmitted = true;
9345 }
9346 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
9347 diag::note_typecheck_assign_const)
9348 << ConstFunction << FD << FD->getReturnType()
9349 << FD->getReturnTypeSourceRange();
9350 }
9351 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9352 // Point to variable declaration.
9353 if (const ValueDecl *VD = DRE->getDecl()) {
9354 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
9355 if (!DiagnosticEmitted) {
9356 S.Diag(Loc, diag::err_typecheck_assign_const)
9357 << ExprRange << ConstVariable << VD << VD->getType();
9358 DiagnosticEmitted = true;
9359 }
9360 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9361 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
9362 }
9363 }
9364 } else if (isa<CXXThisExpr>(E)) {
9365 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
9366 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
9367 if (MD->isConst()) {
9368 if (!DiagnosticEmitted) {
9369 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9370 << ConstMethod << MD;
9371 DiagnosticEmitted = true;
9372 }
9373 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
9374 << ConstMethod << MD << MD->getSourceRange();
9375 }
9376 }
9377 }
9378 }
9379
9380 if (DiagnosticEmitted)
9381 return;
9382
9383 // Can't determine a more specific message, so display the generic error.
9384 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
9385}
9386
Chris Lattner30bd3272008-11-18 01:22:49 +00009387/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
9388/// emit an error and return true. If so, return false.
9389static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianca5c5972012-04-10 17:30:10 +00009390 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00009391 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00009392 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00009393 &Loc);
Eli Friedmanaa205c42013-06-27 01:36:36 +00009394 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
Fariborz Jahanian071caef2011-03-26 19:48:30 +00009395 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00009396 if (IsLV == Expr::MLV_Valid)
9397 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009398
David Majnemer3e7743e2014-12-26 06:06:53 +00009399 unsigned DiagID = 0;
Chris Lattner30bd3272008-11-18 01:22:49 +00009400 bool NeedType = false;
9401 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00009402 case Expr::MLV_ConstQualified:
John McCall5fa2ef42012-03-13 00:37:01 +00009403 // Use a specialized diagnostic when we're assigning to an object
9404 // from an enclosing function or block.
9405 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
9406 if (NCCK == NCCK_Block)
David Majnemer3e7743e2014-12-26 06:06:53 +00009407 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
John McCall5fa2ef42012-03-13 00:37:01 +00009408 else
David Majnemer3e7743e2014-12-26 06:06:53 +00009409 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
John McCall5fa2ef42012-03-13 00:37:01 +00009410 break;
9411 }
9412
John McCalld4631322011-06-17 06:42:21 +00009413 // In ARC, use some specialized diagnostics for occasions where we
9414 // infer 'const'. These are always pseudo-strong variables.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009415 if (S.getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00009416 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
9417 if (declRef && isa<VarDecl>(declRef->getDecl())) {
9418 VarDecl *var = cast<VarDecl>(declRef->getDecl());
9419
John McCalld4631322011-06-17 06:42:21 +00009420 // Use the normal diagnostic if it's pseudo-__strong but the
9421 // user actually wrote 'const'.
9422 if (var->isARCPseudoStrong() &&
9423 (!var->getTypeSourceInfo() ||
9424 !var->getTypeSourceInfo()->getType().isConstQualified())) {
9425 // There are two pseudo-strong cases:
9426 // - self
John McCall31168b02011-06-15 23:02:42 +00009427 ObjCMethodDecl *method = S.getCurMethodDecl();
9428 if (method && var == method->getSelfDecl())
David Majnemer3e7743e2014-12-26 06:06:53 +00009429 DiagID = method->isClassMethod()
Ted Kremenek1fcdaa92011-11-14 21:59:25 +00009430 ? diag::err_typecheck_arc_assign_self_class_method
9431 : diag::err_typecheck_arc_assign_self;
John McCalld4631322011-06-17 06:42:21 +00009432
9433 // - fast enumeration variables
9434 else
David Majnemer3e7743e2014-12-26 06:06:53 +00009435 DiagID = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00009436
John McCall31168b02011-06-15 23:02:42 +00009437 SourceRange Assign;
9438 if (Loc != OrigLoc)
9439 Assign = SourceRange(OrigLoc, OrigLoc);
David Majnemer3e7743e2014-12-26 06:06:53 +00009440 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
Richard Trieuaf7d76c2015-04-11 01:53:13 +00009441 // We need to preserve the AST regardless, so migration tool
John McCall31168b02011-06-15 23:02:42 +00009442 // can do its job.
9443 return false;
9444 }
9445 }
9446 }
9447
Richard Trieuaf7d76c2015-04-11 01:53:13 +00009448 // If none of the special cases above are triggered, then this is a
9449 // simple const assignment.
9450 if (DiagID == 0) {
9451 DiagnoseConstAssignment(S, E, Loc);
9452 return true;
9453 }
9454
John McCall31168b02011-06-15 23:02:42 +00009455 break;
Richard Smitha7bd4582015-05-22 01:14:39 +00009456 case Expr::MLV_ConstAddrSpace:
9457 DiagnoseConstAssignment(S, E, Loc);
9458 return true;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009459 case Expr::MLV_ArrayType:
Richard Smitheb3cad52012-06-04 22:27:30 +00009460 case Expr::MLV_ArrayTemporary:
David Majnemer3e7743e2014-12-26 06:06:53 +00009461 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
Chris Lattner30bd3272008-11-18 01:22:49 +00009462 NeedType = true;
9463 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009464 case Expr::MLV_NotObjectType:
David Majnemer3e7743e2014-12-26 06:06:53 +00009465 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
Chris Lattner30bd3272008-11-18 01:22:49 +00009466 NeedType = true;
9467 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00009468 case Expr::MLV_LValueCast:
David Majnemer3e7743e2014-12-26 06:06:53 +00009469 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
Chris Lattner30bd3272008-11-18 01:22:49 +00009470 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00009471 case Expr::MLV_Valid:
9472 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00009473 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00009474 case Expr::MLV_MemberFunction:
9475 case Expr::MLV_ClassTemporary:
David Majnemer3e7743e2014-12-26 06:06:53 +00009476 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
Chris Lattner30bd3272008-11-18 01:22:49 +00009477 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009478 case Expr::MLV_IncompleteType:
9479 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00009480 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009481 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009482 case Expr::MLV_DuplicateVectorComponents:
David Majnemer3e7743e2014-12-26 06:06:53 +00009483 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
Chris Lattner30bd3272008-11-18 01:22:49 +00009484 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00009485 case Expr::MLV_NoSetterProperty:
John McCall526ab472011-10-25 17:37:35 +00009486 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian071caef2011-03-26 19:48:30 +00009487 case Expr::MLV_InvalidMessageExpression:
David Majnemer3e7743e2014-12-26 06:06:53 +00009488 DiagID = diag::error_readonly_message_assignment;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00009489 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00009490 case Expr::MLV_SubObjCPropertySetting:
David Majnemer3e7743e2014-12-26 06:06:53 +00009491 DiagID = diag::error_no_subobject_property_setting;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00009492 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00009493 }
Steve Naroffad373bd2007-07-31 12:34:36 +00009494
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00009495 SourceRange Assign;
9496 if (Loc != OrigLoc)
9497 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00009498 if (NeedType)
David Majnemer3e7743e2014-12-26 06:06:53 +00009499 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00009500 else
David Majnemer3e7743e2014-12-26 06:06:53 +00009501 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00009502 return true;
9503}
9504
Nico Weberb8124d12012-07-03 02:03:06 +00009505static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
9506 SourceLocation Loc,
9507 Sema &Sema) {
9508 // C / C++ fields
Nico Weber33fd5232012-06-28 23:53:12 +00009509 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
9510 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
9511 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
9512 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
Nico Weberb8124d12012-07-03 02:03:06 +00009513 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
Nico Weber33fd5232012-06-28 23:53:12 +00009514 }
Chris Lattner30bd3272008-11-18 01:22:49 +00009515
Nico Weberb8124d12012-07-03 02:03:06 +00009516 // Objective-C instance variables
Nico Weber33fd5232012-06-28 23:53:12 +00009517 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
9518 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
9519 if (OL && OR && OL->getDecl() == OR->getDecl()) {
9520 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
9521 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
9522 if (RL && RR && RL->getDecl() == RR->getDecl())
Nico Weberb8124d12012-07-03 02:03:06 +00009523 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
Nico Weber33fd5232012-06-28 23:53:12 +00009524 }
9525}
Chris Lattner30bd3272008-11-18 01:22:49 +00009526
9527// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +00009528QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00009529 SourceLocation Loc,
9530 QualType CompoundType) {
John McCall526ab472011-10-25 17:37:35 +00009531 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
9532
Chris Lattner326f7572008-11-18 01:30:42 +00009533 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +00009534 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00009535 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00009536
Richard Trieuda4f43a62011-09-07 01:33:52 +00009537 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00009538 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
9539 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009540 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00009541 if (CompoundType.isNull()) {
Nico Weber33fd5232012-06-28 23:53:12 +00009542 Expr *RHSCheck = RHS.get();
9543
Nico Weberb8124d12012-07-03 02:03:06 +00009544 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
Nico Weber33fd5232012-06-28 23:53:12 +00009545
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00009546 QualType LHSTy(LHSType);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00009547 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00009548 if (RHS.isInvalid())
9549 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00009550 // Special case of NSObject attributes on c-style pointer types.
9551 if (ConvTy == IncompatiblePointer &&
9552 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00009553 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00009554 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00009555 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00009556 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009557
John McCall7decc9e2010-11-18 06:31:45 +00009558 if (ConvTy == Compatible &&
Fariborz Jahaniane2a77762012-01-24 19:40:13 +00009559 LHSType->isObjCObjectType())
Fariborz Jahanian3c4225a2012-01-24 18:05:45 +00009560 Diag(Loc, diag::err_objc_object_assignment)
9561 << LHSType;
John McCall7decc9e2010-11-18 06:31:45 +00009562
Chris Lattnerea714382008-08-21 18:04:13 +00009563 // If the RHS is a unary plus or minus, check to see if they = and + are
9564 // right next to each other. If so, the user may have typo'd "x =+ 4"
9565 // instead of "x += 4".
Chris Lattnerea714382008-08-21 18:04:13 +00009566 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
9567 RHSCheck = ICE->getSubExpr();
9568 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00009569 if ((UO->getOpcode() == UO_Plus ||
9570 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00009571 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00009572 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00009573 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner36c39c92009-03-08 06:51:10 +00009574 // And there is a space or other character before the subexpr of the
9575 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00009576 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattnered9f14c2009-03-09 07:11:10 +00009577 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00009578 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00009579 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00009580 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00009581 }
Chris Lattnerea714382008-08-21 18:04:13 +00009582 }
John McCall31168b02011-06-15 23:02:42 +00009583
9584 if (ConvTy == Compatible) {
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009585 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
9586 // Warn about retain cycles where a block captures the LHS, but
9587 // not if the LHS is a simple variable into which the block is
9588 // being stored...unless that variable can be captured by reference!
9589 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
9590 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
9591 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
9592 checkRetainCycles(LHSExpr, RHS.get());
9593
Jordan Rosed3934582012-09-28 22:21:30 +00009594 // It is safe to assign a weak reference into a strong variable.
9595 // Although this code can still have problems:
9596 // id x = self.weakProp;
9597 // id y = self.weakProp;
9598 // we do not warn to warn spuriously when 'x' and 'y' are on separate
9599 // paths through the function. This should be revisited if
9600 // -Wrepeated-use-of-weak is made flow-sensitive.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009601 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9602 RHS.get()->getLocStart()))
Jordan Rosed3934582012-09-28 22:21:30 +00009603 getCurFunction()->markSafeWeakUse(RHS.get());
9604
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009605 } else if (getLangOpts().ObjCAutoRefCount) {
Richard Trieuda4f43a62011-09-07 01:33:52 +00009606 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009607 }
John McCall31168b02011-06-15 23:02:42 +00009608 }
Chris Lattnerea714382008-08-21 18:04:13 +00009609 } else {
9610 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00009611 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00009612 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009613
Chris Lattner326f7572008-11-18 01:30:42 +00009614 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00009615 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00009616 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00009617
Richard Trieuda4f43a62011-09-07 01:33:52 +00009618 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009619
Steve Naroff98cf3e92007-06-06 18:38:38 +00009620 // C99 6.5.16p3: The type of an assignment expression is the type of the
9621 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00009622 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00009623 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
9624 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00009625 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00009626 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009627 return (getLangOpts().CPlusPlus
John McCall01cbf2d2010-10-12 02:19:57 +00009628 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00009629}
9630
Chris Lattner326f7572008-11-18 01:30:42 +00009631// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00009632static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00009633 SourceLocation Loc) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009634 LHS = S.CheckPlaceholderExpr(LHS.get());
9635 RHS = S.CheckPlaceholderExpr(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00009636 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00009637 return QualType();
9638
John McCall73d36182010-10-12 07:14:40 +00009639 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
9640 // operands, but not unary promotions.
9641 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00009642
John McCall34376a62010-12-04 03:47:34 +00009643 // So we treat the LHS as a ignored value, and in C++ we allow the
9644 // containing site to determine what should be done with the RHS.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009645 LHS = S.IgnoredValueConversions(LHS.get());
John Wiegley01296292011-04-08 18:41:53 +00009646 if (LHS.isInvalid())
9647 return QualType();
John McCall34376a62010-12-04 03:47:34 +00009648
Eli Friedmanc11535c2012-05-24 00:47:05 +00009649 S.DiagnoseUnusedExprResult(LHS.get());
9650
David Blaikiebbafb8a2012-03-11 07:00:24 +00009651 if (!S.getLangOpts().CPlusPlus) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009652 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00009653 if (RHS.isInvalid())
9654 return QualType();
9655 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00009656 S.RequireCompleteType(Loc, RHS.get()->getType(),
9657 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00009658 }
Eli Friedmanba961a92009-03-23 00:24:07 +00009659
John Wiegley01296292011-04-08 18:41:53 +00009660 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00009661}
9662
Steve Naroff7a5af782007-07-13 16:58:59 +00009663/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
9664/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00009665static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
9666 ExprValueKind &VK,
David Majnemer74242432014-07-31 04:52:13 +00009667 ExprObjectKind &OK,
John McCall4bc41ae2010-11-18 19:01:18 +00009668 SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009669 bool IsInc, bool IsPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009670 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00009671 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009672
Chris Lattner6b0cf142008-11-21 07:05:48 +00009673 QualType ResType = Op->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00009674 // Atomic types can be used for increment / decrement where the non-atomic
9675 // versions can, so ignore the _Atomic() specifier for the purpose of
9676 // checking.
9677 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9678 ResType = ResAtomicType->getValueType();
9679
Chris Lattner6b0cf142008-11-21 07:05:48 +00009680 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00009681
David Blaikiebbafb8a2012-03-11 07:00:24 +00009682 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00009683 // Decrement of bool is not allowed.
Richard Trieuba63ce62011-09-09 01:45:06 +00009684 if (!IsInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00009685 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00009686 return QualType();
9687 }
9688 // Increment of bool sets it to true, but is deprecated.
Richard Smith4a0cd892015-11-26 02:16:37 +00009689 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
9690 : diag::warn_increment_bool)
9691 << Op->getSourceRange();
Richard Trieu493df1a2013-08-08 01:50:23 +00009692 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
9693 // Error on enum increments and decrements in C++ mode
9694 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
9695 return QualType();
Sebastian Redle10c2c32008-12-20 09:35:34 +00009696 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00009697 // OK!
John McCallf2538342012-07-31 05:14:30 +00009698 } else if (ResType->isPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00009699 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00009700 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00009701 return QualType();
John McCallf2538342012-07-31 05:14:30 +00009702 } else if (ResType->isObjCObjectPointerType()) {
9703 // On modern runtimes, ObjC pointer arithmetic is forbidden.
9704 // Otherwise, we just need a complete type.
9705 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
9706 checkArithmeticOnObjCPointer(S, OpLoc, Op))
9707 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +00009708 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00009709 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00009710 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00009711 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00009712 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00009713 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00009714 if (PR.isInvalid()) return QualType();
David Majnemer74242432014-07-31 04:52:13 +00009715 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009716 IsInc, IsPrefix);
David Blaikiebbafb8a2012-03-11 07:00:24 +00009717 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev85129b82011-02-07 02:17:30 +00009718 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00009719 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
9720 (ResType->getAs<VectorType>()->getVectorKind() !=
9721 VectorType::AltiVecBool)) {
9722 // The z vector extensions allow ++ and -- for non-bool vectors.
David Tweed16574d82013-09-06 09:58:08 +00009723 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
9724 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
9725 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
Chris Lattner6b0cf142008-11-21 07:05:48 +00009726 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00009727 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuba63ce62011-09-09 01:45:06 +00009728 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00009729 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00009730 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009731 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00009732 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00009733 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00009734 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00009735 // In C++, a prefix increment is the same type as the operand. Otherwise
9736 // (in C or with postfix), the increment is the unqualified type of the
9737 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009738 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00009739 VK = VK_LValue;
David Majnemer74242432014-07-31 04:52:13 +00009740 OK = Op->getObjectKind();
John McCall4bc41ae2010-11-18 19:01:18 +00009741 return ResType;
9742 } else {
9743 VK = VK_RValue;
9744 return ResType.getUnqualifiedType();
9745 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00009746}
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00009747
9748
Anders Carlsson806700f2008-02-01 07:15:58 +00009749/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00009750/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00009751/// where the declaration is needed for type checking. We only need to
9752/// handle cases when the expression references a function designator
9753/// or is an lvalue. Here are some examples:
9754/// - &(x) => x
9755/// - &*****f => f for f a function designator.
9756/// - &s.xx => s
9757/// - &s.zz[1].yy -> s, if zz is an array
9758/// - *(x + 1) -> x, if x is an array
9759/// - &"123"[2] -> 0
9760/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00009761static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00009762 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00009763 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00009764 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00009765 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00009766 // If this is an arrow operator, the address is an offset from
9767 // the base's value, so the object the base refers to is
9768 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00009769 if (cast<MemberExpr>(E)->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00009770 return nullptr;
Eli Friedman3a1e6922009-04-20 08:23:18 +00009771 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00009772 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00009773 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00009774 // FIXME: This code shouldn't be necessary! We should catch the implicit
9775 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00009776 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
9777 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
9778 if (ICE->getSubExpr()->getType()->isArrayType())
9779 return getPrimaryDecl(ICE->getSubExpr());
9780 }
Craig Topperc3ec1492014-05-26 06:22:03 +00009781 return nullptr;
Anders Carlsson806700f2008-02-01 07:15:58 +00009782 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00009783 case Stmt::UnaryOperatorClass: {
9784 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009785
Daniel Dunbarb692ef42008-08-04 20:02:37 +00009786 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009787 case UO_Real:
9788 case UO_Imag:
9789 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00009790 return getPrimaryDecl(UO->getSubExpr());
9791 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00009792 return nullptr;
Daniel Dunbarb692ef42008-08-04 20:02:37 +00009793 }
9794 }
Steve Naroff47500512007-04-19 23:00:49 +00009795 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00009796 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00009797 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00009798 // If the result of an implicit cast is an l-value, we care about
9799 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00009800 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00009801 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00009802 return nullptr;
Steve Naroff47500512007-04-19 23:00:49 +00009803 }
9804}
9805
Richard Trieu5f376f62011-09-07 21:46:33 +00009806namespace {
9807 enum {
9808 AO_Bit_Field = 0,
9809 AO_Vector_Element = 1,
9810 AO_Property_Expansion = 2,
9811 AO_Register_Variable = 3,
9812 AO_No_Error = 4
9813 };
9814}
Richard Trieu3fd7bb82011-09-02 00:47:55 +00009815/// \brief Diagnose invalid operand for address of operations.
9816///
9817/// \param Type The type of operand which cannot have its address taken.
Richard Trieu3fd7bb82011-09-02 00:47:55 +00009818static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
9819 Expr *E, unsigned Type) {
9820 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
9821}
9822
Steve Naroff47500512007-04-19 23:00:49 +00009823/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00009824/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00009825/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00009826/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00009827/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00009828/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00009829/// we allow the '&' but retain the overloaded-function type.
Richard Smithaf9de912013-07-11 02:26:56 +00009830QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
John McCall526ab472011-10-25 17:37:35 +00009831 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
9832 if (PTy->getKind() == BuiltinType::Overload) {
David Majnemer0f328442013-07-05 06:23:33 +00009833 Expr *E = OrigOp.get()->IgnoreParens();
9834 if (!isa<OverloadExpr>(E)) {
9835 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
Richard Smithaf9de912013-07-11 02:26:56 +00009836 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
John McCall526ab472011-10-25 17:37:35 +00009837 << OrigOp.get()->getSourceRange();
9838 return QualType();
9839 }
David Majnemer66ad5742013-06-11 03:56:29 +00009840
David Majnemer0f328442013-07-05 06:23:33 +00009841 OverloadExpr *Ovl = cast<OverloadExpr>(E);
David Majnemer66ad5742013-06-11 03:56:29 +00009842 if (isa<UnresolvedMemberExpr>(Ovl))
Richard Smithaf9de912013-07-11 02:26:56 +00009843 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
9844 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
David Majnemer66ad5742013-06-11 03:56:29 +00009845 << OrigOp.get()->getSourceRange();
9846 return QualType();
9847 }
9848
Richard Smithaf9de912013-07-11 02:26:56 +00009849 return Context.OverloadTy;
John McCall526ab472011-10-25 17:37:35 +00009850 }
9851
9852 if (PTy->getKind() == BuiltinType::UnknownAny)
Richard Smithaf9de912013-07-11 02:26:56 +00009853 return Context.UnknownAnyTy;
John McCall526ab472011-10-25 17:37:35 +00009854
9855 if (PTy->getKind() == BuiltinType::BoundMember) {
Richard Smithaf9de912013-07-11 02:26:56 +00009856 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00009857 << OrigOp.get()->getSourceRange();
Douglas Gregor668d3622011-10-09 19:10:41 +00009858 return QualType();
9859 }
John McCall526ab472011-10-25 17:37:35 +00009860
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009861 OrigOp = CheckPlaceholderExpr(OrigOp.get());
John McCall526ab472011-10-25 17:37:35 +00009862 if (OrigOp.isInvalid()) return QualType();
John McCall0009fcc2011-04-26 20:42:42 +00009863 }
John McCall8d08b9b2010-08-27 09:08:28 +00009864
John McCall526ab472011-10-25 17:37:35 +00009865 if (OrigOp.get()->isTypeDependent())
Richard Smithaf9de912013-07-11 02:26:56 +00009866 return Context.DependentTy;
John McCall526ab472011-10-25 17:37:35 +00009867
9868 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00009869
John McCall8d08b9b2010-08-27 09:08:28 +00009870 // Make sure to ignore parentheses in subsequent checks
John McCall526ab472011-10-25 17:37:35 +00009871 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00009872
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +00009873 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
9874 if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
9875 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
9876 return QualType();
9877 }
9878
Richard Smithaf9de912013-07-11 02:26:56 +00009879 if (getLangOpts().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00009880 // Implement C99-only parts of addressof rules.
9881 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00009882 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00009883 // Per C99 6.5.3.2, the address of a deref always returns a valid result
9884 // (assuming the deref expression is valid).
9885 return uOp->getSubExpr()->getType();
9886 }
9887 // Technically, there should be a check for array subscript
9888 // expressions here, but the result of one is always an lvalue anyway.
9889 }
John McCallf3a88602011-02-03 08:15:49 +00009890 ValueDecl *dcl = getPrimaryDecl(op);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009891
9892 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
9893 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
9894 op->getLocStart()))
9895 return QualType();
9896
Richard Smithaf9de912013-07-11 02:26:56 +00009897 Expr::LValueClassification lval = op->ClassifyLValue(Context);
Richard Trieu5f376f62011-09-07 21:46:33 +00009898 unsigned AddressOfError = AO_No_Error;
Nuno Lopes17f345f2008-12-16 22:59:47 +00009899
Richard Smithc084bd282013-02-02 02:14:45 +00009900 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
Richard Smithaf9de912013-07-11 02:26:56 +00009901 bool sfinae = (bool)isSFINAEContext();
9902 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
9903 : diag::ext_typecheck_addrof_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00009904 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00009905 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00009906 return QualType();
Richard Smith9f8400e2013-05-01 19:00:39 +00009907 // Materialize the temporary as an lvalue so that we can take its address.
Richard Smithaf9de912013-07-11 02:26:56 +00009908 OrigOp = op = new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009909 MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
John McCall8d08b9b2010-08-27 09:08:28 +00009910 } else if (isa<ObjCSelectorExpr>(op)) {
Richard Smithaf9de912013-07-11 02:26:56 +00009911 return Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00009912 } else if (lval == Expr::LV_MemberFunction) {
9913 // If it's an instance method, make a member pointer.
9914 // The expression must have exactly the form &A::foo.
9915
9916 // If the underlying expression isn't a decl ref, give up.
9917 if (!isa<DeclRefExpr>(op)) {
Richard Smithaf9de912013-07-11 02:26:56 +00009918 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00009919 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00009920 return QualType();
9921 }
9922 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
9923 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
9924
9925 // The id-expression was parenthesized.
John McCall526ab472011-10-25 17:37:35 +00009926 if (OrigOp.get() != DRE) {
Richard Smithaf9de912013-07-11 02:26:56 +00009927 Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00009928 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00009929
9930 // The method was named without a qualifier.
9931 } else if (!DRE->getQualifier()) {
David Blaikiec2ff8e12012-10-11 22:55:07 +00009932 if (MD->getParent()->getName().empty())
Richard Smithaf9de912013-07-11 02:26:56 +00009933 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
David Blaikiec2ff8e12012-10-11 22:55:07 +00009934 << op->getSourceRange();
9935 else {
9936 SmallString<32> Str;
9937 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
Richard Smithaf9de912013-07-11 02:26:56 +00009938 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
David Blaikiec2ff8e12012-10-11 22:55:07 +00009939 << op->getSourceRange()
9940 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
9941 }
John McCall8d08b9b2010-08-27 09:08:28 +00009942 }
9943
Benjamin Kramer915d1692013-10-10 09:44:41 +00009944 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
9945 if (isa<CXXDestructorDecl>(MD))
9946 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
9947
David Majnemer1cdd96d2014-01-17 09:01:00 +00009948 QualType MPTy = Context.getMemberPointerType(
9949 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
9950 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
9951 RequireCompleteType(OpLoc, MPTy, 0);
9952 return MPTy;
John McCall8d08b9b2010-08-27 09:08:28 +00009953 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00009954 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00009955 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00009956 if (!op->getType()->isFunctionType()) {
John McCall526ab472011-10-25 17:37:35 +00009957 // Use a special diagnostic for loads from property references.
John McCallfe96e0b2011-11-06 09:01:30 +00009958 if (isa<PseudoObjectExpr>(op)) {
John McCall526ab472011-10-25 17:37:35 +00009959 AddressOfError = AO_Property_Expansion;
9960 } else {
Richard Smithaf9de912013-07-11 02:26:56 +00009961 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Richard Smithc084bd282013-02-02 02:14:45 +00009962 << op->getType() << op->getSourceRange();
John McCall526ab472011-10-25 17:37:35 +00009963 return QualType();
9964 }
Steve Naroff35d85152007-05-07 00:24:15 +00009965 }
John McCall086a4642010-11-24 05:12:34 +00009966 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00009967 // The operand cannot be a bit-field
Richard Trieu5f376f62011-09-07 21:46:33 +00009968 AddressOfError = AO_Bit_Field;
John McCall086a4642010-11-24 05:12:34 +00009969 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00009970 // The operand cannot be an element of a vector
Richard Trieu5f376f62011-09-07 21:46:33 +00009971 AddressOfError = AO_Vector_Element;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00009972 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00009973 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00009974 // with the register storage-class specifier.
9975 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00009976 // in C++ it is not error to take address of a register
9977 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00009978 if (vd->getStorageClass() == SC_Register &&
Richard Smithaf9de912013-07-11 02:26:56 +00009979 !getLangOpts().CPlusPlus) {
Richard Trieu5f376f62011-09-07 21:46:33 +00009980 AddressOfError = AO_Register_Variable;
Steve Naroff35d85152007-05-07 00:24:15 +00009981 }
Reid Kleckner85c7e0a2015-02-24 20:29:40 +00009982 } else if (isa<MSPropertyDecl>(dcl)) {
9983 AddressOfError = AO_Property_Expansion;
John McCalld14a8642009-11-21 08:51:07 +00009984 } else if (isa<FunctionTemplateDecl>(dcl)) {
Richard Smithaf9de912013-07-11 02:26:56 +00009985 return Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00009986 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00009987 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00009988 // Could be a pointer to member, though, if there is an explicit
9989 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00009990 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00009991 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00009992 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00009993 if (dcl->getType()->isReferenceType()) {
Richard Smithaf9de912013-07-11 02:26:56 +00009994 Diag(OpLoc,
9995 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00009996 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00009997 return QualType();
9998 }
Mike Stump11289f42009-09-09 15:08:12 +00009999
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +000010000 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10001 Ctx = Ctx->getParent();
David Majnemer1cdd96d2014-01-17 09:01:00 +000010002
10003 QualType MPTy = Context.getMemberPointerType(
10004 op->getType(),
10005 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10006 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10007 RequireCompleteType(OpLoc, MPTy, 0);
10008 return MPTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +000010009 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +000010010 }
Eli Friedman755c0c92011-08-26 20:28:17 +000010011 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikie83d382b2011-09-23 05:06:16 +000010012 llvm_unreachable("Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +000010013 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010014
Richard Trieu5f376f62011-09-07 21:46:33 +000010015 if (AddressOfError != AO_No_Error) {
Richard Smithaf9de912013-07-11 02:26:56 +000010016 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
Richard Trieu5f376f62011-09-07 21:46:33 +000010017 return QualType();
10018 }
10019
Eli Friedmance7f9002009-05-16 23:27:50 +000010020 if (lval == Expr::LV_IncompleteVoidType) {
10021 // Taking the address of a void variable is technically illegal, but we
10022 // allow it in cases which are otherwise valid.
10023 // Example: "extern void x; void* y = &x;".
Richard Smithaf9de912013-07-11 02:26:56 +000010024 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +000010025 }
10026
Steve Naroff47500512007-04-19 23:00:49 +000010027 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +000010028 if (op->getType()->isObjCObjectType())
Richard Smithaf9de912013-07-11 02:26:56 +000010029 return Context.getObjCObjectPointerType(op->getType());
10030 return Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +000010031}
10032
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010033static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10034 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10035 if (!DRE)
10036 return;
10037 const Decl *D = DRE->getDecl();
10038 if (!D)
10039 return;
10040 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10041 if (!Param)
10042 return;
10043 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
Aaron Ballman2521f362014-12-11 19:35:42 +000010044 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010045 return;
10046 if (FunctionScopeInfo *FD = S.getCurFunction())
10047 if (!FD->ModifiedNonNullParams.count(Param))
10048 FD->ModifiedNonNullParams.insert(Param);
10049}
10050
Chris Lattner9156f1b2010-07-05 19:17:26 +000010051/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +000010052static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10053 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000010054 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +000010055 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000010056
John Wiegley01296292011-04-08 18:41:53 +000010057 ExprResult ConvResult = S.UsualUnaryConversions(Op);
10058 if (ConvResult.isInvalid())
10059 return QualType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010060 Op = ConvResult.get();
Chris Lattner9156f1b2010-07-05 19:17:26 +000010061 QualType OpTy = Op->getType();
10062 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +000010063
10064 if (isa<CXXReinterpretCastExpr>(Op)) {
10065 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10066 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10067 Op->getSourceRange());
10068 }
10069
Chris Lattner9156f1b2010-07-05 19:17:26 +000010070 if (const PointerType *PT = OpTy->getAs<PointerType>())
10071 Result = PT->getPointeeType();
10072 else if (const ObjCObjectPointerType *OPT =
10073 OpTy->getAs<ObjCObjectPointerType>())
10074 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +000010075 else {
John McCall3aef3d82011-04-10 19:13:55 +000010076 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +000010077 if (PR.isInvalid()) return QualType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010078 if (PR.get() != Op)
10079 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +000010080 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000010081
Chris Lattner9156f1b2010-07-05 19:17:26 +000010082 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +000010083 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +000010084 << OpTy << Op->getSourceRange();
10085 return QualType();
10086 }
John McCall4bc41ae2010-11-18 19:01:18 +000010087
Richard Smith80877c22014-05-07 21:53:27 +000010088 // Note that per both C89 and C99, indirection is always legal, even if Result
10089 // is an incomplete type or void. It would be possible to warn about
10090 // dereferencing a void pointer, but it's completely well-defined, and such a
10091 // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10092 // for pointers to 'void' but is fine for any other pointer type:
10093 //
10094 // C++ [expr.unary.op]p1:
10095 // [...] the expression to which [the unary * operator] is applied shall
10096 // be a pointer to an object type, or a pointer to a function type
10097 if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10098 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10099 << OpTy << Op->getSourceRange();
10100
John McCall4bc41ae2010-11-18 19:01:18 +000010101 // Dereferences are usually l-values...
10102 VK = VK_LValue;
10103
10104 // ...except that certain expressions are never l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010105 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +000010106 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +000010107
10108 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +000010109}
Steve Naroff218bc2b2007-05-04 21:54:46 +000010110
Richard Smith0f0af192014-11-08 05:07:16 +000010111BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +000010112 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +000010113 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +000010114 default: llvm_unreachable("Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +000010115 case tok::periodstar: Opc = BO_PtrMemD; break;
10116 case tok::arrowstar: Opc = BO_PtrMemI; break;
10117 case tok::star: Opc = BO_Mul; break;
10118 case tok::slash: Opc = BO_Div; break;
10119 case tok::percent: Opc = BO_Rem; break;
10120 case tok::plus: Opc = BO_Add; break;
10121 case tok::minus: Opc = BO_Sub; break;
10122 case tok::lessless: Opc = BO_Shl; break;
10123 case tok::greatergreater: Opc = BO_Shr; break;
10124 case tok::lessequal: Opc = BO_LE; break;
10125 case tok::less: Opc = BO_LT; break;
10126 case tok::greaterequal: Opc = BO_GE; break;
10127 case tok::greater: Opc = BO_GT; break;
10128 case tok::exclaimequal: Opc = BO_NE; break;
10129 case tok::equalequal: Opc = BO_EQ; break;
10130 case tok::amp: Opc = BO_And; break;
10131 case tok::caret: Opc = BO_Xor; break;
10132 case tok::pipe: Opc = BO_Or; break;
10133 case tok::ampamp: Opc = BO_LAnd; break;
10134 case tok::pipepipe: Opc = BO_LOr; break;
10135 case tok::equal: Opc = BO_Assign; break;
10136 case tok::starequal: Opc = BO_MulAssign; break;
10137 case tok::slashequal: Opc = BO_DivAssign; break;
10138 case tok::percentequal: Opc = BO_RemAssign; break;
10139 case tok::plusequal: Opc = BO_AddAssign; break;
10140 case tok::minusequal: Opc = BO_SubAssign; break;
10141 case tok::lesslessequal: Opc = BO_ShlAssign; break;
10142 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
10143 case tok::ampequal: Opc = BO_AndAssign; break;
10144 case tok::caretequal: Opc = BO_XorAssign; break;
10145 case tok::pipeequal: Opc = BO_OrAssign; break;
10146 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +000010147 }
10148 return Opc;
10149}
10150
John McCalle3027922010-08-25 11:45:40 +000010151static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +000010152 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +000010153 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +000010154 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +000010155 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +000010156 case tok::plusplus: Opc = UO_PreInc; break;
10157 case tok::minusminus: Opc = UO_PreDec; break;
10158 case tok::amp: Opc = UO_AddrOf; break;
10159 case tok::star: Opc = UO_Deref; break;
10160 case tok::plus: Opc = UO_Plus; break;
10161 case tok::minus: Opc = UO_Minus; break;
10162 case tok::tilde: Opc = UO_Not; break;
10163 case tok::exclaim: Opc = UO_LNot; break;
10164 case tok::kw___real: Opc = UO_Real; break;
10165 case tok::kw___imag: Opc = UO_Imag; break;
10166 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +000010167 }
10168 return Opc;
10169}
10170
Chandler Carruthe0cee6a2011-01-04 06:52:15 +000010171/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
10172/// This warning is only emitted for builtin assignment operations. It is also
10173/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +000010174static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +000010175 SourceLocation OpLoc) {
10176 if (!S.ActiveTemplateInstantiations.empty())
10177 return;
10178 if (OpLoc.isInvalid() || OpLoc.isMacroID())
10179 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +000010180 LHSExpr = LHSExpr->IgnoreParenImpCasts();
10181 RHSExpr = RHSExpr->IgnoreParenImpCasts();
10182 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10183 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10184 if (!LHSDeclRef || !RHSDeclRef ||
10185 LHSDeclRef->getLocation().isMacroID() ||
10186 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +000010187 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +000010188 const ValueDecl *LHSDecl =
10189 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
10190 const ValueDecl *RHSDecl =
10191 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
10192 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +000010193 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +000010194 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +000010195 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +000010196 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +000010197 if (RefTy->getPointeeType().isVolatileQualified())
10198 return;
10199
10200 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +000010201 << LHSDeclRef->getType()
10202 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +000010203}
10204
Ted Kremenekebeabab2013-04-22 22:46:52 +000010205/// Check if a bitwise-& is performed on an Objective-C pointer. This
10206/// is usually indicative of introspection within the Objective-C pointer.
10207static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
10208 SourceLocation OpLoc) {
10209 if (!S.getLangOpts().ObjC1)
10210 return;
10211
Craig Topperc3ec1492014-05-26 06:22:03 +000010212 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
Ted Kremenekebeabab2013-04-22 22:46:52 +000010213 const Expr *LHS = L.get();
10214 const Expr *RHS = R.get();
10215
10216 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10217 ObjCPointerExpr = LHS;
10218 OtherExpr = RHS;
10219 }
10220 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10221 ObjCPointerExpr = RHS;
10222 OtherExpr = LHS;
10223 }
10224
10225 // This warning is deliberately made very specific to reduce false
10226 // positives with logic that uses '&' for hashing. This logic mainly
10227 // looks for code trying to introspect into tagged pointers, which
10228 // code should generally never do.
10229 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
Ted Kremenek009d61d2013-06-24 21:35:39 +000010230 unsigned Diag = diag::warn_objc_pointer_masking;
10231 // Determine if we are introspecting the result of performSelectorXXX.
10232 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
10233 // Special case messages to -performSelector and friends, which
10234 // can return non-pointer values boxed in a pointer value.
10235 // Some clients may wish to silence warnings in this subcase.
10236 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
10237 Selector S = ME->getSelector();
10238 StringRef SelArg0 = S.getNameForSlot(0);
10239 if (SelArg0.startswith("performSelector"))
10240 Diag = diag::warn_objc_pointer_masking_performSelector;
10241 }
10242
10243 S.Diag(OpLoc, Diag)
Ted Kremenekebeabab2013-04-22 22:46:52 +000010244 << ObjCPointerExpr->getSourceRange();
10245 }
10246}
10247
Kaelyn Takata7a503692015-01-27 22:01:39 +000010248static NamedDecl *getDeclFromExpr(Expr *E) {
10249 if (!E)
10250 return nullptr;
10251 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
10252 return DRE->getDecl();
10253 if (auto *ME = dyn_cast<MemberExpr>(E))
10254 return ME->getMemberDecl();
10255 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
10256 return IRE->getDecl();
10257 return nullptr;
10258}
10259
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010260/// CreateBuiltinBinOp - Creates a new built-in binary operation with
10261/// operator @p Opc at location @c TokLoc. This routine only supports
10262/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +000010263ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +000010264 BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +000010265 Expr *LHSExpr, Expr *RHSExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010266 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl67766732012-02-27 20:34:02 +000010267 // The syntax only allows initializer lists on the RHS of assignment,
10268 // so we don't need to worry about accepting invalid code for
10269 // non-assignment operators.
10270 // C++11 5.17p9:
10271 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
10272 // of x = {} is x = T().
10273 InitializationKind Kind =
10274 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
10275 InitializedEntity Entity =
10276 InitializedEntity::InitializeTemporary(LHSExpr->getType());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000010277 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010278 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
Sebastian Redl67766732012-02-27 20:34:02 +000010279 if (Init.isInvalid())
10280 return Init;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010281 RHSExpr = Init.get();
Sebastian Redl67766732012-02-27 20:34:02 +000010282 }
10283
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010284 ExprResult LHS = LHSExpr, RHS = RHSExpr;
Eli Friedman8b7b1b12009-03-28 01:22:36 +000010285 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +000010286 // The following two variables are used for compound assignment operators
10287 QualType CompLHSTy; // Type of LHS after promotions for computation
10288 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +000010289 ExprValueKind VK = VK_RValue;
10290 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010291
Kaelyn Takata15867822014-11-21 18:48:04 +000010292 if (!getLangOpts().CPlusPlus) {
10293 // C cannot handle TypoExpr nodes on either side of a binop because it
10294 // doesn't handle dependent types properly, so make sure any TypoExprs have
10295 // been dealt with before checking the operands.
10296 LHS = CorrectDelayedTyposInExpr(LHSExpr);
Kaelyn Takata7a503692015-01-27 22:01:39 +000010297 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
10298 if (Opc != BO_Assign)
10299 return ExprResult(E);
10300 // Avoid correcting the RHS to the same Expr as the LHS.
10301 Decl *D = getDeclFromExpr(E);
10302 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
10303 });
Kaelyn Takata15867822014-11-21 18:48:04 +000010304 if (!LHS.isUsable() || !RHS.isUsable())
10305 return ExprError();
10306 }
10307
Anastasia Stulovade0e4242015-09-30 13:18:52 +000010308 if (getLangOpts().OpenCL) {
10309 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
10310 // the ATOMIC_VAR_INIT macro.
10311 if (LHSExpr->getType()->isAtomicType() ||
10312 RHSExpr->getType()->isAtomicType()) {
10313 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
10314 if (BO_Assign == Opc)
10315 Diag(OpLoc, diag::err_atomic_init_constant) << SR;
10316 else
10317 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
10318 return ExprError();
10319 }
10320 }
10321
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010322 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +000010323 case BO_Assign:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010324 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikiebbafb8a2012-03-11 07:00:24 +000010325 if (getLangOpts().CPlusPlus &&
Richard Trieu4a287fb2011-09-07 01:49:20 +000010326 LHS.get()->getObjectKind() != OK_ObjCProperty) {
10327 VK = LHS.get()->getValueKind();
10328 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +000010329 }
Richard Trieu17ddb822015-01-10 06:04:18 +000010330 if (!ResultTy.isNull()) {
Richard Trieu4a287fb2011-09-07 01:49:20 +000010331 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010332 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
Richard Trieu17ddb822015-01-10 06:04:18 +000010333 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010334 RecordModifiableNonNullParam(*this, LHS.get());
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010335 break;
John McCalle3027922010-08-25 11:45:40 +000010336 case BO_PtrMemD:
10337 case BO_PtrMemI:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010338 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +000010339 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +000010340 break;
John McCalle3027922010-08-25 11:45:40 +000010341 case BO_Mul:
10342 case BO_Div:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010343 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +000010344 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010345 break;
John McCalle3027922010-08-25 11:45:40 +000010346 case BO_Rem:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010347 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010348 break;
John McCalle3027922010-08-25 11:45:40 +000010349 case BO_Add:
Nico Weberccec40d2012-03-02 22:01:22 +000010350 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010351 break;
John McCalle3027922010-08-25 11:45:40 +000010352 case BO_Sub:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010353 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010354 break;
John McCalle3027922010-08-25 11:45:40 +000010355 case BO_Shl:
10356 case BO_Shr:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010357 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010358 break;
John McCalle3027922010-08-25 11:45:40 +000010359 case BO_LE:
10360 case BO_LT:
10361 case BO_GE:
10362 case BO_GT:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010363 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010364 break;
John McCalle3027922010-08-25 11:45:40 +000010365 case BO_EQ:
10366 case BO_NE:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010367 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010368 break;
John McCalle3027922010-08-25 11:45:40 +000010369 case BO_And:
Ted Kremenekebeabab2013-04-22 22:46:52 +000010370 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
John McCalle3027922010-08-25 11:45:40 +000010371 case BO_Xor:
10372 case BO_Or:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010373 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010374 break;
John McCalle3027922010-08-25 11:45:40 +000010375 case BO_LAnd:
10376 case BO_LOr:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010377 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010378 break;
John McCalle3027922010-08-25 11:45:40 +000010379 case BO_MulAssign:
10380 case BO_DivAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010381 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +000010382 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +000010383 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +000010384 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10385 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010386 break;
John McCalle3027922010-08-25 11:45:40 +000010387 case BO_RemAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010388 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +000010389 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +000010390 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10391 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010392 break;
John McCalle3027922010-08-25 11:45:40 +000010393 case BO_AddAssign:
Nico Weberccec40d2012-03-02 22:01:22 +000010394 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu4a287fb2011-09-07 01:49:20 +000010395 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10396 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010397 break;
John McCalle3027922010-08-25 11:45:40 +000010398 case BO_SubAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010399 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
10400 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10401 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010402 break;
John McCalle3027922010-08-25 11:45:40 +000010403 case BO_ShlAssign:
10404 case BO_ShrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010405 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +000010406 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +000010407 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10408 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010409 break;
John McCalle3027922010-08-25 11:45:40 +000010410 case BO_AndAssign:
Nikola Smiljanic292b5ce2014-05-30 00:15:04 +000010411 case BO_OrAssign: // fallthrough
Craig Topperbd44cd92015-12-08 04:33:04 +000010412 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
John McCalle3027922010-08-25 11:45:40 +000010413 case BO_XorAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010414 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +000010415 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +000010416 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10417 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010418 break;
John McCalle3027922010-08-25 11:45:40 +000010419 case BO_Comma:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010420 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikiebbafb8a2012-03-11 07:00:24 +000010421 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu4a287fb2011-09-07 01:49:20 +000010422 VK = RHS.get()->getValueKind();
10423 OK = RHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +000010424 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010425 break;
10426 }
Richard Trieu4a287fb2011-09-07 01:49:20 +000010427 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +000010428 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010429
10430 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu4a287fb2011-09-07 01:49:20 +000010431 CheckArrayAccess(LHS.get());
10432 CheckArrayAccess(RHS.get());
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010433
Fariborz Jahanian06bb7f72013-03-28 19:50:55 +000010434 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
10435 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
10436 &Context.Idents.get("object_setClass"),
10437 SourceLocation(), LookupOrdinaryName);
10438 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
Craig Topper07fa1762015-11-15 02:31:46 +000010439 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
Fariborz Jahanian06bb7f72013-03-28 19:50:55 +000010440 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
10441 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
10442 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
10443 FixItHint::CreateInsertion(RHSLocEnd, ")");
10444 }
10445 else
10446 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
10447 }
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +000010448 else if (const ObjCIvarRefExpr *OIRE =
10449 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +000010450 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +000010451
Eli Friedman8b7b1b12009-03-28 01:22:36 +000010452 if (CompResultTy.isNull())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010453 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
10454 OK, OpLoc, FPFeatures.fp_contract);
David Blaikiebbafb8a2012-03-11 07:00:24 +000010455 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieucfc491d2011-08-02 04:35:43 +000010456 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +000010457 VK = VK_LValue;
Richard Trieu4a287fb2011-09-07 01:49:20 +000010458 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +000010459 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010460 return new (Context) CompoundAssignOperator(
10461 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
10462 OpLoc, FPFeatures.fp_contract);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010463}
10464
Sebastian Redl44615072009-10-27 12:10:02 +000010465/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
10466/// operators are mixed in a way that suggests that the programmer forgot that
10467/// comparison operators have higher precedence. The most typical example of
10468/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +000010469static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +000010470 SourceLocation OpLoc, Expr *LHSExpr,
10471 Expr *RHSExpr) {
Eli Friedman37feb2d2012-11-15 00:29:07 +000010472 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
10473 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +000010474
Craig Topperf942fde2015-12-12 06:30:48 +000010475 // Check that one of the sides is a comparison operator and the other isn't.
Eli Friedman37feb2d2012-11-15 00:29:07 +000010476 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
10477 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
Craig Topperf942fde2015-12-12 06:30:48 +000010478 if (isLeftComp == isRightComp)
Sebastian Redl43028242009-10-26 15:24:15 +000010479 return;
10480
10481 // Bitwise operations are sometimes used as eager logical ops.
10482 // Don't diagnose this.
Eli Friedman37feb2d2012-11-15 00:29:07 +000010483 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
10484 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
Craig Topperf942fde2015-12-12 06:30:48 +000010485 if (isLeftBitwise || isRightBitwise)
Sebastian Redl43028242009-10-26 15:24:15 +000010486 return;
10487
Richard Trieu4a287fb2011-09-07 01:49:20 +000010488 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
10489 OpLoc)
10490 : SourceRange(OpLoc, RHSExpr->getLocEnd());
Eli Friedman37feb2d2012-11-15 00:29:07 +000010491 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
Richard Trieu73088052011-08-10 22:41:34 +000010492 SourceRange ParensRange = isLeftComp ?
Eli Friedman37feb2d2012-11-15 00:29:07 +000010493 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
Richard Trieu7ec1a312014-08-23 00:30:57 +000010494 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
Richard Trieu73088052011-08-10 22:41:34 +000010495
10496 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
Eli Friedman37feb2d2012-11-15 00:29:07 +000010497 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
Richard Trieu73088052011-08-10 22:41:34 +000010498 SuggestParentheses(Self, OpLoc,
David Blaikiedac86fd2012-10-08 01:19:49 +000010499 Self.PDiag(diag::note_precedence_silence) << OpStr,
Nico Webercdfb1ae2012-06-03 07:07:00 +000010500 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu73088052011-08-10 22:41:34 +000010501 SuggestParentheses(Self, OpLoc,
Eli Friedman37feb2d2012-11-15 00:29:07 +000010502 Self.PDiag(diag::note_precedence_bitwise_first)
10503 << BinaryOperator::getOpcodeStr(Opc),
Richard Trieu73088052011-08-10 22:41:34 +000010504 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +000010505}
10506
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +000010507/// \brief It accepts a '&&' expr that is inside a '||' one.
10508/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
10509/// in parentheses.
10510static void
10511EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +000010512 BinaryOperator *Bop) {
10513 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +000010514 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
10515 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +000010516 SuggestParentheses(Self, Bop->getOperatorLoc(),
David Blaikiedac86fd2012-10-08 01:19:49 +000010517 Self.PDiag(diag::note_precedence_silence)
10518 << Bop->getOpcodeStr(),
Chandler Carruthb00e8c02011-06-16 01:05:14 +000010519 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +000010520}
10521
10522/// \brief Returns true if the given expression can be evaluated as a constant
10523/// 'true'.
10524static bool EvaluatesAsTrue(Sema &S, Expr *E) {
10525 bool Res;
Richard Smitha6c87032013-08-19 22:06:05 +000010526 return !E->isValueDependent() &&
10527 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +000010528}
10529
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +000010530/// \brief Returns true if the given expression can be evaluated as a constant
10531/// 'false'.
10532static bool EvaluatesAsFalse(Sema &S, Expr *E) {
10533 bool Res;
Richard Smitha6c87032013-08-19 22:06:05 +000010534 return !E->isValueDependent() &&
10535 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +000010536}
10537
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +000010538/// \brief Look for '&&' in the left hand of a '||' expr.
10539static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +000010540 Expr *LHSExpr, Expr *RHSExpr) {
10541 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +000010542 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +000010543 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +000010544 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +000010545 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +000010546 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
10547 if (!EvaluatesAsTrue(S, Bop->getLHS()))
10548 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
10549 } else if (Bop->getOpcode() == BO_LOr) {
10550 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
10551 // If it's "a || b && 1 || c" we didn't warn earlier for
10552 // "a || b && 1", but warn now.
10553 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
10554 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
10555 }
10556 }
10557 }
10558}
10559
10560/// \brief Look for '&&' in the right hand of a '||' expr.
10561static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +000010562 Expr *LHSExpr, Expr *RHSExpr) {
10563 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +000010564 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +000010565 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +000010566 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +000010567 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +000010568 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
10569 if (!EvaluatesAsTrue(S, Bop->getRHS()))
10570 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +000010571 }
10572 }
10573}
10574
Craig Topper84543b02015-12-13 05:41:41 +000010575/// \brief Look for bitwise op in the left or right hand of a bitwise op with
10576/// lower precedence and emit a diagnostic together with a fixit hint that wraps
10577/// the '&' expression in parentheses.
10578static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
10579 SourceLocation OpLoc, Expr *SubExpr) {
10580 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
10581 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
10582 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
10583 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
10584 << Bop->getSourceRange() << OpLoc;
10585 SuggestParentheses(S, Bop->getOperatorLoc(),
10586 S.PDiag(diag::note_precedence_silence)
10587 << Bop->getOpcodeStr(),
10588 Bop->getSourceRange());
10589 }
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +000010590 }
10591}
10592
David Blaikie15f17cb2012-10-05 00:41:03 +000010593static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
David Blaikie82d3ab92012-10-19 18:26:06 +000010594 Expr *SubExpr, StringRef Shift) {
David Blaikie15f17cb2012-10-05 00:41:03 +000010595 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
10596 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
David Blaikiedac86fd2012-10-08 01:19:49 +000010597 StringRef Op = Bop->getOpcodeStr();
David Blaikie15f17cb2012-10-05 00:41:03 +000010598 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
David Blaikie82d3ab92012-10-19 18:26:06 +000010599 << Bop->getSourceRange() << OpLoc << Shift << Op;
David Blaikie15f17cb2012-10-05 00:41:03 +000010600 SuggestParentheses(S, Bop->getOperatorLoc(),
David Blaikiedac86fd2012-10-08 01:19:49 +000010601 S.PDiag(diag::note_precedence_silence) << Op,
David Blaikie15f17cb2012-10-05 00:41:03 +000010602 Bop->getSourceRange());
10603 }
10604 }
10605}
10606
Richard Trieufe042e62013-04-17 02:12:45 +000010607static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
10608 Expr *LHSExpr, Expr *RHSExpr) {
10609 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
10610 if (!OCE)
10611 return;
10612
10613 FunctionDecl *FD = OCE->getDirectCallee();
10614 if (!FD || !FD->isOverloadedOperator())
10615 return;
10616
10617 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
10618 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
10619 return;
10620
10621 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
10622 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
10623 << (Kind == OO_LessLess);
Richard Trieufe042e62013-04-17 02:12:45 +000010624 SuggestParentheses(S, OCE->getOperatorLoc(),
10625 S.PDiag(diag::note_precedence_silence)
10626 << (Kind == OO_LessLess ? "<<" : ">>"),
10627 OCE->getSourceRange());
Richard Trieue0894972013-04-18 01:04:37 +000010628 SuggestParentheses(S, OpLoc,
10629 S.PDiag(diag::note_evaluate_comparison_first),
10630 SourceRange(OCE->getArg(1)->getLocStart(),
10631 RHSExpr->getLocEnd()));
Richard Trieufe042e62013-04-17 02:12:45 +000010632}
10633
Sebastian Redl43028242009-10-26 15:24:15 +000010634/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +000010635/// precedence.
John McCalle3027922010-08-25 11:45:40 +000010636static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +000010637 SourceLocation OpLoc, Expr *LHSExpr,
10638 Expr *RHSExpr){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +000010639 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +000010640 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieuf9bd0f52011-09-07 02:02:10 +000010641 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +000010642
10643 // Diagnose "arg1 & arg2 | arg3"
Craig Topper84543b02015-12-13 05:41:41 +000010644 if ((Opc == BO_Or || Opc == BO_Xor) &&
10645 !OpLoc.isMacroID()/* Don't warn in macros. */) {
10646 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
10647 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +000010648 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +000010649
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +000010650 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
10651 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +000010652 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +000010653 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
10654 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +000010655 }
David Blaikie15f17cb2012-10-05 00:41:03 +000010656
10657 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
10658 || Opc == BO_Shr) {
David Blaikie82d3ab92012-10-19 18:26:06 +000010659 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
10660 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
10661 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
David Blaikie15f17cb2012-10-05 00:41:03 +000010662 }
Richard Trieufe042e62013-04-17 02:12:45 +000010663
10664 // Warn on overloaded shift operators and comparisons, such as:
10665 // cout << 5 == 4;
10666 if (BinaryOperator::isComparisonOp(Opc))
10667 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +000010668}
10669
Steve Naroff218bc2b2007-05-04 21:54:46 +000010670// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +000010671ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +000010672 tok::TokenKind Kind,
Richard Trieuf9bd0f52011-09-07 02:02:10 +000010673 Expr *LHSExpr, Expr *RHSExpr) {
John McCalle3027922010-08-25 11:45:40 +000010674 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Craig Topperc3ec1492014-05-26 06:22:03 +000010675 assert(LHSExpr && "ActOnBinOp(): missing left expression");
10676 assert(RHSExpr && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +000010677
Sebastian Redl43028242009-10-26 15:24:15 +000010678 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieuf9bd0f52011-09-07 02:02:10 +000010679 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +000010680
Richard Trieuf9bd0f52011-09-07 02:02:10 +000010681 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor5287f092009-11-05 00:51:44 +000010682}
10683
John McCall526ab472011-10-25 17:37:35 +000010684/// Build an overloaded binary operator expression in the given scope.
10685static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
10686 BinaryOperatorKind Opc,
10687 Expr *LHS, Expr *RHS) {
10688 // Find all of the overloaded operators visible from this
10689 // point. We perform both an operator-name lookup from the local
10690 // scope and an argument-dependent lookup based on the types of
10691 // the arguments.
10692 UnresolvedSet<16> Functions;
10693 OverloadedOperatorKind OverOp
10694 = BinaryOperator::getOverloadedOperator(Opc);
Richard Smith0daabd72014-09-23 20:31:39 +000010695 if (Sc && OverOp != OO_None && OverOp != OO_Equal)
John McCall526ab472011-10-25 17:37:35 +000010696 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
10697 RHS->getType(), Functions);
10698
10699 // Build the (potentially-overloaded, potentially-dependent)
10700 // binary operation.
10701 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
10702}
10703
John McCalldadc5752010-08-24 06:29:42 +000010704ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +000010705 BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +000010706 Expr *LHSExpr, Expr *RHSExpr) {
John McCall9a43e122011-10-28 01:04:34 +000010707 // We want to end up calling one of checkPseudoObjectAssignment
10708 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
10709 // both expressions are overloadable or either is type-dependent),
10710 // or CreateBuiltinBinOp (in any other case). We also want to get
10711 // any placeholder types out of the way.
10712
John McCall526ab472011-10-25 17:37:35 +000010713 // Handle pseudo-objects in the LHS.
10714 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
10715 // Assignments with a pseudo-object l-value need special analysis.
10716 if (pty->getKind() == BuiltinType::PseudoObject &&
10717 BinaryOperator::isAssignmentOp(Opc))
10718 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
10719
10720 // Don't resolve overloads if the other type is overloadable.
10721 if (pty->getKind() == BuiltinType::Overload) {
10722 // We can't actually test that if we still have a placeholder,
10723 // though. Fortunately, none of the exceptions we see in that
John McCall9a43e122011-10-28 01:04:34 +000010724 // code below are valid when the LHS is an overload set. Note
10725 // that an overload set can be dependently-typed, but it never
10726 // instantiates to having an overloadable type.
John McCall526ab472011-10-25 17:37:35 +000010727 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
10728 if (resolvedRHS.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010729 RHSExpr = resolvedRHS.get();
John McCall526ab472011-10-25 17:37:35 +000010730
John McCall9a43e122011-10-28 01:04:34 +000010731 if (RHSExpr->isTypeDependent() ||
10732 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +000010733 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10734 }
10735
10736 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
10737 if (LHS.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010738 LHSExpr = LHS.get();
John McCall526ab472011-10-25 17:37:35 +000010739 }
10740
10741 // Handle pseudo-objects in the RHS.
10742 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
10743 // An overload in the RHS can potentially be resolved by the type
10744 // being assigned to.
John McCall9a43e122011-10-28 01:04:34 +000010745 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
10746 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
10747 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10748
Eli Friedman419b1ff2012-01-17 21:27:43 +000010749 if (LHSExpr->getType()->isOverloadableType())
10750 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10751
John McCall526ab472011-10-25 17:37:35 +000010752 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCall9a43e122011-10-28 01:04:34 +000010753 }
John McCall526ab472011-10-25 17:37:35 +000010754
10755 // Don't resolve overloads if the other type is overloadable.
10756 if (pty->getKind() == BuiltinType::Overload &&
10757 LHSExpr->getType()->isOverloadableType())
10758 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10759
10760 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
10761 if (!resolvedRHS.isUsable()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010762 RHSExpr = resolvedRHS.get();
John McCall526ab472011-10-25 17:37:35 +000010763 }
10764
David Blaikiebbafb8a2012-03-11 07:00:24 +000010765 if (getLangOpts().CPlusPlus) {
John McCall9a43e122011-10-28 01:04:34 +000010766 // If either expression is type-dependent, always build an
10767 // overloaded op.
10768 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
10769 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010770
John McCall9a43e122011-10-28 01:04:34 +000010771 // Otherwise, build an overloaded op if either expression has an
10772 // overloadable type.
10773 if (LHSExpr->getType()->isOverloadableType() ||
10774 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +000010775 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb5d49352009-01-19 22:31:54 +000010776 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010777
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010778 // Build a built-in binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +000010779 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Steve Naroff218bc2b2007-05-04 21:54:46 +000010780}
10781
John McCalldadc5752010-08-24 06:29:42 +000010782ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +000010783 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +000010784 Expr *InputExpr) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010785 ExprResult Input = InputExpr;
John McCall7decc9e2010-11-18 06:31:45 +000010786 ExprValueKind VK = VK_RValue;
10787 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +000010788 QualType resultType;
Anastasia Stulovade0e4242015-09-30 13:18:52 +000010789 if (getLangOpts().OpenCL) {
10790 // The only legal unary operation for atomics is '&'.
10791 if (Opc != UO_AddrOf && InputExpr->getType()->isAtomicType()) {
10792 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10793 << InputExpr->getType()
10794 << Input.get()->getSourceRange());
10795 }
10796 }
Steve Naroff35d85152007-05-07 00:24:15 +000010797 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +000010798 case UO_PreInc:
10799 case UO_PreDec:
10800 case UO_PostInc:
10801 case UO_PostDec:
David Majnemer74242432014-07-31 04:52:13 +000010802 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
10803 OpLoc,
John McCalle3027922010-08-25 11:45:40 +000010804 Opc == UO_PreInc ||
10805 Opc == UO_PostInc,
10806 Opc == UO_PreInc ||
10807 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +000010808 break;
John McCalle3027922010-08-25 11:45:40 +000010809 case UO_AddrOf:
Richard Smithaf9de912013-07-11 02:26:56 +000010810 resultType = CheckAddressOfOperand(Input, OpLoc);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010811 RecordModifiableNonNullParam(*this, InputExpr);
Steve Naroff35d85152007-05-07 00:24:15 +000010812 break;
John McCall31996342011-04-07 08:22:57 +000010813 case UO_Deref: {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010814 Input = DefaultFunctionArrayLvalueConversion(Input.get());
Eli Friedman34866c72012-08-31 00:14:07 +000010815 if (Input.isInvalid()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010816 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +000010817 break;
John McCall31996342011-04-07 08:22:57 +000010818 }
John McCalle3027922010-08-25 11:45:40 +000010819 case UO_Plus:
10820 case UO_Minus:
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010821 Input = UsualUnaryConversions(Input.get());
John Wiegley01296292011-04-08 18:41:53 +000010822 if (Input.isInvalid()) return ExprError();
10823 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000010824 if (resultType->isDependentType())
10825 break;
Ulrich Weigand3c5038a2015-07-30 14:08:36 +000010826 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
10827 break;
10828 else if (resultType->isVectorType() &&
10829 // The z vector extensions don't allow + or - with bool vectors.
10830 (!Context.getLangOpts().ZVector ||
10831 resultType->getAs<VectorType>()->getVectorKind() !=
10832 VectorType::AltiVecBool))
Douglas Gregord08452f2008-11-19 15:42:04 +000010833 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010834 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +000010835 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +000010836 resultType->isPointerType())
10837 break;
10838
Sebastian Redlc215cfc2009-01-19 00:08:26 +000010839 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +000010840 << resultType << Input.get()->getSourceRange());
10841
John McCalle3027922010-08-25 11:45:40 +000010842 case UO_Not: // bitwise complement
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010843 Input = UsualUnaryConversions(Input.get());
Joey Gouly7d00f002013-02-21 11:49:56 +000010844 if (Input.isInvalid())
10845 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010846 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000010847 if (resultType->isDependentType())
10848 break;
Chris Lattner0d707612008-07-25 23:52:49 +000010849 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
10850 if (resultType->isComplexType() || resultType->isComplexIntegerType())
10851 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +000010852 Diag(OpLoc, diag::ext_integer_complement_complex)
Joey Gouly7d00f002013-02-21 11:49:56 +000010853 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +000010854 else if (resultType->hasIntegerRepresentation())
10855 break;
Joey Gouly7d00f002013-02-21 11:49:56 +000010856 else if (resultType->isExtVectorType()) {
10857 if (Context.getLangOpts().OpenCL) {
10858 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
10859 // on vector float types.
10860 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
10861 if (!T->isIntegerType())
10862 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10863 << resultType << Input.get()->getSourceRange());
10864 }
10865 break;
10866 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +000010867 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
Joey Gouly7d00f002013-02-21 11:49:56 +000010868 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +000010869 }
Steve Naroff35d85152007-05-07 00:24:15 +000010870 break;
John Wiegley01296292011-04-08 18:41:53 +000010871
John McCalle3027922010-08-25 11:45:40 +000010872 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +000010873 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010874 Input = DefaultFunctionArrayLvalueConversion(Input.get());
John Wiegley01296292011-04-08 18:41:53 +000010875 if (Input.isInvalid()) return ExprError();
10876 resultType = Input.get()->getType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000010877
10878 // Though we still have to promote half FP to float...
Joey Goulydd7f4562013-01-23 11:56:20 +000010879 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010880 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000010881 resultType = Context.FloatTy;
10882 }
10883
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000010884 if (resultType->isDependentType())
10885 break;
Alp Tokerc620cab2014-01-20 07:20:22 +000010886 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
Abramo Bagnara7ccce982011-04-07 09:26:19 +000010887 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010888 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara7ccce982011-04-07 09:26:19 +000010889 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
10890 // operand contextually converted to bool.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010891 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
John Wiegley01296292011-04-08 18:41:53 +000010892 ScalarTypeToBooleanCastKind(resultType));
Joey Gouly7d00f002013-02-21 11:49:56 +000010893 } else if (Context.getLangOpts().OpenCL &&
10894 Context.getLangOpts().OpenCLVersion < 120) {
10895 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
10896 // operate on scalar float types.
10897 if (!resultType->isIntegerType())
10898 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10899 << resultType << Input.get()->getSourceRange());
Abramo Bagnara7ccce982011-04-07 09:26:19 +000010900 }
Tanya Lattner3dd33b22012-01-19 01:16:16 +000010901 } else if (resultType->isExtVectorType()) {
Joey Gouly7d00f002013-02-21 11:49:56 +000010902 if (Context.getLangOpts().OpenCL &&
10903 Context.getLangOpts().OpenCLVersion < 120) {
10904 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
10905 // operate on vector float types.
10906 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
10907 if (!T->isIntegerType())
10908 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10909 << resultType << Input.get()->getSourceRange());
10910 }
Tanya Lattner20248222012-01-16 21:02:28 +000010911 // Vector logical not returns the signed variant of the operand type.
10912 resultType = GetSignedVectorType(resultType);
10913 break;
John McCall36226622010-10-12 02:09:17 +000010914 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +000010915 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +000010916 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +000010917 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +000010918
Chris Lattnerbe31ed82007-06-02 19:11:33 +000010919 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +000010920 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +000010921 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +000010922 break;
John McCalle3027922010-08-25 11:45:40 +000010923 case UO_Real:
10924 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +000010925 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smith0b6b8e42012-02-18 20:53:32 +000010926 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
10927 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley01296292011-04-08 18:41:53 +000010928 if (Input.isInvalid()) return ExprError();
Richard Smith0b6b8e42012-02-18 20:53:32 +000010929 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
10930 if (Input.get()->getValueKind() != VK_RValue &&
10931 Input.get()->getObjectKind() == OK_Ordinary)
10932 VK = Input.get()->getValueKind();
David Blaikiebbafb8a2012-03-11 07:00:24 +000010933 } else if (!getLangOpts().CPlusPlus) {
Richard Smith0b6b8e42012-02-18 20:53:32 +000010934 // In C, a volatile scalar is read by __imag. In C++, it is not.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010935 Input = DefaultLvalueConversion(Input.get());
Richard Smith0b6b8e42012-02-18 20:53:32 +000010936 }
Chris Lattner30b5dd02007-08-24 21:16:53 +000010937 break;
John McCalle3027922010-08-25 11:45:40 +000010938 case UO_Extension:
Richard Smith9f690bd2015-10-27 06:02:45 +000010939 case UO_Coawait:
John Wiegley01296292011-04-08 18:41:53 +000010940 resultType = Input.get()->getType();
10941 VK = Input.get()->getValueKind();
10942 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +000010943 break;
Steve Naroff35d85152007-05-07 00:24:15 +000010944 }
John Wiegley01296292011-04-08 18:41:53 +000010945 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +000010946 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +000010947
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010948 // Check for array bounds violations in the operand of the UnaryOperator,
10949 // except for the '*' and '&' operators that have to be handled specially
10950 // by CheckArrayAccess (as there are special cases like &array[arraysize]
10951 // that are explicitly defined as valid by the standard).
10952 if (Opc != UO_AddrOf && Opc != UO_Deref)
10953 CheckArrayAccess(Input.get());
10954
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010955 return new (Context)
10956 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +000010957}
Chris Lattnereefa10e2007-05-28 06:56:27 +000010958
Douglas Gregor72341032011-12-14 21:23:13 +000010959/// \brief Determine whether the given expression is a qualified member
10960/// access expression, of a form that could be turned into a pointer to member
10961/// with the address-of operator.
10962static bool isQualifiedMemberAccess(Expr *E) {
10963 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10964 if (!DRE->getQualifier())
10965 return false;
10966
10967 ValueDecl *VD = DRE->getDecl();
10968 if (!VD->isCXXClassMember())
10969 return false;
10970
10971 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
10972 return true;
10973 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
10974 return Method->isInstance();
10975
10976 return false;
10977 }
10978
10979 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
10980 if (!ULE->getQualifier())
10981 return false;
10982
10983 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
10984 DEnd = ULE->decls_end();
10985 D != DEnd; ++D) {
10986 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
10987 if (Method->isInstance())
10988 return true;
10989 } else {
10990 // Overload set does not contain methods.
10991 break;
10992 }
10993 }
10994
10995 return false;
10996 }
10997
10998 return false;
10999}
11000
John McCalldadc5752010-08-24 06:29:42 +000011001ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +000011002 UnaryOperatorKind Opc, Expr *Input) {
John McCall526ab472011-10-25 17:37:35 +000011003 // First things first: handle placeholders so that the
11004 // overloaded-operator check considers the right type.
11005 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11006 // Increment and decrement of pseudo-object references.
11007 if (pty->getKind() == BuiltinType::PseudoObject &&
11008 UnaryOperator::isIncrementDecrementOp(Opc))
11009 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11010
11011 // extension is always a builtin operator.
11012 if (Opc == UO_Extension)
11013 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11014
11015 // & gets special logic for several kinds of placeholder.
11016 // The builtin code knows what to do.
11017 if (Opc == UO_AddrOf &&
11018 (pty->getKind() == BuiltinType::Overload ||
11019 pty->getKind() == BuiltinType::UnknownAny ||
11020 pty->getKind() == BuiltinType::BoundMember))
11021 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11022
11023 // Anything else needs to be handled now.
11024 ExprResult Result = CheckPlaceholderExpr(Input);
11025 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011026 Input = Result.get();
John McCall526ab472011-10-25 17:37:35 +000011027 }
11028
David Blaikiebbafb8a2012-03-11 07:00:24 +000011029 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregor72341032011-12-14 21:23:13 +000011030 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11031 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011032 // Find all of the overloaded operators visible from this
11033 // point. We perform both an operator-name lookup from the local
11034 // scope and an argument-dependent lookup based on the types of
11035 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +000011036 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +000011037 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +000011038 if (S && OverOp != OO_None)
11039 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11040 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011041
John McCallb268a282010-08-23 23:25:46 +000011042 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011043 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011044
John McCallb268a282010-08-23 23:25:46 +000011045 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011046}
11047
Douglas Gregor5287f092009-11-05 00:51:44 +000011048// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +000011049ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +000011050 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +000011051 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +000011052}
11053
Steve Naroff66356bd2007-09-16 14:56:35 +000011054/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +000011055ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +000011056 LabelDecl *TheDecl) {
Eli Friedman276dd182013-09-05 00:02:25 +000011057 TheDecl->markUsed(Context);
Chris Lattnereefa10e2007-05-28 06:56:27 +000011058 // Create the AST node. The address of a label always has type 'void*'.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011059 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11060 Context.getPointerType(Context.VoidTy));
Chris Lattnereefa10e2007-05-28 06:56:27 +000011061}
11062
John McCall31168b02011-06-15 23:02:42 +000011063/// Given the last statement in a statement-expression, check whether
11064/// the result is a producing expression (like a call to an
11065/// ns_returns_retained function) and, if so, rebuild it to hoist the
11066/// release out of the full-expression. Otherwise, return null.
11067/// Cannot fail.
Richard Trieuba63ce62011-09-09 01:45:06 +000011068static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCall31168b02011-06-15 23:02:42 +000011069 // Should always be wrapped with one of these.
Richard Trieuba63ce62011-09-09 01:45:06 +000011070 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
Craig Topperc3ec1492014-05-26 06:22:03 +000011071 if (!cleanups) return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011072
11073 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall2d637d22011-09-10 06:18:15 +000011074 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
Craig Topperc3ec1492014-05-26 06:22:03 +000011075 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011076
11077 // Splice out the cast. This shouldn't modify any interesting
11078 // features of the statement.
11079 Expr *producer = cast->getSubExpr();
11080 assert(producer->getType() == cast->getType());
11081 assert(producer->getValueKind() == cast->getValueKind());
11082 cleanups->setSubExpr(producer);
11083 return cleanups;
11084}
11085
John McCall3abee492012-04-04 01:27:53 +000011086void Sema::ActOnStartStmtExpr() {
11087 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11088}
11089
11090void Sema::ActOnStmtExprError() {
John McCalled7b2782012-04-06 18:20:53 +000011091 // Note that function is also called by TreeTransform when leaving a
11092 // StmtExpr scope without rebuilding anything.
11093
John McCall3abee492012-04-04 01:27:53 +000011094 DiscardCleanupsInEvaluationContext();
11095 PopExpressionEvaluationContext();
11096}
11097
John McCalldadc5752010-08-24 06:29:42 +000011098ExprResult
John McCallb268a282010-08-23 23:25:46 +000011099Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +000011100 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +000011101 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11102 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11103
John McCall3abee492012-04-04 01:27:53 +000011104 if (hasAnyUnrecoverableErrorsInThisFunction())
11105 DiscardCleanupsInEvaluationContext();
11106 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
11107 PopExpressionEvaluationContext();
11108
Chris Lattner366727f2007-07-24 16:58:17 +000011109 // FIXME: there are a variety of strange constraints to enforce here, for
11110 // example, it is not possible to goto into a stmt expression apparently.
11111 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +000011112
Alp Toker028ed912013-12-06 17:56:43 +000011113 // If there are sub-stmts in the compound stmt, take the type of the last one
Chris Lattner366727f2007-07-24 16:58:17 +000011114 // as the type of the stmtexpr.
11115 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +000011116 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +000011117 if (!Compound->body_empty()) {
11118 Stmt *LastStmt = Compound->body_back();
Craig Topperc3ec1492014-05-26 06:22:03 +000011119 LabelStmt *LastLabelStmt = nullptr;
Chris Lattner944d3062008-07-26 19:51:01 +000011120 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +000011121 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11122 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +000011123 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +000011124 }
John McCall31168b02011-06-15 23:02:42 +000011125
John Wiegley01296292011-04-08 18:41:53 +000011126 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +000011127 // Do function/array conversion on the last expression, but not
11128 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +000011129 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11130 if (LastExpr.isInvalid())
11131 return ExprError();
11132 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +000011133
John Wiegley01296292011-04-08 18:41:53 +000011134 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +000011135 // In ARC, if the final expression ends in a consume, splice
11136 // the consume out and bind it later. In the alternate case
11137 // (when dealing with a retainable type), the result
11138 // initialization will create a produce. In both cases the
11139 // result will be +1, and we'll need to balance that out with
11140 // a bind.
11141 if (Expr *rebuiltLastStmt
11142 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11143 LastExpr = rebuiltLastStmt;
11144 } else {
11145 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +000011146 InitializedEntity::InitializeResult(LPLoc,
11147 Ty,
11148 false),
11149 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +000011150 LastExpr);
11151 }
11152
John Wiegley01296292011-04-08 18:41:53 +000011153 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +000011154 return ExprError();
Craig Topperc3ec1492014-05-26 06:22:03 +000011155 if (LastExpr.get() != nullptr) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +000011156 if (!LastLabelStmt)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011157 Compound->setLastStmt(LastExpr.get());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +000011158 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011159 LastLabelStmt->setSubStmt(LastExpr.get());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +000011160 StmtExprMayBindToTemp = true;
11161 }
11162 }
11163 }
Chris Lattner944d3062008-07-26 19:51:01 +000011164 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000011165
Eli Friedmanba961a92009-03-23 00:24:07 +000011166 // FIXME: Check that expression type is complete/non-abstract; statement
11167 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +000011168 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
11169 if (StmtExprMayBindToTemp)
11170 return MaybeBindToTemporary(ResStmtExpr);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011171 return ResStmtExpr;
Chris Lattner366727f2007-07-24 16:58:17 +000011172}
Steve Naroff78864672007-08-01 22:05:33 +000011173
John McCalldadc5752010-08-24 06:29:42 +000011174ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +000011175 TypeSourceInfo *TInfo,
Craig Topperb5518242015-10-22 04:59:59 +000011176 ArrayRef<OffsetOfComponent> Components,
John McCall36226622010-10-12 02:09:17 +000011177 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +000011178 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000011179 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000011180 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +000011181
Chris Lattnerf17bd422007-08-30 17:45:32 +000011182 // We must have at least one component that refers to the type, and the first
11183 // one is known to be a field designator. Verify that the ArgTy represents
11184 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000011185 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +000011186 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
11187 << ArgTy << TypeRange);
11188
11189 // Type must be complete per C99 7.17p3 because a declaring a variable
11190 // with an incomplete type would be ill-formed.
11191 if (!Dependent
11192 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011193 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor882211c2010-04-28 22:16:22 +000011194 return ExprError();
11195
Chris Lattner78502cf2007-08-31 21:49:13 +000011196 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
11197 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +000011198 // FIXME: This diagnostic isn't actually visible because the location is in
11199 // a system header!
Craig Topperb5518242015-10-22 04:59:59 +000011200 if (Components.size() != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +000011201 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
Craig Topperb5518242015-10-22 04:59:59 +000011202 << SourceRange(Components[1].LocStart, Components.back().LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +000011203
11204 bool DidWarnAboutNonPOD = false;
11205 QualType CurrentType = ArgTy;
11206 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011207 SmallVector<OffsetOfNode, 4> Comps;
11208 SmallVector<Expr*, 4> Exprs;
Craig Topperb5518242015-10-22 04:59:59 +000011209 for (const OffsetOfComponent &OC : Components) {
Douglas Gregor882211c2010-04-28 22:16:22 +000011210 if (OC.isBrackets) {
11211 // Offset of an array sub-field. TODO: Should we allow vector elements?
11212 if (!CurrentType->isDependentType()) {
11213 const ArrayType *AT = Context.getAsArrayType(CurrentType);
11214 if(!AT)
11215 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
11216 << CurrentType);
11217 CurrentType = AT->getElementType();
11218 } else
11219 CurrentType = Context.DependentTy;
11220
Richard Smith9fcc5c32011-10-17 23:29:39 +000011221 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
11222 if (IdxRval.isInvalid())
11223 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011224 Expr *Idx = IdxRval.get();
Richard Smith9fcc5c32011-10-17 23:29:39 +000011225
Douglas Gregor882211c2010-04-28 22:16:22 +000011226 // The expression must be an integral expression.
11227 // FIXME: An integral constant expression?
Douglas Gregor882211c2010-04-28 22:16:22 +000011228 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
11229 !Idx->getType()->isIntegerType())
11230 return ExprError(Diag(Idx->getLocStart(),
11231 diag::err_typecheck_subscript_not_integer)
11232 << Idx->getSourceRange());
Richard Smitheda612882011-10-17 05:48:07 +000011233
Douglas Gregor882211c2010-04-28 22:16:22 +000011234 // Record this array index.
11235 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smith9fcc5c32011-10-17 23:29:39 +000011236 Exprs.push_back(Idx);
Douglas Gregor882211c2010-04-28 22:16:22 +000011237 continue;
11238 }
11239
11240 // Offset of a field.
11241 if (CurrentType->isDependentType()) {
11242 // We have the offset of a field, but we can't look into the dependent
11243 // type. Just record the identifier of the field.
11244 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
11245 CurrentType = Context.DependentTy;
11246 continue;
11247 }
11248
11249 // We need to have a complete type to look into.
11250 if (RequireCompleteType(OC.LocStart, CurrentType,
11251 diag::err_offsetof_incomplete_type))
11252 return ExprError();
11253
11254 // Look for the designated field.
11255 const RecordType *RC = CurrentType->getAs<RecordType>();
11256 if (!RC)
11257 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
11258 << CurrentType);
11259 RecordDecl *RD = RC->getDecl();
11260
11261 // C++ [lib.support.types]p5:
11262 // The macro offsetof accepts a restricted set of type arguments in this
11263 // International Standard. type shall be a POD structure or a POD union
11264 // (clause 9).
Benjamin Kramer9e7876b2012-04-28 11:14:51 +000011265 // C++11 [support.types]p4:
11266 // If type is not a standard-layout class (Clause 9), the results are
11267 // undefined.
Douglas Gregor882211c2010-04-28 22:16:22 +000011268 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011269 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
Benjamin Kramer9e7876b2012-04-28 11:14:51 +000011270 unsigned DiagID =
Richard Smith1b98ccc2014-07-19 01:39:17 +000011271 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
11272 : diag::ext_offsetof_non_pod_type;
Benjamin Kramer9e7876b2012-04-28 11:14:51 +000011273
11274 if (!IsSafe && !DidWarnAboutNonPOD &&
Craig Topperc3ec1492014-05-26 06:22:03 +000011275 DiagRuntimeBehavior(BuiltinLoc, nullptr,
Benjamin Kramer9e7876b2012-04-28 11:14:51 +000011276 PDiag(DiagID)
Craig Topperb5518242015-10-22 04:59:59 +000011277 << SourceRange(Components[0].LocStart, OC.LocEnd)
Douglas Gregor882211c2010-04-28 22:16:22 +000011278 << CurrentType))
11279 DidWarnAboutNonPOD = true;
11280 }
11281
11282 // Look for the field.
11283 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
11284 LookupQualifiedName(R, RD);
11285 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Craig Topperc3ec1492014-05-26 06:22:03 +000011286 IndirectFieldDecl *IndirectMemberDecl = nullptr;
Francois Pichet783dd6e2010-11-21 06:08:52 +000011287 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +000011288 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +000011289 MemberDecl = IndirectMemberDecl->getAnonField();
11290 }
11291
Douglas Gregor882211c2010-04-28 22:16:22 +000011292 if (!MemberDecl)
11293 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
11294 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
11295 OC.LocEnd));
11296
Douglas Gregor10982ea2010-04-28 22:36:06 +000011297 // C99 7.17p3:
11298 // (If the specified member is a bit-field, the behavior is undefined.)
11299 //
11300 // We diagnose this as an error.
Richard Smithcaf33902011-10-10 18:28:20 +000011301 if (MemberDecl->isBitField()) {
Douglas Gregor10982ea2010-04-28 22:36:06 +000011302 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
11303 << MemberDecl->getDeclName()
11304 << SourceRange(BuiltinLoc, RParenLoc);
11305 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
11306 return ExprError();
11307 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +000011308
11309 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +000011310 if (IndirectMemberDecl)
11311 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +000011312
Douglas Gregord1702062010-04-29 00:18:15 +000011313 // If the member was found in a base class, introduce OffsetOfNodes for
11314 // the base class indirections.
David Majnemerff17f832013-10-15 06:28:23 +000011315 CXXBasePaths Paths;
Eli Friedman74ef7cf2010-08-05 10:11:36 +000011316 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
David Majnemerff17f832013-10-15 06:28:23 +000011317 if (Paths.getDetectedVirtual()) {
11318 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
11319 << MemberDecl->getDeclName()
11320 << SourceRange(BuiltinLoc, RParenLoc);
11321 return ExprError();
11322 }
11323
Douglas Gregord1702062010-04-29 00:18:15 +000011324 CXXBasePath &Path = Paths.front();
11325 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
11326 B != BEnd; ++B)
11327 Comps.push_back(OffsetOfNode(B->Base));
11328 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +000011329
Francois Pichet783dd6e2010-11-21 06:08:52 +000011330 if (IndirectMemberDecl) {
Aaron Ballman29c94602014-03-07 18:36:15 +000011331 for (auto *FI : IndirectMemberDecl->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +000011332 assert(isa<FieldDecl>(FI));
Francois Pichet783dd6e2010-11-21 06:08:52 +000011333 Comps.push_back(OffsetOfNode(OC.LocStart,
Aaron Ballman13916082014-03-07 18:11:58 +000011334 cast<FieldDecl>(FI), OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +000011335 }
11336 } else
Douglas Gregor882211c2010-04-28 22:16:22 +000011337 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +000011338
Douglas Gregor882211c2010-04-28 22:16:22 +000011339 CurrentType = MemberDecl->getType().getNonReferenceType();
11340 }
11341
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011342 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
11343 Comps, Exprs, RParenLoc);
Douglas Gregor882211c2010-04-28 22:16:22 +000011344}
Mike Stump4e1f26a2009-02-19 03:04:26 +000011345
John McCalldadc5752010-08-24 06:29:42 +000011346ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +000011347 SourceLocation BuiltinLoc,
11348 SourceLocation TypeLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +000011349 ParsedType ParsedArgTy,
Craig Topperb5518242015-10-22 04:59:59 +000011350 ArrayRef<OffsetOfComponent> Components,
Richard Trieuba63ce62011-09-09 01:45:06 +000011351 SourceLocation RParenLoc) {
John McCall36226622010-10-12 02:09:17 +000011352
Douglas Gregor882211c2010-04-28 22:16:22 +000011353 TypeSourceInfo *ArgTInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +000011354 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor882211c2010-04-28 22:16:22 +000011355 if (ArgTy.isNull())
11356 return ExprError();
11357
Eli Friedman06dcfd92010-08-05 10:15:45 +000011358 if (!ArgTInfo)
11359 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
11360
Craig Topperb5518242015-10-22 04:59:59 +000011361 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +000011362}
11363
11364
John McCalldadc5752010-08-24 06:29:42 +000011365ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +000011366 Expr *CondExpr,
11367 Expr *LHSExpr, Expr *RHSExpr,
11368 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +000011369 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
11370
John McCall7decc9e2010-11-18 06:31:45 +000011371 ExprValueKind VK = VK_RValue;
11372 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000011373 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +000011374 bool ValueDependent = false;
Eli Friedman75807f22013-07-20 00:40:58 +000011375 bool CondIsTrue = false;
Douglas Gregor0df91122009-05-19 22:43:30 +000011376 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000011377 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +000011378 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000011379 } else {
11380 // The conditional expression is required to be a constant expression.
11381 llvm::APSInt condEval(32);
Douglas Gregore2b37442012-05-04 22:38:52 +000011382 ExprResult CondICE
11383 = VerifyIntegerConstantExpression(CondExpr, &condEval,
11384 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smithf4c51d92012-02-04 09:53:13 +000011385 if (CondICE.isInvalid())
11386 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011387 CondExpr = CondICE.get();
Eli Friedman75807f22013-07-20 00:40:58 +000011388 CondIsTrue = condEval.getZExtValue();
Steve Naroff9efdabc2007-08-03 21:21:27 +000011389
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000011390 // If the condition is > zero, then the AST type is the same as the LSHExpr.
Eli Friedman75807f22013-07-20 00:40:58 +000011391 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
John McCall7decc9e2010-11-18 06:31:45 +000011392
11393 resType = ActiveExpr->getType();
11394 ValueDependent = ActiveExpr->isValueDependent();
11395 VK = ActiveExpr->getValueKind();
11396 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000011397 }
11398
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011399 return new (Context)
11400 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
11401 CondIsTrue, resType->isDependentType(), ValueDependent);
Steve Naroff9efdabc2007-08-03 21:21:27 +000011402}
11403
Steve Naroffc540d662008-09-03 18:15:37 +000011404//===----------------------------------------------------------------------===//
11405// Clang Extensions.
11406//===----------------------------------------------------------------------===//
11407
11408/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuba63ce62011-09-09 01:45:06 +000011409void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +000011410 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Eli Friedman7e346a82013-07-01 20:22:57 +000011411
Eli Friedman4ef077a2013-09-12 22:36:24 +000011412 if (LangOpts.CPlusPlus) {
Eli Friedman7e346a82013-07-01 20:22:57 +000011413 Decl *ManglingContextDecl;
11414 if (MangleNumberingContext *MCtx =
11415 getCurrentMangleNumberContext(Block->getDeclContext(),
11416 ManglingContextDecl)) {
11417 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
11418 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
11419 }
11420 }
11421
Richard Trieuba63ce62011-09-09 01:45:06 +000011422 PushBlockScope(CurScope, Block);
Douglas Gregor9a28e842010-03-01 23:15:13 +000011423 CurContext->addDecl(Block);
Richard Trieuba63ce62011-09-09 01:45:06 +000011424 if (CurScope)
11425 PushDeclContext(CurScope, Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +000011426 else
11427 CurContext = Block;
John McCallf1a3c2a2011-11-11 03:19:12 +000011428
Eli Friedman34b49062012-01-26 03:00:14 +000011429 getCurBlock()->HasImplicitReturnType = true;
11430
John McCallf1a3c2a2011-11-11 03:19:12 +000011431 // Enter a new evaluation context to insulate the block from any
11432 // cleanups from the enclosing full-expression.
11433 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff1d95e5a2008-10-10 01:28:17 +000011434}
11435
Douglas Gregor7efd007c2012-06-15 16:59:29 +000011436void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
11437 Scope *CurScope) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011438 assert(ParamInfo.getIdentifier() == nullptr &&
11439 "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +000011440 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +000011441 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011442
John McCall8cb7bdf2010-06-04 23:28:52 +000011443 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +000011444 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +000011445
Douglas Gregor7efd007c2012-06-15 16:59:29 +000011446 // FIXME: We should allow unexpanded parameter packs here, but that would,
11447 // in turn, make the block expression contain unexpanded parameter packs.
11448 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
11449 // Drop the parameters.
11450 FunctionProtoType::ExtProtoInfo EPI;
11451 EPI.HasTrailingReturn = false;
11452 EPI.TypeQuals |= DeclSpec::TQ_const;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000011453 T = Context.getFunctionType(Context.DependentTy, None, EPI);
Douglas Gregor7efd007c2012-06-15 16:59:29 +000011454 Sig = Context.getTrivialTypeSourceInfo(T);
11455 }
11456
John McCall3882ace2011-01-05 12:14:39 +000011457 // GetTypeForDeclarator always produces a function type for a block
11458 // literal signature. Furthermore, it is always a FunctionProtoType
11459 // unless the function was written with a typedef.
11460 assert(T->isFunctionType() &&
11461 "GetTypeForDeclarator made a non-function block signature");
11462
11463 // Look for an explicit signature in that function type.
11464 FunctionProtoTypeLoc ExplicitSignature;
11465
11466 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +000011467 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
John McCall3882ace2011-01-05 12:14:39 +000011468
11469 // Check whether that explicit signature was synthesized by
11470 // GetTypeForDeclarator. If so, don't save that as part of the
11471 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000011472 if (ExplicitSignature.getLocalRangeBegin() ==
11473 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +000011474 // This would be much cheaper if we stored TypeLocs instead of
11475 // TypeSourceInfos.
Alp Toker42a16a62014-01-25 23:51:36 +000011476 TypeLoc Result = ExplicitSignature.getReturnLoc();
John McCall3882ace2011-01-05 12:14:39 +000011477 unsigned Size = Result.getFullDataSize();
11478 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
11479 Sig->getTypeLoc().initializeFullCopy(Result, Size);
11480
11481 ExplicitSignature = FunctionProtoTypeLoc();
11482 }
John McCalla3ccba02010-06-04 11:21:44 +000011483 }
Mike Stump11289f42009-09-09 15:08:12 +000011484
John McCall3882ace2011-01-05 12:14:39 +000011485 CurBlock->TheDecl->setSignatureAsWritten(Sig);
11486 CurBlock->FunctionType = T;
11487
11488 const FunctionType *Fn = T->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +000011489 QualType RetTy = Fn->getReturnType();
John McCall3882ace2011-01-05 12:14:39 +000011490 bool isVariadic =
11491 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
11492
John McCall8e346702010-06-04 19:02:56 +000011493 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +000011494
John McCalla3ccba02010-06-04 11:21:44 +000011495 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +000011496 // return type. TODO: what should we do with declarators like:
11497 // ^ * { ... }
11498 // If the answer is "apply template argument deduction"....
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +000011499 if (RetTy != Context.DependentTy) {
John McCalla3ccba02010-06-04 11:21:44 +000011500 CurBlock->ReturnType = RetTy;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +000011501 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman34b49062012-01-26 03:00:14 +000011502 CurBlock->HasImplicitReturnType = false;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +000011503 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000011504
John McCalla3ccba02010-06-04 11:21:44 +000011505 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011506 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +000011507 if (ExplicitSignature) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011508 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
11509 ParmVarDecl *Param = ExplicitSignature.getParam(I);
Craig Topperc3ec1492014-05-26 06:22:03 +000011510 if (Param->getIdentifier() == nullptr &&
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +000011511 !Param->isImplicit() &&
11512 !Param->isInvalidDecl() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000011513 !getLangOpts().CPlusPlus)
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +000011514 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +000011515 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +000011516 }
John McCalla3ccba02010-06-04 11:21:44 +000011517
11518 // Fake up parameter variables if we have a typedef, like
11519 // ^ fntype { ... }
11520 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +000011521 for (const auto &I : Fn->param_types()) {
11522 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
11523 CurBlock->TheDecl, ParamInfo.getLocStart(), I);
John McCall8e346702010-06-04 19:02:56 +000011524 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +000011525 }
Steve Naroffc540d662008-09-03 18:15:37 +000011526 }
John McCalla3ccba02010-06-04 11:21:44 +000011527
John McCall8e346702010-06-04 19:02:56 +000011528 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +000011529 if (!Params.empty()) {
David Blaikie9c70e042011-09-21 18:16:56 +000011530 CurBlock->TheDecl->setParams(Params);
Douglas Gregorb524d902010-11-01 18:37:59 +000011531 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
11532 CurBlock->TheDecl->param_end(),
11533 /*CheckParameterNames=*/false);
11534 }
11535
John McCalla3ccba02010-06-04 11:21:44 +000011536 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +000011537 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +000011538
Eli Friedman7e346a82013-07-01 20:22:57 +000011539 // Put the parameter variables in scope.
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +000011540 for (auto AI : CurBlock->TheDecl->params()) {
11541 AI->setOwningFunction(CurBlock->TheDecl);
John McCallf7b2fb52010-01-22 00:28:27 +000011542
Steve Naroff1d95e5a2008-10-10 01:28:17 +000011543 // If this has an identifier, add it to the scope stack.
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +000011544 if (AI->getIdentifier()) {
11545 CheckShadow(CurBlock->TheScope, AI);
John McCalldf8b37c2010-03-22 09:20:08 +000011546
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +000011547 PushOnScopeChains(AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +000011548 }
John McCallf7b2fb52010-01-22 00:28:27 +000011549 }
Steve Naroffc540d662008-09-03 18:15:37 +000011550}
11551
11552/// ActOnBlockError - If there is an error parsing a block, this callback
11553/// is invoked to pop the information about the block from the action impl.
11554void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCallf1a3c2a2011-11-11 03:19:12 +000011555 // Leave the expression-evaluation context.
11556 DiscardCleanupsInEvaluationContext();
11557 PopExpressionEvaluationContext();
11558
Steve Naroffc540d662008-09-03 18:15:37 +000011559 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +000011560 PopDeclContext();
Eli Friedman71c80552012-01-05 03:35:19 +000011561 PopFunctionScopeInfo();
Steve Naroffc540d662008-09-03 18:15:37 +000011562}
11563
11564/// ActOnBlockStmtExpr - This is called when the body of a block statement
11565/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +000011566ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +000011567 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +000011568 // If blocks are disabled, emit an error.
11569 if (!LangOpts.Blocks)
11570 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +000011571
John McCallf1a3c2a2011-11-11 03:19:12 +000011572 // Leave the expression-evaluation context.
John McCall85110b42012-03-08 22:00:17 +000011573 if (hasAnyUnrecoverableErrorsInThisFunction())
11574 DiscardCleanupsInEvaluationContext();
John McCallf1a3c2a2011-11-11 03:19:12 +000011575 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
11576 PopExpressionEvaluationContext();
11577
Douglas Gregor9a28e842010-03-01 23:15:13 +000011578 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Jordan Rosed39e5f12012-07-02 21:19:23 +000011579
11580 if (BSI->HasImplicitReturnType)
11581 deduceClosureReturnType(*BSI);
11582
Steve Naroff1d95e5a2008-10-10 01:28:17 +000011583 PopDeclContext();
11584
Steve Naroffc540d662008-09-03 18:15:37 +000011585 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +000011586 if (!BSI->ReturnType.isNull())
11587 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +000011588
Aaron Ballman9ead1242013-12-19 02:39:40 +000011589 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +000011590 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +000011591
John McCallc63de662011-02-02 13:00:07 +000011592 // Set the captured variables on the block.
Eli Friedman20139d32012-01-11 02:36:31 +000011593 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
11594 SmallVector<BlockDecl::Capture, 4> Captures;
11595 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
11596 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
11597 if (Cap.isThisCapture())
11598 continue;
Eli Friedman24af8502012-02-03 22:47:37 +000011599 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Richard Smithba71c082013-05-16 06:20:58 +000011600 Cap.isNested(), Cap.getInitExpr());
Eli Friedman20139d32012-01-11 02:36:31 +000011601 Captures.push_back(NewCap);
11602 }
Benjamin Kramerb40e4af2015-08-05 09:40:35 +000011603 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
John McCallc63de662011-02-02 13:00:07 +000011604
John McCall8e346702010-06-04 19:02:56 +000011605 // If the user wrote a function type in some form, try to use that.
11606 if (!BSI->FunctionType.isNull()) {
11607 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
11608
11609 FunctionType::ExtInfo Ext = FTy->getExtInfo();
11610 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
11611
11612 // Turn protoless block types into nullary block types.
11613 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +000011614 FunctionProtoType::ExtProtoInfo EPI;
11615 EPI.ExtInfo = Ext;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000011616 BlockTy = Context.getFunctionType(RetTy, None, EPI);
John McCall8e346702010-06-04 19:02:56 +000011617
11618 // Otherwise, if we don't need to change anything about the function type,
11619 // preserve its sugar structure.
Alp Toker314cc812014-01-25 16:55:45 +000011620 } else if (FTy->getReturnType() == RetTy &&
John McCall8e346702010-06-04 19:02:56 +000011621 (!NoReturn || FTy->getNoReturnAttr())) {
11622 BlockTy = BSI->FunctionType;
11623
11624 // Otherwise, make the minimal modifications to the function type.
11625 } else {
11626 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +000011627 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11628 EPI.TypeQuals = 0; // FIXME: silently?
11629 EPI.ExtInfo = Ext;
Alp Toker9cacbab2014-01-20 20:26:09 +000011630 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
John McCall8e346702010-06-04 19:02:56 +000011631 }
11632
11633 // If we don't have a function type, just build one from nothing.
11634 } else {
John McCalldb40c7f2010-12-14 08:05:40 +000011635 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +000011636 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000011637 BlockTy = Context.getFunctionType(RetTy, None, EPI);
John McCall8e346702010-06-04 19:02:56 +000011638 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000011639
John McCall8e346702010-06-04 19:02:56 +000011640 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
11641 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +000011642 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +000011643
Chris Lattner45542ea2009-04-19 05:28:12 +000011644 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +000011645 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor5d944db2012-08-17 05:12:08 +000011646 !PP.isCodeCompletionEnabled())
John McCallb268a282010-08-23 23:25:46 +000011647 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +000011648
Chris Lattner60f84492011-02-17 23:58:47 +000011649 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011650
Jordan Rosed39e5f12012-07-02 21:19:23 +000011651 // Try to apply the named return value optimization. We have to check again
11652 // if we can do this, though, because blocks keep return statements around
11653 // to deduce an implicit return type.
11654 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
11655 !BSI->TheDecl->isDependentContext())
Argyrios Kyrtzidisea75aad2014-04-26 18:29:13 +000011656 computeNRVO(Body, BSI);
Douglas Gregor49695f02011-09-06 20:46:03 +000011657
Benjamin Kramera4fb8362011-07-12 14:11:05 +000011658 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
David Blaikie43472b32013-09-03 21:40:15 +000011659 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedman71c80552012-01-05 03:35:19 +000011660 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramera4fb8362011-07-12 14:11:05 +000011661
John McCall28fc7092011-11-10 05:35:25 +000011662 // If the block isn't obviously global, i.e. it captures anything at
John McCalld2393872012-04-13 01:08:17 +000011663 // all, then we need to do a few things in the surrounding context:
John McCall28fc7092011-11-10 05:35:25 +000011664 if (Result->getBlockDecl()->hasCaptures()) {
John McCalld2393872012-04-13 01:08:17 +000011665 // First, this expression has a new cleanup object.
John McCall28fc7092011-11-10 05:35:25 +000011666 ExprCleanupObjects.push_back(Result->getBlockDecl());
11667 ExprNeedsCleanups = true;
John McCalld2393872012-04-13 01:08:17 +000011668
11669 // It also gets a branch-protected scope if any of the captured
11670 // variables needs destruction.
Aaron Ballman9371dd22014-03-14 18:34:04 +000011671 for (const auto &CI : Result->getBlockDecl()->captures()) {
11672 const VarDecl *var = CI.getVariable();
John McCalld2393872012-04-13 01:08:17 +000011673 if (var->getType().isDestructedType() != QualType::DK_none) {
11674 getCurFunction()->setHasBranchProtectedScope();
11675 break;
11676 }
11677 }
John McCall28fc7092011-11-10 05:35:25 +000011678 }
Fariborz Jahanian197c68c2012-03-06 18:41:35 +000011679
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011680 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +000011681}
11682
John McCalldadc5752010-08-24 06:29:42 +000011683ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +000011684 Expr *E, ParsedType Ty,
Sebastian Redl6d4256c2009-03-15 17:47:39 +000011685 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +000011686 TypeSourceInfo *TInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +000011687 GetTypeFromParser(Ty, &TInfo);
11688 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +000011689}
11690
John McCalldadc5752010-08-24 06:29:42 +000011691ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +000011692 Expr *E, TypeSourceInfo *TInfo,
11693 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +000011694 Expr *OrigExpr = E;
Charles Davisc7d5c942015-09-17 20:55:33 +000011695 bool IsMS = false;
11696
11697 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
11698 // as Microsoft ABI on an actual Microsoft platform, where
11699 // __builtin_ms_va_list and __builtin_va_list are the same.)
11700 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
11701 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
11702 QualType MSVaListType = Context.getBuiltinMSVaListType();
11703 if (Context.hasSameType(MSVaListType, E->getType())) {
11704 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
11705 return ExprError();
11706 IsMS = true;
11707 }
11708 }
Mike Stump11289f42009-09-09 15:08:12 +000011709
Eli Friedman121ba0c2008-08-09 23:32:40 +000011710 // Get the va_list type
11711 QualType VaListType = Context.getBuiltinVaListType();
Charles Davisc7d5c942015-09-17 20:55:33 +000011712 if (!IsMS) {
11713 if (VaListType->isArrayType()) {
11714 // Deal with implicit array decay; for example, on x86-64,
11715 // va_list is an array, but it's supposed to decay to
11716 // a pointer for va_arg.
11717 VaListType = Context.getArrayDecayedType(VaListType);
11718 // Make sure the input expression also decays appropriately.
11719 ExprResult Result = UsualUnaryConversions(E);
11720 if (Result.isInvalid())
11721 return ExprError();
11722 E = Result.get();
11723 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
11724 // If va_list is a record type and we are compiling in C++ mode,
11725 // check the argument using reference binding.
11726 InitializedEntity Entity = InitializedEntity::InitializeParameter(
11727 Context, Context.getLValueReferenceType(VaListType), false);
11728 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
11729 if (Init.isInvalid())
11730 return ExprError();
11731 E = Init.getAs<Expr>();
11732 } else {
11733 // Otherwise, the va_list argument must be an l-value because
11734 // it is modified by va_arg.
11735 if (!E->isTypeDependent() &&
11736 CheckForModifiableLvalue(E, BuiltinLoc, *this))
11737 return ExprError();
11738 }
Eli Friedmane2cad652009-05-16 12:46:54 +000011739 }
Eli Friedman121ba0c2008-08-09 23:32:40 +000011740
Charles Davisc7d5c942015-09-17 20:55:33 +000011741 if (!IsMS && !E->isTypeDependent() &&
11742 !Context.hasSameType(VaListType, E->getType()))
Sebastian Redl6d4256c2009-03-15 17:47:39 +000011743 return ExprError(Diag(E->getLocStart(),
11744 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +000011745 << OrigExpr->getType() << E->getSourceRange());
Mike Stump4e1f26a2009-02-19 03:04:26 +000011746
David Majnemerc75d1a12011-06-14 05:17:32 +000011747 if (!TInfo->getType()->isDependentType()) {
11748 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011749 diag::err_second_parameter_to_va_arg_incomplete,
11750 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +000011751 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +000011752
David Majnemerc75d1a12011-06-14 05:17:32 +000011753 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregorae298422012-05-04 17:09:59 +000011754 TInfo->getType(),
11755 diag::err_second_parameter_to_va_arg_abstract,
11756 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +000011757 return ExprError();
11758
Douglas Gregor7e1eb932011-07-30 06:45:27 +000011759 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +000011760 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +000011761 TInfo->getType()->isObjCLifetimeType()
11762 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
11763 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +000011764 << TInfo->getType()
11765 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +000011766 }
Eli Friedman6290ae42011-07-11 21:45:59 +000011767
11768 // Check for va_arg where arguments of the given type will be promoted
11769 // (i.e. this va_arg is guaranteed to have undefined behavior).
11770 QualType PromoteType;
11771 if (TInfo->getType()->isPromotableIntegerType()) {
11772 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
11773 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
11774 PromoteType = QualType();
11775 }
11776 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
11777 PromoteType = Context.DoubleTy;
11778 if (!PromoteType.isNull())
Ted Kremeneka0461692013-01-08 01:50:40 +000011779 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
11780 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
11781 << TInfo->getType()
11782 << PromoteType
11783 << TInfo->getTypeLoc().getSourceRange());
David Majnemerc75d1a12011-06-14 05:17:32 +000011784 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000011785
Abramo Bagnara27db2392010-08-10 10:06:15 +000011786 QualType T = TInfo->getType().getNonLValueExprType(Context);
Charles Davisc7d5c942015-09-17 20:55:33 +000011787 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
Anders Carlsson7e13ab82007-10-15 20:28:48 +000011788}
11789
John McCalldadc5752010-08-24 06:29:42 +000011790ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +000011791 // The type of __null will be int or long, depending on the size of
11792 // pointers on the target.
11793 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +000011794 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
11795 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +000011796 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +000011797 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +000011798 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +000011799 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +000011800 Ty = Context.LongLongTy;
11801 else {
David Blaikie83d382b2011-09-23 05:06:16 +000011802 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +000011803 }
Douglas Gregor3be4b122008-11-29 04:51:27 +000011804
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011805 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregor3be4b122008-11-29 04:51:27 +000011806}
11807
Fariborz Jahanian283bf892013-12-18 21:04:43 +000011808bool
11809Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) {
Fariborz Jahanianbd714e92013-12-17 19:33:43 +000011810 if (!getLangOpts().ObjC1)
Fariborz Jahanian283bf892013-12-18 21:04:43 +000011811 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011812
Anders Carlssonace5d072009-11-10 04:46:30 +000011813 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
11814 if (!PT)
Fariborz Jahanian283bf892013-12-18 21:04:43 +000011815 return false;
Anders Carlssonace5d072009-11-10 04:46:30 +000011816
Anders Carlssonace5d072009-11-10 04:46:30 +000011817 if (!PT->isObjCIdType()) {
11818 // Check if the destination is the 'NSString' interface.
11819 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
11820 if (!ID || !ID->getIdentifier()->isStr("NSString"))
Fariborz Jahanian283bf892013-12-18 21:04:43 +000011821 return false;
Anders Carlssonace5d072009-11-10 04:46:30 +000011822 }
Fariborz Jahanian283bf892013-12-18 21:04:43 +000011823
John McCallfe96e0b2011-11-06 09:01:30 +000011824 // Ignore any parens, implicit casts (should only be
11825 // array-to-pointer decays), and not-so-opaque values. The last is
11826 // important for making this trigger for property assignments.
Fariborz Jahanian283bf892013-12-18 21:04:43 +000011827 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
John McCallfe96e0b2011-11-06 09:01:30 +000011828 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
11829 if (OV->getSourceExpr())
11830 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
11831
11832 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregorfb65e592011-07-27 05:40:30 +000011833 if (!SL || !SL->isAscii())
Fariborz Jahanian283bf892013-12-18 21:04:43 +000011834 return false;
11835 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
11836 << FixItHint::CreateInsertion(SL->getLocStart(), "@");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011837 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
Fariborz Jahanian283bf892013-12-18 21:04:43 +000011838 return true;
Anders Carlssonace5d072009-11-10 04:46:30 +000011839}
11840
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011841static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
11842 const Expr *SrcExpr) {
11843 if (!DstType->isFunctionPointerType() ||
11844 !SrcExpr->getType()->isFunctionType())
11845 return false;
11846
11847 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
11848 if (!DRE)
11849 return false;
11850
11851 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11852 if (!FD)
11853 return false;
11854
11855 return !S.checkAddressOfFunctionIsAvailable(FD,
11856 /*Complain=*/true,
11857 SrcExpr->getLocStart());
11858}
11859
Chris Lattner9bad62c2008-01-04 18:04:52 +000011860bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
11861 SourceLocation Loc,
11862 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +000011863 Expr *SrcExpr, AssignmentAction Action,
11864 bool *Complained) {
11865 if (Complained)
11866 *Complained = false;
11867
Chris Lattner9bad62c2008-01-04 18:04:52 +000011868 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +000011869 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +000011870 bool isInvalid = false;
Eli Friedman381f4312012-02-29 20:59:56 +000011871 unsigned DiagKind = 0;
Douglas Gregora771f462010-03-31 17:46:05 +000011872 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +000011873 ConversionFixItGenerator ConvHints;
11874 bool MayHaveConvFixit = false;
Richard Trieucaff2472011-11-23 22:32:32 +000011875 bool MayHaveFunctionDiff = false;
Fariborz Jahaniand3296742014-06-19 23:05:46 +000011876 const ObjCInterfaceDecl *IFace = nullptr;
11877 const ObjCProtocolDecl *PDecl = nullptr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011878
Chris Lattner9bad62c2008-01-04 18:04:52 +000011879 switch (ConvTy) {
Fariborz Jahanian268fec12012-07-17 18:00:08 +000011880 case Compatible:
Joerg Sonnenberger05bd2da2013-11-19 13:38:38 +000011881 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
11882 return false;
Fariborz Jahanian268fec12012-07-17 18:00:08 +000011883
Chris Lattner940cfeb2008-01-04 18:22:42 +000011884 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +000011885 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +000011886 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11887 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +000011888 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +000011889 case IntToPointer:
11890 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +000011891 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11892 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +000011893 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +000011894 case IncompatiblePointer:
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +000011895 DiagKind =
11896 (Action == AA_Passing_CFAudited ?
11897 diag::err_arc_typecheck_convert_incompatible_pointer :
11898 diag::ext_typecheck_convert_incompatible_pointer);
Douglas Gregor33823722011-06-11 01:09:30 +000011899 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
11900 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +000011901 if (Hint.isNull() && !CheckInferredResultType) {
11902 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11903 }
Fariborz Jahanian3beec202013-04-30 00:30:48 +000011904 else if (CheckInferredResultType) {
11905 SrcType = SrcType.getUnqualifiedType();
11906 DstType = DstType.getUnqualifiedType();
11907 }
Anna Zaks3b402712011-07-28 19:51:27 +000011908 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +000011909 break;
Eli Friedman80160bd2009-03-22 23:59:44 +000011910 case IncompatiblePointerSign:
11911 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
11912 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +000011913 case FunctionVoidPointer:
11914 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
11915 break;
John McCall4fff8f62011-02-01 00:10:29 +000011916 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +000011917 // Perform array-to-pointer decay if necessary.
11918 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
11919
John McCall4fff8f62011-02-01 00:10:29 +000011920 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
11921 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
11922 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
11923 DiagKind = diag::err_typecheck_incompatible_address_space;
11924 break;
John McCall31168b02011-06-15 23:02:42 +000011925
11926
11927 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +000011928 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +000011929 break;
John McCall4fff8f62011-02-01 00:10:29 +000011930 }
11931
11932 llvm_unreachable("unknown error case for discarding qualifiers!");
11933 // fallthrough
11934 }
Chris Lattner9bad62c2008-01-04 18:04:52 +000011935 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +000011936 // If the qualifiers lost were because we were applying the
11937 // (deprecated) C++ conversion from a string literal to a char*
11938 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
11939 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +000011940 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +000011941 // bit of refactoring (so that the second argument is an
11942 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +000011943 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +000011944 // C++ semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011945 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +000011946 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
11947 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +000011948 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
11949 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +000011950 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +000011951 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +000011952 break;
Steve Naroff081c7422008-09-04 15:10:53 +000011953 case IntToBlockPointer:
11954 DiagKind = diag::err_int_to_block_pointer;
11955 break;
11956 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +000011957 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +000011958 break;
Fariborz Jahaniand3296742014-06-19 23:05:46 +000011959 case IncompatibleObjCQualifiedId: {
11960 if (SrcType->isObjCQualifiedIdType()) {
11961 const ObjCObjectPointerType *srcOPT =
11962 SrcType->getAs<ObjCObjectPointerType>();
11963 for (auto *srcProto : srcOPT->quals()) {
11964 PDecl = srcProto;
11965 break;
11966 }
11967 if (const ObjCInterfaceType *IFaceT =
11968 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
11969 IFace = IFaceT->getDecl();
11970 }
11971 else if (DstType->isObjCQualifiedIdType()) {
11972 const ObjCObjectPointerType *dstOPT =
11973 DstType->getAs<ObjCObjectPointerType>();
11974 for (auto *dstProto : dstOPT->quals()) {
11975 PDecl = dstProto;
11976 break;
11977 }
11978 if (const ObjCInterfaceType *IFaceT =
11979 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
11980 IFace = IFaceT->getDecl();
11981 }
Steve Naroff8afa9892008-10-14 22:18:38 +000011982 DiagKind = diag::warn_incompatible_qualified_id;
11983 break;
Fariborz Jahaniand3296742014-06-19 23:05:46 +000011984 }
Anders Carlssondb5a9b62009-01-30 23:17:46 +000011985 case IncompatibleVectors:
11986 DiagKind = diag::warn_incompatible_vectors;
11987 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +000011988 case IncompatibleObjCWeakRef:
11989 DiagKind = diag::err_arc_weak_unavailable_assign;
11990 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +000011991 case Incompatible:
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011992 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
11993 if (Complained)
11994 *Complained = true;
11995 return true;
11996 }
11997
Chris Lattner9bad62c2008-01-04 18:04:52 +000011998 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +000011999 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12000 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +000012001 isInvalid = true;
Richard Trieucaff2472011-11-23 22:32:32 +000012002 MayHaveFunctionDiff = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +000012003 break;
12004 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000012005
Douglas Gregorc68e1402010-04-09 00:35:39 +000012006 QualType FirstType, SecondType;
12007 switch (Action) {
12008 case AA_Assigning:
12009 case AA_Initializing:
12010 // The destination type comes first.
12011 FirstType = DstType;
12012 SecondType = SrcType;
12013 break;
Alexis Huntc46382e2010-04-28 23:02:27 +000012014
Douglas Gregorc68e1402010-04-09 00:35:39 +000012015 case AA_Returning:
12016 case AA_Passing:
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +000012017 case AA_Passing_CFAudited:
Douglas Gregorc68e1402010-04-09 00:35:39 +000012018 case AA_Converting:
12019 case AA_Sending:
12020 case AA_Casting:
12021 // The source type comes first.
12022 FirstType = SrcType;
12023 SecondType = DstType;
12024 break;
12025 }
Alexis Huntc46382e2010-04-28 23:02:27 +000012026
Anna Zaks3b402712011-07-28 19:51:27 +000012027 PartialDiagnostic FDiag = PDiag(DiagKind);
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +000012028 if (Action == AA_Passing_CFAudited)
Fariborz Jahanian68e18672014-09-10 18:23:34 +000012029 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +000012030 else
12031 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
Anna Zaks3b402712011-07-28 19:51:27 +000012032
12033 // If we can fix the conversion, suggest the FixIts.
12034 assert(ConvHints.isNull() || Hint.isNull());
12035 if (!ConvHints.isNull()) {
Benjamin Kramer490afa62012-01-14 21:05:10 +000012036 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
12037 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks3b402712011-07-28 19:51:27 +000012038 FDiag << *HI;
12039 } else {
12040 FDiag << Hint;
12041 }
12042 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12043
Richard Trieucaff2472011-11-23 22:32:32 +000012044 if (MayHaveFunctionDiff)
12045 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12046
Anna Zaks3b402712011-07-28 19:51:27 +000012047 Diag(Loc, FDiag);
Fariborz Jahaniand3296742014-06-19 23:05:46 +000012048 if (DiagKind == diag::warn_incompatible_qualified_id &&
12049 PDecl && IFace && !IFace->hasDefinition())
12050 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
12051 << IFace->getName() << PDecl->getName();
12052
Richard Trieucaff2472011-11-23 22:32:32 +000012053 if (SecondType == Context.OverloadTy)
12054 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
George Burgess IV5f21c712015-10-12 19:57:04 +000012055 FirstType, /*TakingAddress=*/true);
Richard Trieucaff2472011-11-23 22:32:32 +000012056
Douglas Gregor33823722011-06-11 01:09:30 +000012057 if (CheckInferredResultType)
12058 EmitRelatedResultTypeNote(SrcExpr);
John McCall5ec7e7d2013-03-19 07:04:25 +000012059
12060 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12061 EmitRelatedResultTypeNoteForReturn(DstType);
Douglas Gregor33823722011-06-11 01:09:30 +000012062
Douglas Gregor4f4946a2010-04-22 00:20:18 +000012063 if (Complained)
12064 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +000012065 return isInvalid;
12066}
Anders Carlssone54e8a12008-11-30 19:50:32 +000012067
Richard Smithf4c51d92012-02-04 09:53:13 +000012068ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12069 llvm::APSInt *Result) {
Douglas Gregore2b37442012-05-04 22:38:52 +000012070 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12071 public:
Craig Toppere14c0f82014-03-12 04:55:44 +000012072 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +000012073 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12074 }
12075 } Diagnoser;
12076
12077 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12078}
12079
12080ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12081 llvm::APSInt *Result,
12082 unsigned DiagID,
12083 bool AllowFold) {
12084 class IDDiagnoser : public VerifyICEDiagnoser {
12085 unsigned DiagID;
12086
12087 public:
12088 IDDiagnoser(unsigned DiagID)
12089 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12090
Craig Toppere14c0f82014-03-12 04:55:44 +000012091 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +000012092 S.Diag(Loc, DiagID) << SR;
12093 }
12094 } Diagnoser(DiagID);
12095
12096 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12097}
12098
12099void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12100 SourceRange SR) {
12101 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smithf4c51d92012-02-04 09:53:13 +000012102}
12103
Benjamin Kramer33adaae2012-04-18 14:22:41 +000012104ExprResult
12105Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregore2b37442012-05-04 22:38:52 +000012106 VerifyICEDiagnoser &Diagnoser,
12107 bool AllowFold) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012108 SourceLocation DiagLoc = E->getLocStart();
Richard Smithf4c51d92012-02-04 09:53:13 +000012109
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012110 if (getLangOpts().CPlusPlus11) {
Richard Smithf4c51d92012-02-04 09:53:13 +000012111 // C++11 [expr.const]p5:
12112 // If an expression of literal class type is used in a context where an
12113 // integral constant expression is required, then that class type shall
12114 // have a single non-explicit conversion function to an integral or
12115 // unscoped enumeration type
12116 ExprResult Converted;
Richard Smithccc11812013-05-21 19:05:48 +000012117 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12118 public:
12119 CXX11ConvertDiagnoser(bool Silent)
12120 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12121 Silent, true) {}
Douglas Gregore2b37442012-05-04 22:38:52 +000012122
Craig Toppere14c0f82014-03-12 04:55:44 +000012123 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12124 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +000012125 return S.Diag(Loc, diag::err_ice_not_integral) << T;
12126 }
12127
Craig Toppere14c0f82014-03-12 04:55:44 +000012128 SemaDiagnosticBuilder diagnoseIncomplete(
12129 Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +000012130 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12131 }
12132
Craig Toppere14c0f82014-03-12 04:55:44 +000012133 SemaDiagnosticBuilder diagnoseExplicitConv(
12134 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +000012135 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12136 }
12137
Craig Toppere14c0f82014-03-12 04:55:44 +000012138 SemaDiagnosticBuilder noteExplicitConv(
12139 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +000012140 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12141 << ConvTy->isEnumeralType() << ConvTy;
12142 }
12143
Craig Toppere14c0f82014-03-12 04:55:44 +000012144 SemaDiagnosticBuilder diagnoseAmbiguous(
12145 Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +000012146 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
12147 }
12148
Craig Toppere14c0f82014-03-12 04:55:44 +000012149 SemaDiagnosticBuilder noteAmbiguous(
12150 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +000012151 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12152 << ConvTy->isEnumeralType() << ConvTy;
12153 }
12154
Craig Toppere14c0f82014-03-12 04:55:44 +000012155 SemaDiagnosticBuilder diagnoseConversion(
12156 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +000012157 llvm_unreachable("conversion functions are permitted");
12158 }
12159 } ConvertDiagnoser(Diagnoser.Suppress);
12160
12161 Converted = PerformContextualImplicitConversion(DiagLoc, E,
12162 ConvertDiagnoser);
Richard Smithf4c51d92012-02-04 09:53:13 +000012163 if (Converted.isInvalid())
12164 return Converted;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012165 E = Converted.get();
Richard Smithf4c51d92012-02-04 09:53:13 +000012166 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
12167 return ExprError();
12168 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12169 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregore2b37442012-05-04 22:38:52 +000012170 if (!Diagnoser.Suppress)
12171 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithf4c51d92012-02-04 09:53:13 +000012172 return ExprError();
12173 }
12174
Richard Smith902ca212011-12-14 23:32:26 +000012175 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
12176 // in the non-ICE case.
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012177 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
Richard Smithf4c51d92012-02-04 09:53:13 +000012178 if (Result)
12179 *Result = E->EvaluateKnownConstInt(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012180 return E;
Eli Friedmanbb967cc2009-04-25 22:26:58 +000012181 }
12182
Anders Carlssone54e8a12008-11-30 19:50:32 +000012183 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012184 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith92b1ce02011-12-12 09:28:41 +000012185 EvalResult.Diag = &Notes;
Anders Carlssone54e8a12008-11-30 19:50:32 +000012186
Richard Smith902ca212011-12-14 23:32:26 +000012187 // Try to evaluate the expression, and produce diagnostics explaining why it's
12188 // not a constant expression as a side-effect.
12189 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
12190 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
12191
12192 // In C++11, we can rely on diagnostics being produced for any expression
12193 // which is not a constant expression. If no diagnostics were produced, then
12194 // this is a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012195 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
Richard Smith902ca212011-12-14 23:32:26 +000012196 if (Result)
12197 *Result = EvalResult.Val.getInt();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012198 return E;
Richard Smithf4c51d92012-02-04 09:53:13 +000012199 }
12200
12201 // If our only note is the usual "invalid subexpression" note, just point
12202 // the caret at its location rather than producing an essentially
12203 // redundant note.
12204 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12205 diag::note_invalid_subexpr_in_const_expr) {
12206 DiagLoc = Notes[0].first;
12207 Notes.clear();
Richard Smith902ca212011-12-14 23:32:26 +000012208 }
12209
12210 if (!Folded || !AllowFold) {
Douglas Gregore2b37442012-05-04 22:38:52 +000012211 if (!Diagnoser.Suppress) {
12212 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith92b1ce02011-12-12 09:28:41 +000012213 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12214 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone54e8a12008-11-30 19:50:32 +000012215 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000012216
Richard Smithf4c51d92012-02-04 09:53:13 +000012217 return ExprError();
Anders Carlssone54e8a12008-11-30 19:50:32 +000012218 }
12219
Douglas Gregore2b37442012-05-04 22:38:52 +000012220 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith2ec40612012-01-15 03:51:30 +000012221 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12222 Diag(Notes[I].first, Notes[I].second);
Mike Stump4e1f26a2009-02-19 03:04:26 +000012223
Anders Carlssone54e8a12008-11-30 19:50:32 +000012224 if (Result)
12225 *Result = EvalResult.Val.getInt();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012226 return E;
Anders Carlssone54e8a12008-11-30 19:50:32 +000012227}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000012228
Eli Friedman456f0182012-01-20 01:26:23 +000012229namespace {
12230 // Handle the case where we conclude a expression which we speculatively
12231 // considered to be unevaluated is actually evaluated.
12232 class TransformToPE : public TreeTransform<TransformToPE> {
12233 typedef TreeTransform<TransformToPE> BaseTransform;
12234
12235 public:
12236 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
12237
12238 // Make sure we redo semantic analysis
12239 bool AlwaysRebuild() { return true; }
12240
Eli Friedman5f0ca242012-02-06 23:29:57 +000012241 // Make sure we handle LabelStmts correctly.
12242 // FIXME: This does the right thing, but maybe we need a more general
12243 // fix to TreeTransform?
12244 StmtResult TransformLabelStmt(LabelStmt *S) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012245 S->getDecl()->setStmt(nullptr);
Eli Friedman5f0ca242012-02-06 23:29:57 +000012246 return BaseTransform::TransformLabelStmt(S);
12247 }
12248
Eli Friedman456f0182012-01-20 01:26:23 +000012249 // We need to special-case DeclRefExprs referring to FieldDecls which
12250 // are not part of a member pointer formation; normal TreeTransforming
12251 // doesn't catch this case because of the way we represent them in the AST.
12252 // FIXME: This is a bit ugly; is it really the best way to handle this
12253 // case?
12254 //
12255 // Error on DeclRefExprs referring to FieldDecls.
12256 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
12257 if (isa<FieldDecl>(E->getDecl()) &&
David Blaikie131fcb42012-08-06 22:47:24 +000012258 !SemaRef.isUnevaluatedContext())
Eli Friedman456f0182012-01-20 01:26:23 +000012259 return SemaRef.Diag(E->getLocation(),
12260 diag::err_invalid_non_static_member_use)
12261 << E->getDecl() << E->getSourceRange();
12262
12263 return BaseTransform::TransformDeclRefExpr(E);
12264 }
12265
12266 // Exception: filter out member pointer formation
12267 ExprResult TransformUnaryOperator(UnaryOperator *E) {
12268 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
12269 return E;
12270
12271 return BaseTransform::TransformUnaryOperator(E);
12272 }
12273
Douglas Gregor89625492012-02-09 08:14:43 +000012274 ExprResult TransformLambdaExpr(LambdaExpr *E) {
12275 // Lambdas never need to be transformed.
12276 return E;
12277 }
Eli Friedman456f0182012-01-20 01:26:23 +000012278 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000012279}
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000012280
Benjamin Kramerd81108f2012-11-14 15:08:31 +000012281ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
John McCallf413f5e2013-05-03 00:10:13 +000012282 assert(isUnevaluatedContext() &&
Eli Friedmane4f22df2012-02-29 04:03:55 +000012283 "Should only transform unevaluated expressions");
Eli Friedman456f0182012-01-20 01:26:23 +000012284 ExprEvalContexts.back().Context =
12285 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
John McCallf413f5e2013-05-03 00:10:13 +000012286 if (isUnevaluatedContext())
Eli Friedman456f0182012-01-20 01:26:23 +000012287 return E;
12288 return TransformToPE(*this).TransformExpr(E);
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000012289}
12290
Douglas Gregorff790f12009-11-26 00:44:06 +000012291void
Douglas Gregor7fcbd902012-02-21 00:37:24 +000012292Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smithfd555f62012-02-22 02:04:18 +000012293 Decl *LambdaContextDecl,
12294 bool IsDecltype) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +000012295 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(),
12296 ExprNeedsCleanups, LambdaContextDecl,
12297 IsDecltype);
John McCall31168b02011-06-15 23:02:42 +000012298 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +000012299 if (!MaybeODRUseExprs.empty())
12300 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +000012301}
12302
Eli Friedman15681d62012-09-26 04:34:21 +000012303void
12304Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12305 ReuseLambdaContextDecl_t,
12306 bool IsDecltype) {
Eli Friedman7e346a82013-07-01 20:22:57 +000012307 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
12308 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
Eli Friedman15681d62012-09-26 04:34:21 +000012309}
12310
Richard Trieucfc491d2011-08-02 04:35:43 +000012311void Sema::PopExpressionEvaluationContext() {
Eli Friedmanfa0df832012-02-02 03:46:19 +000012312 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Kaelyn Takata6c759512014-10-27 18:07:37 +000012313 unsigned NumTypos = Rec.NumTypos;
Douglas Gregor0b6a6242009-06-22 20:57:11 +000012314
Douglas Gregor89625492012-02-09 08:14:43 +000012315 if (!Rec.Lambdas.empty()) {
David Majnemer9adc3612013-10-25 09:12:52 +000012316 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12317 unsigned D;
12318 if (Rec.isUnevaluated()) {
12319 // C++11 [expr.prim.lambda]p2:
12320 // A lambda-expression shall not appear in an unevaluated operand
12321 // (Clause 5).
12322 D = diag::err_lambda_unevaluated_operand;
12323 } else {
12324 // C++1y [expr.const]p2:
12325 // A conditional-expression e is a core constant expression unless the
12326 // evaluation of e, following the rules of the abstract machine, would
12327 // evaluate [...] a lambda-expression.
12328 D = diag::err_lambda_in_constant_expression;
12329 }
Aaron Ballmanae2144e2014-10-16 17:53:07 +000012330 for (const auto *L : Rec.Lambdas)
12331 Diag(L->getLocStart(), D);
Douglas Gregor89625492012-02-09 08:14:43 +000012332 } else {
12333 // Mark the capture expressions odr-used. This was deferred
12334 // during lambda expression creation.
Aaron Ballmanae2144e2014-10-16 17:53:07 +000012335 for (auto *Lambda : Rec.Lambdas) {
12336 for (auto *C : Lambda->capture_inits())
12337 MarkDeclarationsReferencedInExpr(C);
Douglas Gregor89625492012-02-09 08:14:43 +000012338 }
12339 }
12340 }
12341
Douglas Gregorff790f12009-11-26 00:44:06 +000012342 // When are coming out of an unevaluated context, clear out any
12343 // temporaries that we may have created as part of the evaluation of
12344 // the expression in that context: they aren't relevant because they
12345 // will never be constructed.
John McCallf413f5e2013-05-03 00:10:13 +000012346 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
John McCall28fc7092011-11-10 05:35:25 +000012347 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
12348 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +000012349 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +000012350 CleanupVarDeclMarking();
12351 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCall31168b02011-06-15 23:02:42 +000012352 // Otherwise, merge the contexts together.
12353 } else {
12354 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +000012355 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
12356 Rec.SavedMaybeODRUseExprs.end());
John McCall31168b02011-06-15 23:02:42 +000012357 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000012358
12359 // Pop the current expression evaluation context off the stack.
12360 ExprEvalContexts.pop_back();
Kaelyn Takata6c759512014-10-27 18:07:37 +000012361
12362 if (!ExprEvalContexts.empty())
12363 ExprEvalContexts.back().NumTypos += NumTypos;
12364 else
12365 assert(NumTypos == 0 && "There are outstanding typos after popping the "
12366 "last ExpressionEvaluationContextRecord");
Douglas Gregor0b6a6242009-06-22 20:57:11 +000012367}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000012368
John McCall31168b02011-06-15 23:02:42 +000012369void Sema::DiscardCleanupsInEvaluationContext() {
John McCall28fc7092011-11-10 05:35:25 +000012370 ExprCleanupObjects.erase(
12371 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
12372 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +000012373 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +000012374 MaybeODRUseExprs.clear();
John McCall31168b02011-06-15 23:02:42 +000012375}
12376
Eli Friedmane0afc982012-01-21 01:01:51 +000012377ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
12378 if (!E->getType()->isVariablyModifiedType())
12379 return E;
Benjamin Kramerd81108f2012-11-14 15:08:31 +000012380 return TransformToPotentiallyEvaluated(E);
Eli Friedmane0afc982012-01-21 01:01:51 +000012381}
12382
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +000012383static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000012384 // Do not mark anything as "used" within a dependent context; wait for
12385 // an instantiation.
Eli Friedmanfa0df832012-02-02 03:46:19 +000012386 if (SemaRef.CurContext->isDependentContext())
12387 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012388
Eli Friedmanfa0df832012-02-02 03:46:19 +000012389 switch (SemaRef.ExprEvalContexts.back().Context) {
12390 case Sema::Unevaluated:
John McCallf413f5e2013-05-03 00:10:13 +000012391 case Sema::UnevaluatedAbstract:
Douglas Gregor0b6a6242009-06-22 20:57:11 +000012392 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman02b58512012-01-21 04:44:06 +000012393 // (Depending on how you read the standard, we actually do need to do
12394 // something here for null pointer constants, but the standard's
12395 // definition of a null pointer constant is completely crazy.)
Eli Friedmanfa0df832012-02-02 03:46:19 +000012396 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012397
Eli Friedmanfa0df832012-02-02 03:46:19 +000012398 case Sema::ConstantEvaluated:
12399 case Sema::PotentiallyEvaluated:
Eli Friedman02b58512012-01-21 04:44:06 +000012400 // We are in a potentially evaluated expression (or a constant-expression
12401 // in C++03); we need to do implicit template instantiation, implicitly
12402 // define class members, and mark most declarations as used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000012403 return true;
Mike Stump11289f42009-09-09 15:08:12 +000012404
Eli Friedmanfa0df832012-02-02 03:46:19 +000012405 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000012406 // Referenced declarations will only be used if the construct in the
12407 // containing expression is used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000012408 return false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +000012409 }
Matt Beaumont-Gay248bc722012-02-02 18:35:35 +000012410 llvm_unreachable("Invalid context");
Eli Friedmanfa0df832012-02-02 03:46:19 +000012411}
12412
12413/// \brief Mark a function referenced, and check whether it is odr-used
12414/// (C++ [basic.def.odr]p2, C99 6.9p3)
Nico Weber8bf410f2014-08-27 17:04:39 +000012415void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
12416 bool OdrUse) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000012417 assert(Func && "No function?");
12418
12419 Func->setReferenced();
12420
Richard Smithe10d3042012-11-07 01:14:25 +000012421 // C++11 [basic.def.odr]p3:
12422 // A function whose name appears as a potentially-evaluated expression is
12423 // odr-used if it is the unique lookup result or the selected member of a
12424 // set of overloaded functions [...].
12425 //
12426 // We (incorrectly) mark overload resolution as an unevaluated context, so we
12427 // can just check that here. Skip the rest of this function if we've already
12428 // marked the function as used.
Nico Weber562ff372015-01-25 01:00:21 +000012429 if (Func->isUsed(/*CheckUsedAttr=*/false) ||
12430 !IsPotentiallyEvaluatedContext(*this)) {
Richard Smithe10d3042012-11-07 01:14:25 +000012431 // C++11 [temp.inst]p3:
12432 // Unless a function template specialization has been explicitly
12433 // instantiated or explicitly specialized, the function template
12434 // specialization is implicitly instantiated when the specialization is
12435 // referenced in a context that requires a function definition to exist.
12436 //
12437 // We consider constexpr function templates to be referenced in a context
12438 // that requires a definition to exist whenever they are referenced.
12439 //
12440 // FIXME: This instantiates constexpr functions too frequently. If this is
12441 // really an unevaluated context (and we're not just in the definition of a
12442 // function template or overload resolution or other cases which we
12443 // incorrectly consider to be unevaluated contexts), and we're not in a
12444 // subexpression which we actually need to evaluate (for instance, a
12445 // template argument, array bound or an expression in a braced-init-list),
12446 // we are not permitted to instantiate this constexpr function definition.
12447 //
12448 // FIXME: This also implicitly defines special members too frequently. They
12449 // are only supposed to be implicitly defined if they are odr-used, but they
12450 // are not odr-used from constant expressions in unevaluated contexts.
12451 // However, they cannot be referenced if they are deleted, and they are
12452 // deleted whenever the implicit definition of the special member would
12453 // fail.
David Majnemerc85ed7e2013-10-23 21:31:20 +000012454 if (!Func->isConstexpr() || Func->getBody())
Richard Smithe10d3042012-11-07 01:14:25 +000012455 return;
12456 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
12457 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
12458 return;
12459 }
Mike Stump11289f42009-09-09 15:08:12 +000012460
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000012461 // Note that this declaration has been used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000012462 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smithab44d5b2013-12-10 08:25:00 +000012463 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
Richard Smith273c4e92012-02-26 07:51:39 +000012464 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000012465 if (Constructor->isDefaultConstructor()) {
Hans Wennborg853ae942014-05-30 16:59:42 +000012466 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
Sebastian Redl22653ba2011-08-30 19:58:05 +000012467 return;
Richard Smithab44d5b2013-12-10 08:25:00 +000012468 DefineImplicitDefaultConstructor(Loc, Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012469 } else if (Constructor->isCopyConstructor()) {
Richard Smithab44d5b2013-12-10 08:25:00 +000012470 DefineImplicitCopyConstructor(Loc, Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012471 } else if (Constructor->isMoveConstructor()) {
Richard Smithab44d5b2013-12-10 08:25:00 +000012472 DefineImplicitMoveConstructor(Loc, Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012473 }
Richard Smithc2bc61b2013-03-18 21:12:30 +000012474 } else if (Constructor->getInheritedConstructor()) {
Richard Smithab44d5b2013-12-10 08:25:00 +000012475 DefineInheritingConstructor(Loc, Constructor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +000012476 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000012477 } else if (CXXDestructorDecl *Destructor =
12478 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smithab44d5b2013-12-10 08:25:00 +000012479 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
Nico Weber55905142015-03-06 06:01:06 +000012480 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
12481 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
12482 return;
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000012483 DefineImplicitDestructor(Loc, Destructor);
Nico Weber55905142015-03-06 06:01:06 +000012484 }
Nico Weberb3a99782015-01-26 06:23:36 +000012485 if (Destructor->isVirtual() && getLangOpts().AppleKext)
Douglas Gregor88d292c2010-05-13 16:44:06 +000012486 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +000012487 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smithab44d5b2013-12-10 08:25:00 +000012488 if (MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +000012489 MethodDecl->getOverloadedOperator() == OO_Equal) {
Richard Smithab44d5b2013-12-10 08:25:00 +000012490 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
12491 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000012492 if (MethodDecl->isCopyAssignmentOperator())
12493 DefineImplicitCopyAssignment(Loc, MethodDecl);
12494 else
12495 DefineImplicitMoveAssignment(Loc, MethodDecl);
12496 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000012497 } else if (isa<CXXConversionDecl>(MethodDecl) &&
12498 MethodDecl->getParent()->isLambda()) {
Richard Smithab44d5b2013-12-10 08:25:00 +000012499 CXXConversionDecl *Conversion =
12500 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
Douglas Gregord3b672c2012-02-16 01:06:16 +000012501 if (Conversion->isLambdaToBlockPointerConversion())
12502 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
12503 else
12504 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Nico Weberb3a99782015-01-26 06:23:36 +000012505 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
Douglas Gregor88d292c2010-05-13 16:44:06 +000012506 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000012507 }
John McCall83779672011-02-19 02:53:41 +000012508
Eli Friedmanfa0df832012-02-02 03:46:19 +000012509 // Recursive functions should be marked when used from another function.
12510 // FIXME: Is this really right?
12511 if (CurContext == Func) return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000012512
Richard Smithd3b5c9082012-07-27 04:22:15 +000012513 // Resolve the exception specification for any function which is
Richard Smithf623c962012-04-17 00:58:00 +000012514 // used: CodeGen will need it.
Richard Smithd3729422012-04-19 00:08:28 +000012515 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +000012516 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
12517 ResolveExceptionSpec(Loc, FPT);
Richard Smithf623c962012-04-17 00:58:00 +000012518
Nico Weber8bf410f2014-08-27 17:04:39 +000012519 if (!OdrUse) return;
12520
Eli Friedmanfa0df832012-02-02 03:46:19 +000012521 // Implicit instantiation of function templates and member functions of
12522 // class templates.
12523 if (Func->isImplicitlyInstantiable()) {
12524 bool AlreadyInstantiated = false;
Richard Smith4a941e22012-02-14 22:25:15 +000012525 SourceLocation PointOfInstantiation = Loc;
Eli Friedmanfa0df832012-02-02 03:46:19 +000012526 if (FunctionTemplateSpecializationInfo *SpecInfo
12527 = Func->getTemplateSpecializationInfo()) {
12528 if (SpecInfo->getPointOfInstantiation().isInvalid())
12529 SpecInfo->setPointOfInstantiation(Loc);
12530 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000012531 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000012532 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000012533 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
12534 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000012535 } else if (MemberSpecializationInfo *MSInfo
12536 = Func->getMemberSpecializationInfo()) {
12537 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregor06db9f52009-10-12 20:18:28 +000012538 MSInfo->setPointOfInstantiation(Loc);
Eli Friedmanfa0df832012-02-02 03:46:19 +000012539 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000012540 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000012541 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000012542 PointOfInstantiation = MSInfo->getPointOfInstantiation();
12543 }
Douglas Gregor06db9f52009-10-12 20:18:28 +000012544 }
Mike Stump11289f42009-09-09 15:08:12 +000012545
David Majnemerc85ed7e2013-10-23 21:31:20 +000012546 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000012547 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
Faisal Vali18d35982013-06-26 02:34:24 +000012548 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
12549 ActiveTemplateInstantiations.size())
Richard Smith4a941e22012-02-14 22:25:15 +000012550 PendingLocalImplicitInstantiations.push_back(
12551 std::make_pair(Func, PointOfInstantiation));
David Majnemerc85ed7e2013-10-23 21:31:20 +000012552 else if (Func->isConstexpr())
Eli Friedmanfa0df832012-02-02 03:46:19 +000012553 // Do not defer instantiations of constexpr functions, to avoid the
12554 // expression evaluator needing to call back into Sema if it sees a
12555 // call to such a function.
Richard Smith4a941e22012-02-14 22:25:15 +000012556 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000012557 else {
Richard Smith4a941e22012-02-14 22:25:15 +000012558 PendingInstantiations.push_back(std::make_pair(Func,
12559 PointOfInstantiation));
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000012560 // Notify the consumer that a function was implicitly instantiated.
12561 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
12562 }
John McCall83779672011-02-19 02:53:41 +000012563 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000012564 } else {
12565 // Walk redefinitions, as some of them may be instantiable.
Aaron Ballman86c93902014-03-06 23:45:36 +000012566 for (auto i : Func->redecls()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000012567 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Aaron Ballman86c93902014-03-06 23:45:36 +000012568 MarkFunctionReferenced(Loc, i);
Eli Friedmanfa0df832012-02-02 03:46:19 +000012569 }
Sam Weinigbae69142009-09-11 03:29:30 +000012570 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000012571
12572 // Keep track of used but undefined functions.
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +000012573 if (!Func->isDefined()) {
Rafael Espindola0e0d0092013-03-14 03:07:35 +000012574 if (mightHaveNonExternalLinkage(Func))
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +000012575 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
12576 else if (Func->getMostRecentDecl()->isInlined() &&
Peter Collingbourne470d9422015-05-13 22:07:22 +000012577 !LangOpts.GNUInline &&
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +000012578 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
12579 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
Eli Friedmanfa0df832012-02-02 03:46:19 +000012580 }
12581
Rafael Espindola0d3da832013-10-19 02:06:23 +000012582 // Normally the most current decl is marked used while processing the use and
Rafael Espindola820fa702013-01-08 19:43:34 +000012583 // any subsequent decls are marked used by decl merging. This fails with
12584 // template instantiation since marking can happen at the end of the file
12585 // and, because of the two phase lookup, this function is called with at
12586 // decl in the middle of a decl chain. We loop to maintain the invariant
12587 // that once a decl is used, all decls after it are also used.
Rafael Espindolaf26d5392013-01-08 19:58:34 +000012588 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
Eli Friedman276dd182013-09-05 00:02:25 +000012589 F->markUsed(Context);
Rafael Espindola820fa702013-01-08 19:43:34 +000012590 if (F == Func)
12591 break;
Rafael Espindola820fa702013-01-08 19:43:34 +000012592 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000012593}
12594
Eli Friedman9bb33f52012-02-03 02:04:35 +000012595static void
12596diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
12597 VarDecl *var, DeclContext *DC) {
Eli Friedmandd053f62012-02-07 00:15:00 +000012598 DeclContext *VarDC = var->getDeclContext();
12599
Eli Friedman9bb33f52012-02-03 02:04:35 +000012600 // If the parameter still belongs to the translation unit, then
12601 // we're actually just using one parameter in the declaration of
12602 // the next.
12603 if (isa<ParmVarDecl>(var) &&
Eli Friedmandd053f62012-02-07 00:15:00 +000012604 isa<TranslationUnitDecl>(VarDC))
Eli Friedman9bb33f52012-02-03 02:04:35 +000012605 return;
12606
Eli Friedmandd053f62012-02-07 00:15:00 +000012607 // For C code, don't diagnose about capture if we're not actually in code
12608 // right now; it's impossible to write a non-constant expression outside of
12609 // function context, so we'll get other (more useful) diagnostics later.
12610 //
12611 // For C++, things get a bit more nasty... it would be nice to suppress this
12612 // diagnostic for certain cases like using a local variable in an array bound
12613 // for a member of a local class, but the correct predicate is not obvious.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012614 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman9bb33f52012-02-03 02:04:35 +000012615 return;
12616
Eli Friedmandd053f62012-02-07 00:15:00 +000012617 if (isa<CXXMethodDecl>(VarDC) &&
12618 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
12619 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
12620 << var->getIdentifier();
12621 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
12622 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
12623 << var->getIdentifier() << fn->getDeclName();
12624 } else if (isa<BlockDecl>(VarDC)) {
12625 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
12626 << var->getIdentifier();
12627 } else {
12628 // FIXME: Is there any other context where a local variable can be
12629 // declared?
12630 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
12631 << var->getIdentifier();
12632 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000012633
Alp Toker2afa8782014-05-28 12:20:14 +000012634 S.Diag(var->getLocation(), diag::note_entity_declared_at)
12635 << var->getIdentifier();
Eli Friedmandd053f62012-02-07 00:15:00 +000012636
12637 // FIXME: Add additional diagnostic info about class etc. which prevents
12638 // capture.
Eli Friedman9bb33f52012-02-03 02:04:35 +000012639}
12640
Faisal Valiad090d82013-10-07 05:13:48 +000012641
12642static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
12643 bool &SubCapturesAreNested,
12644 QualType &CaptureType,
12645 QualType &DeclRefType) {
12646 // Check whether we've already captured it.
12647 if (CSI->CaptureMap.count(Var)) {
12648 // If we found a capture, any subcaptures are nested.
12649 SubCapturesAreNested = true;
12650
12651 // Retrieve the capture type for this variable.
12652 CaptureType = CSI->getCapture(Var).getCaptureType();
12653
12654 // Compute the type of an expression that refers to this variable.
12655 DeclRefType = CaptureType.getNonReferenceType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +000012656
12657 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
12658 // are mutable in the sense that user can change their value - they are
12659 // private instances of the captured declarations.
Faisal Valiad090d82013-10-07 05:13:48 +000012660 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
12661 if (Cap.isCopyCapture() &&
Samuel Antao4af1b7b2015-12-02 17:44:43 +000012662 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
12663 !(isa<CapturedRegionScopeInfo>(CSI) &&
12664 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
Faisal Valiad090d82013-10-07 05:13:48 +000012665 DeclRefType.addConst();
12666 return true;
12667 }
12668 return false;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000012669}
12670
Faisal Valiad090d82013-10-07 05:13:48 +000012671// Only block literals, captured statements, and lambda expressions can
12672// capture; other scopes don't work.
12673static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
12674 SourceLocation Loc,
12675 const bool Diagnose, Sema &S) {
Faisal Valia17d19f2013-11-07 05:17:06 +000012676 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
12677 return getLambdaAwareParentOfDeclContext(DC);
Alexey Bataevf841bd92014-12-16 07:00:22 +000012678 else if (Var->hasLocalStorage()) {
Faisal Valiad090d82013-10-07 05:13:48 +000012679 if (Diagnose)
12680 diagnoseUncapturableValueReference(S, Loc, Var, DC);
12681 }
Craig Topperc3ec1492014-05-26 06:22:03 +000012682 return nullptr;
Faisal Valiad090d82013-10-07 05:13:48 +000012683}
12684
12685// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
12686// certain types of variables (unnamed, variably modified types etc.)
12687// so check for eligibility.
12688static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
12689 SourceLocation Loc,
12690 const bool Diagnose, Sema &S) {
12691
12692 bool IsBlock = isa<BlockScopeInfo>(CSI);
12693 bool IsLambda = isa<LambdaScopeInfo>(CSI);
12694
12695 // Lambdas are not allowed to capture unnamed variables
12696 // (e.g. anonymous unions).
12697 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
12698 // assuming that's the intent.
12699 if (IsLambda && !Var->getDeclName()) {
12700 if (Diagnose) {
12701 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
12702 S.Diag(Var->getLocation(), diag::note_declared_at);
12703 }
12704 return false;
12705 }
12706
Alexey Bataev39c81e22014-08-28 04:28:19 +000012707 // Prohibit variably-modified types in blocks; they're difficult to deal with.
12708 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
Faisal Valiad090d82013-10-07 05:13:48 +000012709 if (Diagnose) {
Alexey Bataev39c81e22014-08-28 04:28:19 +000012710 S.Diag(Loc, diag::err_ref_vm_type);
Faisal Valiad090d82013-10-07 05:13:48 +000012711 S.Diag(Var->getLocation(), diag::note_previous_decl)
12712 << Var->getDeclName();
12713 }
12714 return false;
12715 }
12716 // Prohibit structs with flexible array members too.
12717 // We cannot capture what is in the tail end of the struct.
12718 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
12719 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
12720 if (Diagnose) {
12721 if (IsBlock)
12722 S.Diag(Loc, diag::err_ref_flexarray_type);
12723 else
12724 S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
12725 << Var->getDeclName();
12726 S.Diag(Var->getLocation(), diag::note_previous_decl)
12727 << Var->getDeclName();
12728 }
12729 return false;
12730 }
12731 }
12732 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
12733 // Lambdas and captured statements are not allowed to capture __block
12734 // variables; they don't support the expected semantics.
12735 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
12736 if (Diagnose) {
12737 S.Diag(Loc, diag::err_capture_block_variable)
12738 << Var->getDeclName() << !IsLambda;
12739 S.Diag(Var->getLocation(), diag::note_previous_decl)
12740 << Var->getDeclName();
12741 }
12742 return false;
12743 }
12744
12745 return true;
12746}
12747
12748// Returns true if the capture by block was successful.
12749static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
12750 SourceLocation Loc,
12751 const bool BuildAndDiagnose,
12752 QualType &CaptureType,
12753 QualType &DeclRefType,
12754 const bool Nested,
12755 Sema &S) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012756 Expr *CopyExpr = nullptr;
Faisal Valiad090d82013-10-07 05:13:48 +000012757 bool ByRef = false;
12758
12759 // Blocks are not allowed to capture arrays.
12760 if (CaptureType->isArrayType()) {
12761 if (BuildAndDiagnose) {
12762 S.Diag(Loc, diag::err_ref_array_type);
12763 S.Diag(Var->getLocation(), diag::note_previous_decl)
12764 << Var->getDeclName();
12765 }
12766 return false;
12767 }
12768
12769 // Forbid the block-capture of autoreleasing variables.
12770 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
12771 if (BuildAndDiagnose) {
12772 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
12773 << /*block*/ 0;
12774 S.Diag(Var->getLocation(), diag::note_previous_decl)
12775 << Var->getDeclName();
12776 }
12777 return false;
12778 }
12779 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
12780 if (HasBlocksAttr || CaptureType->isReferenceType()) {
12781 // Block capture by reference does not change the capture or
12782 // declaration reference types.
12783 ByRef = true;
12784 } else {
12785 // Block capture by copy introduces 'const'.
12786 CaptureType = CaptureType.getNonReferenceType().withConst();
12787 DeclRefType = CaptureType;
12788
12789 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
12790 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
12791 // The capture logic needs the destructor, so make sure we mark it.
12792 // Usually this is unnecessary because most local variables have
12793 // their destructors marked at declaration time, but parameters are
12794 // an exception because it's technically only the call site that
12795 // actually requires the destructor.
12796 if (isa<ParmVarDecl>(Var))
12797 S.FinalizeVarWithDestructor(Var, Record);
12798
12799 // Enter a new evaluation context to insulate the copy
12800 // full-expression.
12801 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
12802
12803 // According to the blocks spec, the capture of a variable from
12804 // the stack requires a const copy constructor. This is not true
12805 // of the copy/move done to move a __block variable to the heap.
12806 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
12807 DeclRefType.withConst(),
12808 VK_LValue, Loc);
12809
12810 ExprResult Result
12811 = S.PerformCopyInitialization(
12812 InitializedEntity::InitializeBlock(Var->getLocation(),
12813 CaptureType, false),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012814 Loc, DeclRef);
Faisal Valiad090d82013-10-07 05:13:48 +000012815
12816 // Build a full-expression copy expression if initialization
12817 // succeeded and used a non-trivial constructor. Recover from
12818 // errors by pretending that the copy isn't necessary.
12819 if (!Result.isInvalid() &&
12820 !cast<CXXConstructExpr>(Result.get())->getConstructor()
12821 ->isTrivial()) {
12822 Result = S.MaybeCreateExprWithCleanups(Result);
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012823 CopyExpr = Result.get();
Faisal Valiad090d82013-10-07 05:13:48 +000012824 }
12825 }
12826 }
12827 }
12828
12829 // Actually capture the variable.
12830 if (BuildAndDiagnose)
12831 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
12832 SourceLocation(), CaptureType, CopyExpr);
12833
12834 return true;
12835
12836}
12837
12838
12839/// \brief Capture the given variable in the captured region.
12840static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
12841 VarDecl *Var,
12842 SourceLocation Loc,
12843 const bool BuildAndDiagnose,
12844 QualType &CaptureType,
12845 QualType &DeclRefType,
Alexey Bataev07649fb2014-12-16 08:01:48 +000012846 const bool RefersToCapturedVariable,
Faisal Valiad090d82013-10-07 05:13:48 +000012847 Sema &S) {
12848
12849 // By default, capture variables by reference.
12850 bool ByRef = true;
12851 // Using an LValue reference type is consistent with Lambdas (see below).
Samuel Antao4af1b7b2015-12-02 17:44:43 +000012852 if (S.getLangOpts().OpenMP) {
12853 ByRef = S.IsOpenMPCapturedByRef(Var, RSI);
12854 if (S.IsOpenMPCapturedVar(Var))
12855 DeclRefType = DeclRefType.getUnqualifiedType();
12856 }
12857
12858 if (ByRef)
12859 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
12860 else
12861 CaptureType = DeclRefType;
12862
Craig Topperc3ec1492014-05-26 06:22:03 +000012863 Expr *CopyExpr = nullptr;
Faisal Valiad090d82013-10-07 05:13:48 +000012864 if (BuildAndDiagnose) {
12865 // The current implementation assumes that all variables are captured
Nico Weber83ea0122014-05-03 21:57:40 +000012866 // by references. Since there is no capture by copy, no expression
12867 // evaluation will be needed.
Faisal Valiad090d82013-10-07 05:13:48 +000012868 RecordDecl *RD = RSI->TheRecordDecl;
12869
12870 FieldDecl *Field
Craig Topperc3ec1492014-05-26 06:22:03 +000012871 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
Faisal Valiad090d82013-10-07 05:13:48 +000012872 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
Craig Topperc3ec1492014-05-26 06:22:03 +000012873 nullptr, false, ICIS_NoInit);
Faisal Valiad090d82013-10-07 05:13:48 +000012874 Field->setImplicit(true);
12875 Field->setAccess(AS_private);
12876 RD->addDecl(Field);
12877
Alexey Bataev07649fb2014-12-16 08:01:48 +000012878 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
Faisal Valiad090d82013-10-07 05:13:48 +000012879 DeclRefType, VK_LValue, Loc);
12880 Var->setReferenced(true);
12881 Var->markUsed(S.Context);
12882 }
12883
12884 // Actually capture the variable.
12885 if (BuildAndDiagnose)
Alexey Bataev07649fb2014-12-16 08:01:48 +000012886 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
Faisal Valiad090d82013-10-07 05:13:48 +000012887 SourceLocation(), CaptureType, CopyExpr);
12888
12889
12890 return true;
12891}
12892
12893/// \brief Create a field within the lambda class for the variable
Richard Smithc38498f2015-04-27 21:27:54 +000012894/// being captured.
12895static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, VarDecl *Var,
12896 QualType FieldType, QualType DeclRefType,
12897 SourceLocation Loc,
12898 bool RefersToCapturedVariable) {
Douglas Gregor81495f32012-02-12 18:42:33 +000012899 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregor81495f32012-02-12 18:42:33 +000012900
Douglas Gregorabecb9c2012-02-09 01:56:40 +000012901 // Build the non-static data member.
12902 FieldDecl *Field
Craig Topperc3ec1492014-05-26 06:22:03 +000012903 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
Douglas Gregorabecb9c2012-02-09 01:56:40 +000012904 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Craig Topperc3ec1492014-05-26 06:22:03 +000012905 nullptr, false, ICIS_NoInit);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000012906 Field->setImplicit(true);
12907 Field->setAccess(AS_private);
Douglas Gregor3d23f7882012-02-09 02:12:34 +000012908 Lambda->addDecl(Field);
Douglas Gregor199cec72012-02-09 02:45:47 +000012909}
Douglas Gregorabecb9c2012-02-09 01:56:40 +000012910
Faisal Valiad090d82013-10-07 05:13:48 +000012911/// \brief Capture the given variable in the lambda.
12912static bool captureInLambda(LambdaScopeInfo *LSI,
12913 VarDecl *Var,
12914 SourceLocation Loc,
12915 const bool BuildAndDiagnose,
12916 QualType &CaptureType,
12917 QualType &DeclRefType,
Alexey Bataev07649fb2014-12-16 08:01:48 +000012918 const bool RefersToCapturedVariable,
Faisal Valiad090d82013-10-07 05:13:48 +000012919 const Sema::TryCaptureKind Kind,
12920 SourceLocation EllipsisLoc,
12921 const bool IsTopScope,
12922 Sema &S) {
12923
12924 // Determine whether we are capturing by reference or by value.
12925 bool ByRef = false;
12926 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
12927 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
12928 } else {
12929 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
12930 }
12931
12932 // Compute the type of the field that will capture this variable.
12933 if (ByRef) {
12934 // C++11 [expr.prim.lambda]p15:
12935 // An entity is captured by reference if it is implicitly or
12936 // explicitly captured but not captured by copy. It is
12937 // unspecified whether additional unnamed non-static data
12938 // members are declared in the closure type for entities
12939 // captured by reference.
12940 //
12941 // FIXME: It is not clear whether we want to build an lvalue reference
12942 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
12943 // to do the former, while EDG does the latter. Core issue 1249 will
12944 // clarify, but for now we follow GCC because it's a more permissive and
12945 // easily defensible position.
12946 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
12947 } else {
12948 // C++11 [expr.prim.lambda]p14:
12949 // For each entity captured by copy, an unnamed non-static
12950 // data member is declared in the closure type. The
12951 // declaration order of these members is unspecified. The type
12952 // of such a data member is the type of the corresponding
12953 // captured entity if the entity is not a reference to an
12954 // object, or the referenced type otherwise. [Note: If the
12955 // captured entity is a reference to a function, the
12956 // corresponding data member is also a reference to a
12957 // function. - end note ]
12958 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
12959 if (!RefType->getPointeeType()->isFunctionType())
12960 CaptureType = RefType->getPointeeType();
12961 }
12962
12963 // Forbid the lambda copy-capture of autoreleasing variables.
12964 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
12965 if (BuildAndDiagnose) {
12966 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
12967 S.Diag(Var->getLocation(), diag::note_previous_decl)
12968 << Var->getDeclName();
12969 }
12970 return false;
12971 }
Douglas Gregor71fe0e82013-10-11 04:25:21 +000012972
Richard Smith111d3482014-01-21 23:27:46 +000012973 // Make sure that by-copy captures are of a complete and non-abstract type.
12974 if (BuildAndDiagnose) {
12975 if (!CaptureType->isDependentType() &&
12976 S.RequireCompleteType(Loc, CaptureType,
12977 diag::err_capture_of_incomplete_type,
12978 Var->getDeclName()))
12979 return false;
12980
12981 if (S.RequireNonAbstractType(Loc, CaptureType,
12982 diag::err_capture_of_abstract_type))
12983 return false;
12984 }
Faisal Valiad090d82013-10-07 05:13:48 +000012985 }
12986
12987 // Capture this variable in the lambda.
Richard Smithc38498f2015-04-27 21:27:54 +000012988 if (BuildAndDiagnose)
12989 addAsFieldToClosureType(S, LSI, Var, CaptureType, DeclRefType, Loc,
12990 RefersToCapturedVariable);
Faisal Valiad090d82013-10-07 05:13:48 +000012991
12992 // Compute the type of a reference to this captured variable.
12993 if (ByRef)
12994 DeclRefType = CaptureType.getNonReferenceType();
12995 else {
12996 // C++ [expr.prim.lambda]p5:
12997 // The closure type for a lambda-expression has a public inline
12998 // function call operator [...]. This function call operator is
12999 // declared const (9.3.1) if and only if the lambda-expression’s
13000 // parameter-declaration-clause is not followed by mutable.
13001 DeclRefType = CaptureType.getNonReferenceType();
13002 if (!LSI->Mutable && !CaptureType->isReferenceType())
13003 DeclRefType.addConst();
13004 }
13005
13006 // Add the capture.
13007 if (BuildAndDiagnose)
Alexey Bataev07649fb2014-12-16 08:01:48 +000013008 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
Richard Smithc38498f2015-04-27 21:27:54 +000013009 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
Faisal Valiad090d82013-10-07 05:13:48 +000013010
13011 return true;
13012}
13013
Richard Smithc38498f2015-04-27 21:27:54 +000013014bool Sema::tryCaptureVariable(
13015 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13016 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13017 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13018 // An init-capture is notionally from the context surrounding its
13019 // declaration, but its parent DC is the lambda class.
13020 DeclContext *VarDC = Var->getDeclContext();
13021 if (Var->isInitCapture())
13022 VarDC = VarDC->getParent();
Douglas Gregor81495f32012-02-12 18:42:33 +000013023
Eli Friedman24af8502012-02-03 22:47:37 +000013024 DeclContext *DC = CurContext;
Faisal Valia17d19f2013-11-07 05:17:06 +000013025 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
13026 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
13027 // We need to sync up the Declaration Context with the
13028 // FunctionScopeIndexToStopAt
13029 if (FunctionScopeIndexToStopAt) {
13030 unsigned FSIndex = FunctionScopes.size() - 1;
13031 while (FSIndex != MaxFunctionScopesIndex) {
13032 DC = getLambdaAwareParentOfDeclContext(DC);
13033 --FSIndex;
13034 }
13035 }
Faisal Valiad090d82013-10-07 05:13:48 +000013036
Faisal Valia17d19f2013-11-07 05:17:06 +000013037
Richard Smithc38498f2015-04-27 21:27:54 +000013038 // If the variable is declared in the current context, there is no need to
13039 // capture it.
13040 if (VarDC == DC) return true;
Alexey Bataevf841bd92014-12-16 07:00:22 +000013041
13042 // Capture global variables if it is required to use private copy of this
13043 // variable.
13044 bool IsGlobal = !Var->hasLocalStorage();
13045 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedVar(Var)))
13046 return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000013047
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013048 // Walk up the stack to determine whether we can capture the variable,
13049 // performing the "simple" checks that don't depend on type. We stop when
13050 // we've either hit the declared scope of the variable or find an existing
Faisal Valiad090d82013-10-07 05:13:48 +000013051 // capture of that variable. We start from the innermost capturing-entity
13052 // (the DC) and ensure that all intervening capturing-entities
13053 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
13054 // declcontext can either capture the variable or have already captured
13055 // the variable.
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013056 CaptureType = Var->getType();
13057 DeclRefType = CaptureType.getNonReferenceType();
Richard Smithc38498f2015-04-27 21:27:54 +000013058 bool Nested = false;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013059 bool Explicit = (Kind != TryCapture_Implicit);
Faisal Valiad090d82013-10-07 05:13:48 +000013060 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
Alexey Bataevaac108a2015-06-23 04:51:00 +000013061 unsigned OpenMPLevel = 0;
Eli Friedman9bb33f52012-02-03 02:04:35 +000013062 do {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000013063 // Only block literals, captured statements, and lambda expressions can
13064 // capture; other scopes don't work.
Faisal Valiad090d82013-10-07 05:13:48 +000013065 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
13066 ExprLoc,
13067 BuildAndDiagnose,
13068 *this);
Alexey Bataevf841bd92014-12-16 07:00:22 +000013069 // We need to check for the parent *first* because, if we *have*
13070 // private-captured a global variable, we need to recursively capture it in
13071 // intermediate blocks, lambdas, etc.
13072 if (!ParentDC) {
13073 if (IsGlobal) {
13074 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
13075 break;
13076 }
13077 return true;
13078 }
13079
Faisal Valiad090d82013-10-07 05:13:48 +000013080 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
13081 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
Eli Friedman9bb33f52012-02-03 02:04:35 +000013082
Eli Friedman9bb33f52012-02-03 02:04:35 +000013083
Eli Friedman24af8502012-02-03 22:47:37 +000013084 // Check whether we've already captured it.
Faisal Valiad090d82013-10-07 05:13:48 +000013085 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
13086 DeclRefType))
Eli Friedman9bb33f52012-02-03 02:04:35 +000013087 break;
Faisal Valia17d19f2013-11-07 05:17:06 +000013088 // If we are instantiating a generic lambda call operator body,
13089 // we do not want to capture new variables. What was captured
13090 // during either a lambdas transformation or initial parsing
13091 // should be used.
13092 if (isGenericLambdaCallOperatorSpecialization(DC)) {
13093 if (BuildAndDiagnose) {
13094 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13095 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
13096 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13097 Diag(Var->getLocation(), diag::note_previous_decl)
13098 << Var->getDeclName();
13099 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
13100 } else
13101 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
13102 }
13103 return true;
13104 }
Faisal Valiad090d82013-10-07 05:13:48 +000013105 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13106 // certain types of variables (unnamed, variably modified types etc.)
13107 // so check for eligibility.
13108 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
Alexey Bataevaca7fcf2014-06-30 02:55:54 +000013109 return true;
13110
13111 // Try to capture variable-length arrays types.
13112 if (Var->getType()->isVariablyModifiedType()) {
13113 // We're going to walk down into the type and look for VLA
13114 // expressions.
13115 QualType QTy = Var->getType();
13116 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
13117 QTy = PVD->getOriginalType();
13118 do {
13119 const Type *Ty = QTy.getTypePtr();
13120 switch (Ty->getTypeClass()) {
13121#define TYPE(Class, Base)
13122#define ABSTRACT_TYPE(Class, Base)
13123#define NON_CANONICAL_TYPE(Class, Base)
13124#define DEPENDENT_TYPE(Class, Base) case Type::Class:
13125#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
13126#include "clang/AST/TypeNodes.def"
13127 QTy = QualType();
13128 break;
13129 // These types are never variably-modified.
13130 case Type::Builtin:
13131 case Type::Complex:
13132 case Type::Vector:
13133 case Type::ExtVector:
13134 case Type::Record:
13135 case Type::Enum:
13136 case Type::Elaborated:
13137 case Type::TemplateSpecialization:
13138 case Type::ObjCObject:
13139 case Type::ObjCInterface:
13140 case Type::ObjCObjectPointer:
13141 llvm_unreachable("type class is never variably-modified!");
13142 case Type::Adjusted:
13143 QTy = cast<AdjustedType>(Ty)->getOriginalType();
13144 break;
13145 case Type::Decayed:
13146 QTy = cast<DecayedType>(Ty)->getPointeeType();
13147 break;
13148 case Type::Pointer:
13149 QTy = cast<PointerType>(Ty)->getPointeeType();
13150 break;
13151 case Type::BlockPointer:
13152 QTy = cast<BlockPointerType>(Ty)->getPointeeType();
13153 break;
13154 case Type::LValueReference:
13155 case Type::RValueReference:
13156 QTy = cast<ReferenceType>(Ty)->getPointeeType();
13157 break;
13158 case Type::MemberPointer:
13159 QTy = cast<MemberPointerType>(Ty)->getPointeeType();
13160 break;
13161 case Type::ConstantArray:
13162 case Type::IncompleteArray:
13163 // Losing element qualification here is fine.
13164 QTy = cast<ArrayType>(Ty)->getElementType();
13165 break;
13166 case Type::VariableArray: {
13167 // Losing element qualification here is fine.
Alexey Bataev39c81e22014-08-28 04:28:19 +000013168 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
Alexey Bataevaca7fcf2014-06-30 02:55:54 +000013169
13170 // Unknown size indication requires no size computation.
13171 // Otherwise, evaluate and record it.
Alexey Bataev39c81e22014-08-28 04:28:19 +000013172 if (auto Size = VAT->getSizeExpr()) {
Alexey Bataev330de032014-10-29 12:21:55 +000013173 if (!CSI->isVLATypeCaptured(VAT)) {
13174 RecordDecl *CapRecord = nullptr;
13175 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
13176 CapRecord = LSI->Lambda;
13177 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13178 CapRecord = CRSI->TheRecordDecl;
13179 }
13180 if (CapRecord) {
Alexey Bataev39c81e22014-08-28 04:28:19 +000013181 auto ExprLoc = Size->getExprLoc();
13182 auto SizeType = Context.getSizeType();
Alexey Bataev39c81e22014-08-28 04:28:19 +000013183 // Build the non-static data member.
13184 auto Field = FieldDecl::Create(
Alexey Bataev330de032014-10-29 12:21:55 +000013185 Context, CapRecord, ExprLoc, ExprLoc,
Alexey Bataev39c81e22014-08-28 04:28:19 +000013186 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
13187 /*BW*/ nullptr, /*Mutable*/ false,
13188 /*InitStyle*/ ICIS_NoInit);
13189 Field->setImplicit(true);
13190 Field->setAccess(AS_private);
13191 Field->setCapturedVLAType(VAT);
Alexey Bataev330de032014-10-29 12:21:55 +000013192 CapRecord->addDecl(Field);
Alexey Bataev39c81e22014-08-28 04:28:19 +000013193
Alexey Bataev330de032014-10-29 12:21:55 +000013194 CSI->addVLATypeCapture(ExprLoc, SizeType);
Alexey Bataev39c81e22014-08-28 04:28:19 +000013195 }
Alexey Bataev39c81e22014-08-28 04:28:19 +000013196 }
Alexey Bataevaca7fcf2014-06-30 02:55:54 +000013197 }
Alexey Bataev39c81e22014-08-28 04:28:19 +000013198 QTy = VAT->getElementType();
Alexey Bataevaca7fcf2014-06-30 02:55:54 +000013199 break;
13200 }
13201 case Type::FunctionProto:
13202 case Type::FunctionNoProto:
13203 QTy = cast<FunctionType>(Ty)->getReturnType();
13204 break;
13205 case Type::Paren:
13206 case Type::TypeOf:
13207 case Type::UnaryTransform:
13208 case Type::Attributed:
13209 case Type::SubstTemplateTypeParm:
13210 case Type::PackExpansion:
13211 // Keep walking after single level desugaring.
13212 QTy = QTy.getSingleStepDesugaredType(getASTContext());
13213 break;
13214 case Type::Typedef:
13215 QTy = cast<TypedefType>(Ty)->desugar();
13216 break;
13217 case Type::Decltype:
13218 QTy = cast<DecltypeType>(Ty)->desugar();
13219 break;
13220 case Type::Auto:
13221 QTy = cast<AutoType>(Ty)->getDeducedType();
13222 break;
13223 case Type::TypeOfExpr:
13224 QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
13225 break;
13226 case Type::Atomic:
13227 QTy = cast<AtomicType>(Ty)->getValueType();
13228 break;
13229 }
13230 } while (!QTy.isNull() && QTy->isVariablyModifiedType());
13231 }
13232
Alexey Bataevb5001012015-09-03 10:21:46 +000013233 if (getLangOpts().OpenMP) {
13234 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13235 // OpenMP private variables should not be captured in outer scope, so
Samuel Antao4be30e92015-10-02 17:14:03 +000013236 // just break here. Similarly, global variables that are captured in a
13237 // target region should not be captured outside the scope of the region.
Alexey Bataevb5001012015-09-03 10:21:46 +000013238 if (RSI->CapRegionKind == CR_OpenMP) {
Samuel Antao4be30e92015-10-02 17:14:03 +000013239 auto isTargetCap = isOpenMPTargetCapturedVar(Var, OpenMPLevel);
13240 // When we detect target captures we are looking from inside the
13241 // target region, therefore we need to propagate the capture from the
13242 // enclosing region. Therefore, the capture is not initially nested.
13243 if (isTargetCap)
13244 FunctionScopesIndex--;
13245
13246 if (isTargetCap || isOpenMPPrivateVar(Var, OpenMPLevel)) {
13247 Nested = !isTargetCap;
Alexey Bataevb5001012015-09-03 10:21:46 +000013248 DeclRefType = DeclRefType.getUnqualifiedType();
13249 CaptureType = Context.getLValueReferenceType(DeclRefType);
13250 break;
13251 }
13252 ++OpenMPLevel;
13253 }
13254 }
13255 }
Douglas Gregor81495f32012-02-12 18:42:33 +000013256 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
Faisal Valiad090d82013-10-07 05:13:48 +000013257 // No capture-default, and this is not an explicit capture
13258 // so cannot capture this variable.
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013259 if (BuildAndDiagnose) {
Faisal Valiad090d82013-10-07 05:13:48 +000013260 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
Douglas Gregor81495f32012-02-12 18:42:33 +000013261 Diag(Var->getLocation(), diag::note_previous_decl)
13262 << Var->getDeclName();
13263 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
13264 diag::note_lambda_decl);
Faisal Valia17d19f2013-11-07 05:17:06 +000013265 // FIXME: If we error out because an outer lambda can not implicitly
13266 // capture a variable that an inner lambda explicitly captures, we
13267 // should have the inner lambda do the explicit capture - because
13268 // it makes for cleaner diagnostics later. This would purely be done
13269 // so that the diagnostic does not misleadingly claim that a variable
13270 // can not be captured by a lambda implicitly even though it is captured
13271 // explicitly. Suggestion:
13272 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
13273 // at the function head
13274 // - cache the StartingDeclContext - this must be a lambda
13275 // - captureInLambda in the innermost lambda the variable.
Douglas Gregor81495f32012-02-12 18:42:33 +000013276 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013277 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000013278 }
13279
13280 FunctionScopesIndex--;
13281 DC = ParentDC;
13282 Explicit = false;
Richard Smithc38498f2015-04-27 21:27:54 +000013283 } while (!VarDC->Equals(DC));
Douglas Gregor81495f32012-02-12 18:42:33 +000013284
Faisal Valiad090d82013-10-07 05:13:48 +000013285 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
13286 // computing the type of the capture at each step, checking type-specific
13287 // requirements, and adding captures if requested.
13288 // If the variable had already been captured previously, we start capturing
13289 // at the lambda nested within that one.
13290 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013291 ++I) {
13292 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor812d8f62012-02-18 05:51:20 +000013293
Faisal Valiad090d82013-10-07 05:13:48 +000013294 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
13295 if (!captureInBlock(BSI, Var, ExprLoc,
13296 BuildAndDiagnose, CaptureType,
13297 DeclRefType, Nested, *this))
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013298 return true;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013299 Nested = true;
Faisal Valiad090d82013-10-07 05:13:48 +000013300 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13301 if (!captureInCapturedRegion(RSI, Var, ExprLoc,
13302 BuildAndDiagnose, CaptureType,
13303 DeclRefType, Nested, *this))
John McCall67cd5e02012-03-30 05:23:48 +000013304 return true;
Faisal Valiad090d82013-10-07 05:13:48 +000013305 Nested = true;
13306 } else {
13307 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13308 if (!captureInLambda(LSI, Var, ExprLoc,
13309 BuildAndDiagnose, CaptureType,
13310 DeclRefType, Nested, Kind, EllipsisLoc,
13311 /*IsTopScope*/I == N - 1, *this))
13312 return true;
13313 Nested = true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000013314 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000013315 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013316 return false;
13317}
13318
13319bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
13320 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
13321 QualType CaptureType;
13322 QualType DeclRefType;
13323 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
13324 /*BuildAndDiagnose=*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +000013325 DeclRefType, nullptr);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013326}
13327
Alexey Bataevf841bd92014-12-16 07:00:22 +000013328bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
13329 QualType CaptureType;
13330 QualType DeclRefType;
13331 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13332 /*BuildAndDiagnose=*/false, CaptureType,
13333 DeclRefType, nullptr);
13334}
13335
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013336QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
13337 QualType CaptureType;
13338 QualType DeclRefType;
13339
13340 // Determine whether we can capture this variable.
13341 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
Faisal Valia17d19f2013-11-07 05:17:06 +000013342 /*BuildAndDiagnose=*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +000013343 DeclRefType, nullptr))
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013344 return QualType();
13345
13346 return DeclRefType;
Eli Friedman9bb33f52012-02-03 02:04:35 +000013347}
13348
Eli Friedman3bda6b12012-02-02 23:15:15 +000013349
Eli Friedman9bb33f52012-02-03 02:04:35 +000013350
Faisal Valia17d19f2013-11-07 05:17:06 +000013351// If either the type of the variable or the initializer is dependent,
13352// return false. Otherwise, determine whether the variable is a constant
13353// expression. Use this if you need to know if a variable that might or
13354// might not be dependent is truly a constant expression.
13355static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
13356 ASTContext &Context) {
13357
13358 if (Var->getType()->isDependentType())
13359 return false;
Craig Topperc3ec1492014-05-26 06:22:03 +000013360 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +000013361 Var->getAnyInitializer(DefVD);
13362 if (!DefVD)
13363 return false;
13364 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
13365 Expr *Init = cast<Expr>(Eval->Value);
13366 if (Init->isValueDependent())
13367 return false;
13368 return IsVariableAConstantExpression(Var, Context);
Eli Friedman3bda6b12012-02-02 23:15:15 +000013369}
13370
Faisal Valia17d19f2013-11-07 05:17:06 +000013371
Eli Friedman3bda6b12012-02-02 23:15:15 +000013372void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
13373 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
13374 // an object that satisfies the requirements for appearing in a
13375 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
13376 // is immediately applied." This function handles the lvalue-to-rvalue
13377 // conversion part.
13378 MaybeODRUseExprs.erase(E->IgnoreParens());
Faisal Valia17d19f2013-11-07 05:17:06 +000013379
13380 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
13381 // to a variable that is a constant expression, and if so, identify it as
13382 // a reference to a variable that does not involve an odr-use of that
13383 // variable.
13384 if (LambdaScopeInfo *LSI = getCurLambda()) {
13385 Expr *SansParensExpr = E->IgnoreParens();
Craig Topperc3ec1492014-05-26 06:22:03 +000013386 VarDecl *Var = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +000013387 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
13388 Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
13389 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
13390 Var = dyn_cast<VarDecl>(ME->getMemberDecl());
13391
13392 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
13393 LSI->markVariableExprAsNonODRUsed(SansParensExpr);
13394 }
Eli Friedman3bda6b12012-02-02 23:15:15 +000013395}
13396
Eli Friedmanc6237c62012-02-29 03:16:56 +000013397ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
Kaelyn Takatab16e6322014-11-20 22:06:40 +000013398 Res = CorrectDelayedTyposInExpr(Res);
13399
Eli Friedmanc6237c62012-02-29 03:16:56 +000013400 if (!Res.isUsable())
13401 return Res;
13402
13403 // If a constant-expression is a reference to a variable where we delay
13404 // deciding whether it is an odr-use, just assume we will apply the
13405 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
13406 // (a non-type template argument), we have special handling anyway.
13407 UpdateMarkingForLValueToRValue(Res.get());
13408 return Res;
13409}
13410
Eli Friedman3bda6b12012-02-02 23:15:15 +000013411void Sema::CleanupVarDeclMarking() {
13412 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
13413 e = MaybeODRUseExprs.end();
13414 i != e; ++i) {
13415 VarDecl *Var;
13416 SourceLocation Loc;
John McCall113bee02012-03-10 09:33:50 +000013417 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000013418 Var = cast<VarDecl>(DRE->getDecl());
13419 Loc = DRE->getLocation();
13420 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
13421 Var = cast<VarDecl>(ME->getMemberDecl());
13422 Loc = ME->getMemberLoc();
13423 } else {
Larisse Voufo4e673c92014-07-29 18:45:54 +000013424 llvm_unreachable("Unexpected expression");
Eli Friedman3bda6b12012-02-02 23:15:15 +000013425 }
13426
Craig Topperc3ec1492014-05-26 06:22:03 +000013427 MarkVarDeclODRUsed(Var, Loc, *this,
13428 /*MaxFunctionScopeIndex Pointer*/ nullptr);
Eli Friedman3bda6b12012-02-02 23:15:15 +000013429 }
13430
13431 MaybeODRUseExprs.clear();
13432}
13433
Faisal Valia17d19f2013-11-07 05:17:06 +000013434
Eli Friedman3bda6b12012-02-02 23:15:15 +000013435static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
13436 VarDecl *Var, Expr *E) {
Benjamin Kramercd502b52013-11-07 11:03:53 +000013437 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
13438 "Invalid Expr argument to DoMarkVarDeclReferenced");
Eli Friedmanfa0df832012-02-02 03:46:19 +000013439 Var->setReferenced();
13440
Larisse Voufob6fab262014-07-29 18:44:19 +000013441 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
Larisse Voufof73da982014-07-30 00:49:55 +000013442 bool MarkODRUsed = true;
Larisse Voufob6fab262014-07-29 18:44:19 +000013443
Richard Smith5ef98f72014-02-03 23:22:05 +000013444 // If the context is not potentially evaluated, this is not an odr-use and
13445 // does not trigger instantiation.
Faisal Valia17d19f2013-11-07 05:17:06 +000013446 if (!IsPotentiallyEvaluatedContext(SemaRef)) {
Richard Smith5ef98f72014-02-03 23:22:05 +000013447 if (SemaRef.isUnevaluatedContext())
13448 return;
Faisal Valia17d19f2013-11-07 05:17:06 +000013449
Richard Smith5ef98f72014-02-03 23:22:05 +000013450 // If we don't yet know whether this context is going to end up being an
13451 // evaluated context, and we're referencing a variable from an enclosing
13452 // scope, add a potential capture.
13453 //
13454 // FIXME: Is this necessary? These contexts are only used for default
13455 // arguments, where local variables can't be used.
13456 const bool RefersToEnclosingScope =
13457 (SemaRef.CurContext != Var->getDeclContext() &&
Larisse Voufob6fab262014-07-29 18:44:19 +000013458 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
13459 if (RefersToEnclosingScope) {
13460 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
13461 // If a variable could potentially be odr-used, defer marking it so
13462 // until we finish analyzing the full expression for any
13463 // lvalue-to-rvalue
13464 // or discarded value conversions that would obviate odr-use.
13465 // Add it to the list of potential captures that will be analyzed
13466 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
13467 // unless the variable is a reference that was initialized by a constant
13468 // expression (this will never need to be captured or odr-used).
13469 assert(E && "Capture variable should be used in an expression.");
13470 if (!Var->getType()->isReferenceType() ||
13471 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
13472 LSI->addPotentialCapture(E->IgnoreParens());
13473 }
Richard Smith5ef98f72014-02-03 23:22:05 +000013474 }
Larisse Voufob6fab262014-07-29 18:44:19 +000013475
13476 if (!isTemplateInstantiation(TSK))
Craig Topperbd44cd92015-12-08 04:33:04 +000013477 return;
Larisse Voufof73da982014-07-30 00:49:55 +000013478
13479 // Instantiate, but do not mark as odr-used, variable templates.
13480 MarkODRUsed = false;
Faisal Valia17d19f2013-11-07 05:17:06 +000013481 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000013482
Larisse Voufo39a1e502013-08-06 01:03:05 +000013483 VarTemplateSpecializationDecl *VarSpec =
13484 dyn_cast<VarTemplateSpecializationDecl>(Var);
Richard Smith8809a0c2013-09-27 20:14:12 +000013485 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
13486 "Can't instantiate a partial template specialization.");
Larisse Voufo39a1e502013-08-06 01:03:05 +000013487
Richard Smith5ef98f72014-02-03 23:22:05 +000013488 // Perform implicit instantiation of static data members, static data member
13489 // templates of class templates, and variable template specializations. Delay
13490 // instantiations of variable templates, except for those that could be used
13491 // in a constant expression.
Richard Smith8809a0c2013-09-27 20:14:12 +000013492 if (isTemplateInstantiation(TSK)) {
13493 bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
Larisse Voufo39a1e502013-08-06 01:03:05 +000013494
Richard Smith8809a0c2013-09-27 20:14:12 +000013495 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
13496 if (Var->getPointOfInstantiation().isInvalid()) {
13497 // This is a modification of an existing AST node. Notify listeners.
13498 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
13499 L->StaticDataMemberInstantiated(Var);
13500 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
13501 // Don't bother trying to instantiate it again, unless we might need
13502 // its initializer before we get to the end of the TU.
13503 TryInstantiating = false;
Larisse Voufo39a1e502013-08-06 01:03:05 +000013504 }
13505
Richard Smith8809a0c2013-09-27 20:14:12 +000013506 if (Var->getPointOfInstantiation().isInvalid())
13507 Var->setTemplateSpecializationKind(TSK, Loc);
13508
13509 if (TryInstantiating) {
13510 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
Larisse Voufo39a1e502013-08-06 01:03:05 +000013511 bool InstantiationDependent = false;
13512 bool IsNonDependent =
13513 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
13514 VarSpec->getTemplateArgsInfo(), InstantiationDependent)
13515 : true;
13516
13517 // Do not instantiate specializations that are still type-dependent.
13518 if (IsNonDependent) {
13519 if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
13520 // Do not defer instantiations of variables which could be used in a
13521 // constant expression.
13522 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
13523 } else {
13524 SemaRef.PendingInstantiations
13525 .push_back(std::make_pair(Var, PointOfInstantiation));
13526 }
Richard Smithd3cf2382012-02-15 02:42:50 +000013527 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000013528 }
13529 }
Richard Smith5ef98f72014-02-03 23:22:05 +000013530
Larisse Voufof73da982014-07-30 00:49:55 +000013531 if(!MarkODRUsed) return;
13532
Richard Smith5a1104b2012-10-20 01:38:33 +000013533 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
13534 // the requirements for appearing in a constant expression (5.19) and, if
13535 // it is an object, the lvalue-to-rvalue conversion (4.1)
Eli Friedman3bda6b12012-02-02 23:15:15 +000013536 // is immediately applied." We check the first part here, and
13537 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
13538 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith5a1104b2012-10-20 01:38:33 +000013539 // C++03 depends on whether we get the C++03 version correct. The second
13540 // part does not apply to references, since they are not objects.
Faisal Valia17d19f2013-11-07 05:17:06 +000013541 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
Richard Smith5ef98f72014-02-03 23:22:05 +000013542 // A reference initialized by a constant expression can never be
Faisal Valia17d19f2013-11-07 05:17:06 +000013543 // odr-used, so simply ignore it.
Richard Smith5a1104b2012-10-20 01:38:33 +000013544 if (!Var->getType()->isReferenceType())
13545 SemaRef.MaybeODRUseExprs.insert(E);
Richard Smith5ef98f72014-02-03 23:22:05 +000013546 } else
Craig Topperc3ec1492014-05-26 06:22:03 +000013547 MarkVarDeclODRUsed(Var, Loc, SemaRef,
13548 /*MaxFunctionScopeIndex ptr*/ nullptr);
Eli Friedman3bda6b12012-02-02 23:15:15 +000013549}
Eli Friedmanfa0df832012-02-02 03:46:19 +000013550
Eli Friedman3bda6b12012-02-02 23:15:15 +000013551/// \brief Mark a variable referenced, and check whether it is odr-used
13552/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
13553/// used directly for normal expressions referring to VarDecl.
13554void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013555 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
Eli Friedmanfa0df832012-02-02 03:46:19 +000013556}
13557
13558static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
Nick Lewycky45b50522013-02-02 00:25:55 +000013559 Decl *D, Expr *E, bool OdrUse) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000013560 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
13561 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
13562 return;
13563 }
13564
Nick Lewycky45b50522013-02-02 00:25:55 +000013565 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
Rafael Espindola49e860b2012-06-26 17:45:31 +000013566
13567 // If this is a call to a method via a cast, also mark the method in the
13568 // derived class used in case codegen can devirtualize the call.
13569 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13570 if (!ME)
13571 return;
13572 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
13573 if (!MD)
13574 return;
Reid Kleckner5c553e32014-09-16 22:23:33 +000013575 // Only attempt to devirtualize if this is truly a virtual call.
Davide Italianoccb37382015-07-14 23:36:10 +000013576 bool IsVirtualCall = MD->isVirtual() &&
13577 ME->performsVirtualDispatch(SemaRef.getLangOpts());
Reid Kleckner5c553e32014-09-16 22:23:33 +000013578 if (!IsVirtualCall)
13579 return;
Rafael Espindola49e860b2012-06-26 17:45:31 +000013580 const Expr *Base = ME->getBase();
Rafael Espindolab7f5a9c2012-06-27 18:18:05 +000013581 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Rafael Espindola49e860b2012-06-26 17:45:31 +000013582 if (!MostDerivedClassDecl)
13583 return;
13584 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
Nick Lewyckyb7444cd2013-02-14 00:55:17 +000013585 if (!DM || DM->isPure())
Rafael Espindolaa245edc2012-06-27 17:44:39 +000013586 return;
Nick Lewycky45b50522013-02-02 00:25:55 +000013587 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
Douglas Gregord3b672c2012-02-16 01:06:16 +000013588}
Eli Friedmanfa0df832012-02-02 03:46:19 +000013589
Eli Friedmanfa0df832012-02-02 03:46:19 +000013590/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
13591void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
Nick Lewycky45b50522013-02-02 00:25:55 +000013592 // TODO: update this with DR# once a defect report is filed.
13593 // C++11 defect. The address of a pure member should not be an ODR use, even
13594 // if it's a qualified reference.
13595 bool OdrUse = true;
13596 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
Nick Lewycky192542c2013-02-05 06:20:31 +000013597 if (Method->isVirtual())
Nick Lewycky45b50522013-02-02 00:25:55 +000013598 OdrUse = false;
13599 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
Eli Friedmanfa0df832012-02-02 03:46:19 +000013600}
13601
13602/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
13603void Sema::MarkMemberReferenced(MemberExpr *E) {
Nick Lewycky60bd4be2013-01-31 03:15:20 +000013604 // C++11 [basic.def.odr]p2:
Nick Lewycky35d23592013-01-31 01:34:31 +000013605 // A non-overloaded function whose name appears as a potentially-evaluated
13606 // expression or a member of a set of candidate functions, if selected by
13607 // overload resolution when referred to from a potentially-evaluated
13608 // expression, is odr-used, unless it is a pure virtual function and its
13609 // name is not explicitly qualified.
Nick Lewycky45b50522013-02-02 00:25:55 +000013610 bool OdrUse = true;
Davide Italianoccb37382015-07-14 23:36:10 +000013611 if (E->performsVirtualDispatch(getLangOpts())) {
Nick Lewycky35d23592013-01-31 01:34:31 +000013612 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
13613 if (Method->isPure())
Nick Lewycky45b50522013-02-02 00:25:55 +000013614 OdrUse = false;
Nick Lewycky35d23592013-01-31 01:34:31 +000013615 }
Nick Lewyckya096b142013-02-12 08:08:54 +000013616 SourceLocation Loc = E->getMemberLoc().isValid() ?
13617 E->getMemberLoc() : E->getLocStart();
13618 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
Eli Friedmanfa0df832012-02-02 03:46:19 +000013619}
13620
Douglas Gregorf02455e2012-02-10 09:26:04 +000013621/// \brief Perform marking for a reference to an arbitrary declaration. It
Nico Weber83ea0122014-05-03 21:57:40 +000013622/// marks the declaration referenced, and performs odr-use checking for
13623/// functions and variables. This method should not be used when building a
13624/// normal expression which refers to a variable.
Nick Lewycky45b50522013-02-02 00:25:55 +000013625void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
13626 if (OdrUse) {
Nico Weber8bf410f2014-08-27 17:04:39 +000013627 if (auto *VD = dyn_cast<VarDecl>(D)) {
Nick Lewycky45b50522013-02-02 00:25:55 +000013628 MarkVariableReferenced(Loc, VD);
13629 return;
13630 }
Nico Weber8bf410f2014-08-27 17:04:39 +000013631 }
13632 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
13633 MarkFunctionReferenced(Loc, FD, OdrUse);
13634 return;
Nick Lewycky45b50522013-02-02 00:25:55 +000013635 }
13636 D->setReferenced();
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000013637}
Anders Carlsson7f84ed92009-10-09 23:51:55 +000013638
Douglas Gregor5597ab42010-05-07 23:12:07 +000013639namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +000013640 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +000013641 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +000013642 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +000013643 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
13644 Sema &S;
13645 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +000013646
Douglas Gregor5597ab42010-05-07 23:12:07 +000013647 public:
13648 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +000013649
Douglas Gregor5597ab42010-05-07 23:12:07 +000013650 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +000013651
13652 bool TraverseTemplateArgument(const TemplateArgument &Arg);
13653 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +000013654 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000013655}
Douglas Gregor5597ab42010-05-07 23:12:07 +000013656
Chandler Carruthaf80f662010-06-09 08:17:30 +000013657bool MarkReferencedDecls::TraverseTemplateArgument(
Nico Weber83ea0122014-05-03 21:57:40 +000013658 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000013659 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +000013660 if (Decl *D = Arg.getAsDecl())
Nick Lewycky45b50522013-02-02 00:25:55 +000013661 S.MarkAnyDeclReferenced(Loc, D, true);
Douglas Gregor5597ab42010-05-07 23:12:07 +000013662 }
Chandler Carruthaf80f662010-06-09 08:17:30 +000013663
13664 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +000013665}
13666
Chandler Carruthaf80f662010-06-09 08:17:30 +000013667bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000013668 if (ClassTemplateSpecializationDecl *Spec
13669 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
13670 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +000013671 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +000013672 }
13673
Chandler Carruthc65667c2010-06-10 10:31:57 +000013674 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +000013675}
13676
13677void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
13678 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +000013679 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +000013680}
13681
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000013682namespace {
13683 /// \brief Helper class that marks all of the declarations referenced by
13684 /// potentially-evaluated subexpressions as "referenced".
13685 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
13686 Sema &S;
Douglas Gregor680e9e02012-02-21 19:11:17 +000013687 bool SkipLocalVariables;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000013688
13689 public:
13690 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
13691
Douglas Gregor680e9e02012-02-21 19:11:17 +000013692 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
13693 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000013694
13695 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregor680e9e02012-02-21 19:11:17 +000013696 // If we were asked not to visit local variables, don't.
13697 if (SkipLocalVariables) {
13698 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
13699 if (VD->hasLocalStorage())
13700 return;
13701 }
13702
Eli Friedmanfa0df832012-02-02 03:46:19 +000013703 S.MarkDeclRefReferenced(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000013704 }
Nico Weber83ea0122014-05-03 21:57:40 +000013705
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000013706 void VisitMemberExpr(MemberExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000013707 S.MarkMemberReferenced(E);
Douglas Gregor32b3de52010-09-11 23:32:50 +000013708 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000013709 }
13710
John McCall28fc7092011-11-10 05:35:25 +000013711 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000013712 S.MarkFunctionReferenced(E->getLocStart(),
John McCall28fc7092011-11-10 05:35:25 +000013713 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
13714 Visit(E->getSubExpr());
13715 }
13716
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000013717 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000013718 if (E->getOperatorNew())
Eli Friedmanfa0df832012-02-02 03:46:19 +000013719 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000013720 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000013721 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +000013722 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000013723 }
Sebastian Redl6047f072012-02-16 12:22:20 +000013724
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000013725 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
13726 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000013727 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000013728 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
13729 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
13730 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedmanfa0df832012-02-02 03:46:19 +000013731 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000013732 S.LookupDestructor(Record));
13733 }
13734
Douglas Gregor32b3de52010-09-11 23:32:50 +000013735 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000013736 }
13737
13738 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000013739 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +000013740 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000013741 }
13742
Douglas Gregorf0873f42010-10-19 17:17:35 +000013743 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
13744 Visit(E->getExpr());
13745 }
Eli Friedman3bda6b12012-02-02 23:15:15 +000013746
13747 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13748 Inherited::VisitImplicitCastExpr(E);
13749
13750 if (E->getCastKind() == CK_LValueToRValue)
13751 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
13752 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000013753 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000013754}
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000013755
13756/// \brief Mark any declarations that appear within this expression or any
13757/// potentially-evaluated subexpressions as "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +000013758///
13759/// \param SkipLocalVariables If true, don't mark local variables as
13760/// 'referenced'.
13761void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
13762 bool SkipLocalVariables) {
13763 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000013764}
13765
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000013766/// \brief Emit a diagnostic that describes an effect on the run-time behavior
13767/// of the program being compiled.
13768///
13769/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000013770/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000013771/// possibility that the code will actually be executable. Code in sizeof()
13772/// expressions, code used only during overload resolution, etc., are not
13773/// potentially evaluated. This routine will suppress such diagnostics or,
13774/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000013775/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000013776/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000013777///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000013778/// This routine should be used for all diagnostics that describe the run-time
13779/// behavior of a program, such as passing a non-POD value through an ellipsis.
13780/// Failure to do so will likely result in spurious diagnostics or failures
13781/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuba63ce62011-09-09 01:45:06 +000013782bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000013783 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +000013784 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000013785 case Unevaluated:
John McCallf413f5e2013-05-03 00:10:13 +000013786 case UnevaluatedAbstract:
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000013787 // The argument will never be evaluated, so don't complain.
13788 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000013789
Richard Smith764d2fe2011-12-20 02:08:33 +000013790 case ConstantEvaluated:
13791 // Relevant diagnostics should be produced by constant evaluation.
13792 break;
13793
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000013794 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000013795 case PotentiallyEvaluatedIfUsed:
Richard Trieuba63ce62011-09-09 01:45:06 +000013796 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +000013797 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuba63ce62011-09-09 01:45:06 +000013798 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek3427fac2011-02-23 01:52:04 +000013799 }
13800 else
13801 Diag(Loc, PD);
13802
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000013803 return true;
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000013804 }
13805
13806 return false;
13807}
13808
Anders Carlsson7f84ed92009-10-09 23:51:55 +000013809bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
13810 CallExpr *CE, FunctionDecl *FD) {
13811 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
13812 return false;
13813
Richard Smithfd555f62012-02-22 02:04:18 +000013814 // If we're inside a decltype's expression, don't check for a valid return
13815 // type or construct temporaries until we know whether this is the last call.
13816 if (ExprEvalContexts.back().IsDecltype) {
13817 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
13818 return false;
13819 }
13820
Douglas Gregora6c5abb2012-05-04 16:48:41 +000013821 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000013822 FunctionDecl *FD;
13823 CallExpr *CE;
13824
13825 public:
13826 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
13827 : FD(FD), CE(CE) { }
Craig Toppere14c0f82014-03-12 04:55:44 +000013828
13829 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000013830 if (!FD) {
13831 S.Diag(Loc, diag::err_call_incomplete_return)
13832 << T << CE->getSourceRange();
13833 return;
13834 }
13835
13836 S.Diag(Loc, diag::err_call_function_incomplete_return)
13837 << CE->getSourceRange() << FD->getDeclName() << T;
Alp Toker2afa8782014-05-28 12:20:14 +000013838 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
13839 << FD->getDeclName();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000013840 }
13841 } Diagnoser(FD, CE);
13842
13843 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson7f84ed92009-10-09 23:51:55 +000013844 return true;
13845
13846 return false;
13847}
13848
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000013849// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000013850// will prevent this condition from triggering, which is what we want.
13851void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
13852 SourceLocation Loc;
13853
John McCall0506e4a2009-11-11 02:41:58 +000013854 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000013855 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000013856
Chandler Carruthf87d6c02011-08-16 22:30:10 +000013857 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000013858 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000013859 return;
13860
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000013861 IsOrAssign = Op->getOpcode() == BO_OrAssign;
13862
John McCallb0e419e2009-11-12 00:06:05 +000013863 // Greylist some idioms by putting them into a warning subcategory.
13864 if (ObjCMessageExpr *ME
13865 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
13866 Selector Sel = ME->getSelector();
13867
John McCallb0e419e2009-11-12 00:06:05 +000013868 // self = [<foo> init...]
Jean-Daniel Dupas39655742013-07-17 18:17:14 +000013869 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
John McCallb0e419e2009-11-12 00:06:05 +000013870 diagnostic = diag::warn_condition_is_idiomatic_assignment;
13871
13872 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000013873 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000013874 diagnostic = diag::warn_condition_is_idiomatic_assignment;
13875 }
John McCall0506e4a2009-11-11 02:41:58 +000013876
John McCalld5707ab2009-10-12 21:59:07 +000013877 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +000013878 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000013879 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000013880 return;
13881
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000013882 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000013883 Loc = Op->getOperatorLoc();
Fariborz Jahanianf07bcc52012-08-29 17:17:11 +000013884 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
13885 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
13886 else {
John McCalld5707ab2009-10-12 21:59:07 +000013887 // Not an assignment.
13888 return;
13889 }
13890
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000013891 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000013892
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013893 SourceLocation Open = E->getLocStart();
Craig Topper07fa1762015-11-15 02:31:46 +000013894 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000013895 Diag(Loc, diag::note_condition_assign_silence)
13896 << FixItHint::CreateInsertion(Open, "(")
13897 << FixItHint::CreateInsertion(Close, ")");
13898
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000013899 if (IsOrAssign)
13900 Diag(Loc, diag::note_condition_or_assign_to_comparison)
13901 << FixItHint::CreateReplacement(Loc, "!=");
13902 else
13903 Diag(Loc, diag::note_condition_assign_to_comparison)
13904 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +000013905}
13906
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000013907/// \brief Redundant parentheses over an equality comparison can indicate
13908/// that the user intended an assignment used as condition.
Richard Trieuba63ce62011-09-09 01:45:06 +000013909void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000013910 // Don't warn if the parens came from a macro.
Richard Trieuba63ce62011-09-09 01:45:06 +000013911 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000013912 if (parenLoc.isInvalid() || parenLoc.isMacroID())
13913 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000013914 // Don't warn for dependent expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +000013915 if (ParenE->isTypeDependent())
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000013916 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000013917
Richard Trieuba63ce62011-09-09 01:45:06 +000013918 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000013919
13920 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000013921 if (opE->getOpcode() == BO_EQ &&
13922 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
13923 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000013924 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000013925
Ted Kremenekae022092011-02-02 02:20:30 +000013926 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013927 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +000013928 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013929 << FixItHint::CreateRemoval(ParenERange.getBegin())
13930 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000013931 Diag(Loc, diag::note_equality_comparison_to_assign)
13932 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000013933 }
13934}
13935
John Wiegley01296292011-04-08 18:41:53 +000013936ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +000013937 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000013938 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
13939 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000013940
John McCall0009fcc2011-04-26 20:42:42 +000013941 ExprResult result = CheckPlaceholderExpr(E);
13942 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013943 E = result.get();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000013944
John McCall0009fcc2011-04-26 20:42:42 +000013945 if (!E->isTypeDependent()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000013946 if (getLangOpts().CPlusPlus)
John McCall34376a62010-12-04 03:47:34 +000013947 return CheckCXXBooleanCondition(E); // C++ 6.4p4
13948
John Wiegley01296292011-04-08 18:41:53 +000013949 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
13950 if (ERes.isInvalid())
13951 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013952 E = ERes.get();
John McCall29cb2fd2010-12-04 06:09:13 +000013953
13954 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000013955 if (!T->isScalarType()) { // C99 6.8.4.1p1
13956 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
13957 << T << E->getSourceRange();
13958 return ExprError();
13959 }
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000013960 CheckBoolLikeConversion(E, Loc);
John McCalld5707ab2009-10-12 21:59:07 +000013961 }
13962
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013963 return E;
John McCalld5707ab2009-10-12 21:59:07 +000013964}
Douglas Gregore60e41a2010-05-06 17:25:47 +000013965
John McCalldadc5752010-08-24 06:29:42 +000013966ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +000013967 Expr *SubExpr) {
13968 if (!SubExpr)
Douglas Gregore60e41a2010-05-06 17:25:47 +000013969 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000013970
Richard Trieuba63ce62011-09-09 01:45:06 +000013971 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +000013972}
John McCall36e7fe32010-10-12 00:20:44 +000013973
John McCall31996342011-04-07 08:22:57 +000013974namespace {
John McCall2979fe02011-04-12 00:42:48 +000013975 /// A visitor for rebuilding a call to an __unknown_any expression
13976 /// to have an appropriate type.
13977 struct RebuildUnknownAnyFunction
13978 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
13979
13980 Sema &S;
13981
13982 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
13983
13984 ExprResult VisitStmt(Stmt *S) {
13985 llvm_unreachable("unexpected statement!");
John McCall2979fe02011-04-12 00:42:48 +000013986 }
13987
Richard Trieu10162ab2011-09-09 03:59:41 +000013988 ExprResult VisitExpr(Expr *E) {
13989 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
13990 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000013991 return ExprError();
13992 }
13993
13994 /// Rebuild an expression which simply semantically wraps another
13995 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000013996 template <class T> ExprResult rebuildSugarExpr(T *E) {
13997 ExprResult SubResult = Visit(E->getSubExpr());
13998 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000013999
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014000 Expr *SubExpr = SubResult.get();
Richard Trieu10162ab2011-09-09 03:59:41 +000014001 E->setSubExpr(SubExpr);
14002 E->setType(SubExpr->getType());
14003 E->setValueKind(SubExpr->getValueKind());
14004 assert(E->getObjectKind() == OK_Ordinary);
14005 return E;
John McCall2979fe02011-04-12 00:42:48 +000014006 }
14007
Richard Trieu10162ab2011-09-09 03:59:41 +000014008 ExprResult VisitParenExpr(ParenExpr *E) {
14009 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000014010 }
14011
Richard Trieu10162ab2011-09-09 03:59:41 +000014012 ExprResult VisitUnaryExtension(UnaryOperator *E) {
14013 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000014014 }
14015
Richard Trieu10162ab2011-09-09 03:59:41 +000014016 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14017 ExprResult SubResult = Visit(E->getSubExpr());
14018 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000014019
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014020 Expr *SubExpr = SubResult.get();
Richard Trieu10162ab2011-09-09 03:59:41 +000014021 E->setSubExpr(SubExpr);
14022 E->setType(S.Context.getPointerType(SubExpr->getType()));
14023 assert(E->getValueKind() == VK_RValue);
14024 assert(E->getObjectKind() == OK_Ordinary);
14025 return E;
John McCall2979fe02011-04-12 00:42:48 +000014026 }
14027
Richard Trieu10162ab2011-09-09 03:59:41 +000014028 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14029 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000014030
Richard Trieu10162ab2011-09-09 03:59:41 +000014031 E->setType(VD->getType());
John McCall2979fe02011-04-12 00:42:48 +000014032
Richard Trieu10162ab2011-09-09 03:59:41 +000014033 assert(E->getValueKind() == VK_RValue);
David Blaikiebbafb8a2012-03-11 07:00:24 +000014034 if (S.getLangOpts().CPlusPlus &&
Richard Trieu10162ab2011-09-09 03:59:41 +000014035 !(isa<CXXMethodDecl>(VD) &&
14036 cast<CXXMethodDecl>(VD)->isInstance()))
14037 E->setValueKind(VK_LValue);
John McCall2979fe02011-04-12 00:42:48 +000014038
Richard Trieu10162ab2011-09-09 03:59:41 +000014039 return E;
John McCall2979fe02011-04-12 00:42:48 +000014040 }
14041
Richard Trieu10162ab2011-09-09 03:59:41 +000014042 ExprResult VisitMemberExpr(MemberExpr *E) {
14043 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000014044 }
14045
Richard Trieu10162ab2011-09-09 03:59:41 +000014046 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14047 return resolveDecl(E, E->getDecl());
John McCall2979fe02011-04-12 00:42:48 +000014048 }
14049 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000014050}
John McCall2979fe02011-04-12 00:42:48 +000014051
14052/// Given a function expression of unknown-any type, try to rebuild it
14053/// to have a function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000014054static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14055 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14056 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014057 return S.DefaultFunctionArrayConversion(Result.get());
John McCall2979fe02011-04-12 00:42:48 +000014058}
14059
14060namespace {
John McCall2d2e8702011-04-11 07:02:50 +000014061 /// A visitor for rebuilding an expression of type __unknown_anytype
14062 /// into one which resolves the type directly on the referring
14063 /// expression. Strict preservation of the original source
14064 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +000014065 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +000014066 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +000014067
14068 Sema &S;
14069
14070 /// The current destination type.
14071 QualType DestType;
14072
Richard Trieu10162ab2011-09-09 03:59:41 +000014073 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14074 : S(S), DestType(CastType) {}
John McCall31996342011-04-07 08:22:57 +000014075
John McCall39439732011-04-09 22:50:59 +000014076 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +000014077 llvm_unreachable("unexpected statement!");
John McCall31996342011-04-07 08:22:57 +000014078 }
14079
Richard Trieu10162ab2011-09-09 03:59:41 +000014080 ExprResult VisitExpr(Expr *E) {
14081 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14082 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000014083 return ExprError();
John McCall31996342011-04-07 08:22:57 +000014084 }
14085
Richard Trieu10162ab2011-09-09 03:59:41 +000014086 ExprResult VisitCallExpr(CallExpr *E);
14087 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall2d2e8702011-04-11 07:02:50 +000014088
John McCall39439732011-04-09 22:50:59 +000014089 /// Rebuild an expression which simply semantically wraps another
14090 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000014091 template <class T> ExprResult rebuildSugarExpr(T *E) {
14092 ExprResult SubResult = Visit(E->getSubExpr());
14093 if (SubResult.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014094 Expr *SubExpr = SubResult.get();
Richard Trieu10162ab2011-09-09 03:59:41 +000014095 E->setSubExpr(SubExpr);
14096 E->setType(SubExpr->getType());
14097 E->setValueKind(SubExpr->getValueKind());
14098 assert(E->getObjectKind() == OK_Ordinary);
14099 return E;
John McCall39439732011-04-09 22:50:59 +000014100 }
John McCall31996342011-04-07 08:22:57 +000014101
Richard Trieu10162ab2011-09-09 03:59:41 +000014102 ExprResult VisitParenExpr(ParenExpr *E) {
14103 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000014104 }
14105
Richard Trieu10162ab2011-09-09 03:59:41 +000014106 ExprResult VisitUnaryExtension(UnaryOperator *E) {
14107 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000014108 }
14109
Richard Trieu10162ab2011-09-09 03:59:41 +000014110 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14111 const PointerType *Ptr = DestType->getAs<PointerType>();
14112 if (!Ptr) {
14113 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14114 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000014115 return ExprError();
14116 }
Richard Trieu10162ab2011-09-09 03:59:41 +000014117 assert(E->getValueKind() == VK_RValue);
14118 assert(E->getObjectKind() == OK_Ordinary);
14119 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +000014120
14121 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu10162ab2011-09-09 03:59:41 +000014122 DestType = Ptr->getPointeeType();
14123 ExprResult SubResult = Visit(E->getSubExpr());
14124 if (SubResult.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014125 E->setSubExpr(SubResult.get());
Richard Trieu10162ab2011-09-09 03:59:41 +000014126 return E;
John McCall2979fe02011-04-12 00:42:48 +000014127 }
14128
Richard Trieu10162ab2011-09-09 03:59:41 +000014129 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCall39439732011-04-09 22:50:59 +000014130
Richard Trieu10162ab2011-09-09 03:59:41 +000014131 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCall39439732011-04-09 22:50:59 +000014132
Richard Trieu10162ab2011-09-09 03:59:41 +000014133 ExprResult VisitMemberExpr(MemberExpr *E) {
14134 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000014135 }
John McCall39439732011-04-09 22:50:59 +000014136
Richard Trieu10162ab2011-09-09 03:59:41 +000014137 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14138 return resolveDecl(E, E->getDecl());
John McCall31996342011-04-07 08:22:57 +000014139 }
14140 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000014141}
John McCall31996342011-04-07 08:22:57 +000014142
John McCall2d2e8702011-04-11 07:02:50 +000014143/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu10162ab2011-09-09 03:59:41 +000014144ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
14145 Expr *CalleeExpr = E->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000014146
14147 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +000014148 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +000014149 FK_FunctionPointer,
14150 FK_BlockPointer
14151 };
14152
Richard Trieu10162ab2011-09-09 03:59:41 +000014153 FnKind Kind;
14154 QualType CalleeType = CalleeExpr->getType();
14155 if (CalleeType == S.Context.BoundMemberTy) {
14156 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
14157 Kind = FK_MemberFunction;
14158 CalleeType = Expr::findBoundMemberType(CalleeExpr);
14159 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
14160 CalleeType = Ptr->getPointeeType();
14161 Kind = FK_FunctionPointer;
John McCall2d2e8702011-04-11 07:02:50 +000014162 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000014163 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
14164 Kind = FK_BlockPointer;
John McCall2d2e8702011-04-11 07:02:50 +000014165 }
Richard Trieu10162ab2011-09-09 03:59:41 +000014166 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall2d2e8702011-04-11 07:02:50 +000014167
14168 // Verify that this is a legal result type of a function.
14169 if (DestType->isArrayType() || DestType->isFunctionType()) {
14170 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu10162ab2011-09-09 03:59:41 +000014171 if (Kind == FK_BlockPointer)
John McCall2d2e8702011-04-11 07:02:50 +000014172 diagID = diag::err_block_returning_array_function;
14173
Richard Trieu10162ab2011-09-09 03:59:41 +000014174 S.Diag(E->getExprLoc(), diagID)
John McCall2d2e8702011-04-11 07:02:50 +000014175 << DestType->isFunctionType() << DestType;
14176 return ExprError();
14177 }
14178
14179 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu10162ab2011-09-09 03:59:41 +000014180 E->setType(DestType.getNonLValueExprType(S.Context));
14181 E->setValueKind(Expr::getValueKindForType(DestType));
14182 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000014183
14184 // Rebuild the function type, replacing the result type with DestType.
John McCall611d9b62013-06-27 22:43:24 +000014185 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
14186 if (Proto) {
14187 // __unknown_anytype(...) is a special case used by the debugger when
14188 // it has no idea what a function's signature is.
14189 //
14190 // We want to build this call essentially under the K&R
14191 // unprototyped rules, but making a FunctionNoProtoType in C++
14192 // would foul up all sorts of assumptions. However, we cannot
14193 // simply pass all arguments as variadic arguments, nor can we
14194 // portably just call the function under a non-variadic type; see
14195 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
14196 // However, it turns out that in practice it is generally safe to
14197 // call a function declared as "A foo(B,C,D);" under the prototype
14198 // "A foo(B,C,D,...);". The only known exception is with the
14199 // Windows ABI, where any variadic function is implicitly cdecl
14200 // regardless of its normal CC. Therefore we change the parameter
14201 // types to match the types of the arguments.
14202 //
14203 // This is a hack, but it is far superior to moving the
14204 // corresponding target-specific code from IR-gen to Sema/AST.
14205
Alp Toker9cacbab2014-01-20 20:26:09 +000014206 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
John McCall611d9b62013-06-27 22:43:24 +000014207 SmallVector<QualType, 8> ArgTypes;
14208 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
14209 ArgTypes.reserve(E->getNumArgs());
14210 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
14211 Expr *Arg = E->getArg(i);
14212 QualType ArgType = Arg->getType();
14213 if (E->isLValue()) {
14214 ArgType = S.Context.getLValueReferenceType(ArgType);
14215 } else if (E->isXValue()) {
14216 ArgType = S.Context.getRValueReferenceType(ArgType);
14217 }
14218 ArgTypes.push_back(ArgType);
14219 }
14220 ParamTypes = ArgTypes;
14221 }
14222 DestType = S.Context.getFunctionType(DestType, ParamTypes,
Reid Kleckner896b32f2013-06-10 20:51:09 +000014223 Proto->getExtProtoInfo());
John McCall611d9b62013-06-27 22:43:24 +000014224 } else {
John McCall2d2e8702011-04-11 07:02:50 +000014225 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000014226 FnType->getExtInfo());
John McCall611d9b62013-06-27 22:43:24 +000014227 }
John McCall2d2e8702011-04-11 07:02:50 +000014228
14229 // Rebuild the appropriate pointer-to-function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000014230 switch (Kind) {
John McCall4adb38c2011-04-27 00:36:17 +000014231 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +000014232 // Nothing to do.
14233 break;
14234
14235 case FK_FunctionPointer:
14236 DestType = S.Context.getPointerType(DestType);
14237 break;
14238
14239 case FK_BlockPointer:
14240 DestType = S.Context.getBlockPointerType(DestType);
14241 break;
14242 }
14243
14244 // Finally, we can recurse.
Richard Trieu10162ab2011-09-09 03:59:41 +000014245 ExprResult CalleeResult = Visit(CalleeExpr);
14246 if (!CalleeResult.isUsable()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014247 E->setCallee(CalleeResult.get());
John McCall2d2e8702011-04-11 07:02:50 +000014248
14249 // Bind a temporary if necessary.
Richard Trieu10162ab2011-09-09 03:59:41 +000014250 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000014251}
14252
Richard Trieu10162ab2011-09-09 03:59:41 +000014253ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000014254 // Verify that this is a legal result type of a call.
14255 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu10162ab2011-09-09 03:59:41 +000014256 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall2979fe02011-04-12 00:42:48 +000014257 << DestType->isFunctionType() << DestType;
14258 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000014259 }
14260
John McCall3f4138c2011-07-13 17:56:40 +000014261 // Rewrite the method result type if available.
Richard Trieu10162ab2011-09-09 03:59:41 +000014262 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +000014263 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
14264 Method->setReturnType(DestType);
John McCall3f4138c2011-07-13 17:56:40 +000014265 }
John McCall2979fe02011-04-12 00:42:48 +000014266
John McCall2d2e8702011-04-11 07:02:50 +000014267 // Change the type of the message.
Richard Trieu10162ab2011-09-09 03:59:41 +000014268 E->setType(DestType.getNonReferenceType());
14269 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000014270
Richard Trieu10162ab2011-09-09 03:59:41 +000014271 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000014272}
14273
Richard Trieu10162ab2011-09-09 03:59:41 +000014274ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000014275 // The only case we should ever see here is a function-to-pointer decay.
Sean Callanan2db103c2012-03-06 23:12:57 +000014276 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanan12495112012-03-06 21:34:12 +000014277 assert(E->getValueKind() == VK_RValue);
14278 assert(E->getObjectKind() == OK_Ordinary);
14279
14280 E->setType(DestType);
14281
14282 // Rebuild the sub-expression as the pointee (function) type.
14283 DestType = DestType->castAs<PointerType>()->getPointeeType();
14284
14285 ExprResult Result = Visit(E->getSubExpr());
14286 if (!Result.isUsable()) return ExprError();
14287
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014288 E->setSubExpr(Result.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000014289 return E;
Sean Callanan2db103c2012-03-06 23:12:57 +000014290 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanan12495112012-03-06 21:34:12 +000014291 assert(E->getValueKind() == VK_RValue);
14292 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000014293
Sean Callanan12495112012-03-06 21:34:12 +000014294 assert(isa<BlockPointerType>(E->getType()));
John McCall2979fe02011-04-12 00:42:48 +000014295
Sean Callanan12495112012-03-06 21:34:12 +000014296 E->setType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000014297
Sean Callanan12495112012-03-06 21:34:12 +000014298 // The sub-expression has to be a lvalue reference, so rebuild it as such.
14299 DestType = S.Context.getLValueReferenceType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000014300
Sean Callanan12495112012-03-06 21:34:12 +000014301 ExprResult Result = Visit(E->getSubExpr());
14302 if (!Result.isUsable()) return ExprError();
14303
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014304 E->setSubExpr(Result.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000014305 return E;
Sean Callanan2db103c2012-03-06 23:12:57 +000014306 } else {
Sean Callanan12495112012-03-06 21:34:12 +000014307 llvm_unreachable("Unhandled cast type!");
14308 }
John McCall2d2e8702011-04-11 07:02:50 +000014309}
14310
Richard Trieu10162ab2011-09-09 03:59:41 +000014311ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
14312 ExprValueKind ValueKind = VK_LValue;
14313 QualType Type = DestType;
John McCall2d2e8702011-04-11 07:02:50 +000014314
14315 // We know how to make this work for certain kinds of decls:
14316
14317 // - functions
Richard Trieu10162ab2011-09-09 03:59:41 +000014318 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
14319 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
14320 DestType = Ptr->getPointeeType();
14321 ExprResult Result = resolveDecl(E, VD);
14322 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014323 return S.ImpCastExprToType(Result.get(), Type,
John McCall9a877fe2011-08-10 04:12:23 +000014324 CK_FunctionToPointerDecay, VK_RValue);
14325 }
14326
Richard Trieu10162ab2011-09-09 03:59:41 +000014327 if (!Type->isFunctionType()) {
14328 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
14329 << VD << E->getSourceRange();
John McCall9a877fe2011-08-10 04:12:23 +000014330 return ExprError();
14331 }
Fariborz Jahaniana29986c2014-11-11 16:56:21 +000014332 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
14333 // We must match the FunctionDecl's type to the hack introduced in
14334 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
14335 // type. See the lengthy commentary in that routine.
14336 QualType FDT = FD->getType();
14337 const FunctionType *FnType = FDT->castAs<FunctionType>();
14338 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
14339 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14340 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
14341 SourceLocation Loc = FD->getLocation();
14342 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
14343 FD->getDeclContext(),
14344 Loc, Loc, FD->getNameInfo().getName(),
14345 DestType, FD->getTypeSourceInfo(),
14346 SC_None, false/*isInlineSpecified*/,
14347 FD->hasPrototype(),
14348 false/*isConstexprSpecified*/);
14349
14350 if (FD->getQualifier())
14351 NewFD->setQualifierInfo(FD->getQualifierLoc());
14352
14353 SmallVector<ParmVarDecl*, 16> Params;
14354 for (const auto &AI : FT->param_types()) {
14355 ParmVarDecl *Param =
14356 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
14357 Param->setScopeInfo(0, Params.size());
14358 Params.push_back(Param);
14359 }
14360 NewFD->setParams(Params);
14361 DRE->setDecl(NewFD);
14362 VD = DRE->getDecl();
14363 }
14364 }
John McCall2d2e8702011-04-11 07:02:50 +000014365
Richard Trieu10162ab2011-09-09 03:59:41 +000014366 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
14367 if (MD->isInstance()) {
14368 ValueKind = VK_RValue;
14369 Type = S.Context.BoundMemberTy;
John McCall4adb38c2011-04-27 00:36:17 +000014370 }
14371
John McCall2d2e8702011-04-11 07:02:50 +000014372 // Function references aren't l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000014373 if (!S.getLangOpts().CPlusPlus)
Richard Trieu10162ab2011-09-09 03:59:41 +000014374 ValueKind = VK_RValue;
John McCall2d2e8702011-04-11 07:02:50 +000014375
14376 // - variables
Richard Trieu10162ab2011-09-09 03:59:41 +000014377 } else if (isa<VarDecl>(VD)) {
14378 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
14379 Type = RefTy->getPointeeType();
14380 } else if (Type->isFunctionType()) {
14381 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
14382 << VD << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000014383 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000014384 }
14385
14386 // - nothing else
14387 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000014388 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
14389 << VD << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000014390 return ExprError();
14391 }
14392
John McCall611d9b62013-06-27 22:43:24 +000014393 // Modifying the declaration like this is friendly to IR-gen but
14394 // also really dangerous.
Richard Trieu10162ab2011-09-09 03:59:41 +000014395 VD->setType(DestType);
14396 E->setType(Type);
14397 E->setValueKind(ValueKind);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000014398 return E;
John McCall2d2e8702011-04-11 07:02:50 +000014399}
14400
John McCall31996342011-04-07 08:22:57 +000014401/// Check a cast of an unknown-any type. We intentionally only
14402/// trigger this for C-style casts.
Richard Trieuba63ce62011-09-09 01:45:06 +000014403ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
14404 Expr *CastExpr, CastKind &CastKind,
14405 ExprValueKind &VK, CXXCastPath &Path) {
John McCall31996342011-04-07 08:22:57 +000014406 // Rewrite the casted expression from scratch.
Richard Trieuba63ce62011-09-09 01:45:06 +000014407 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCall39439732011-04-09 22:50:59 +000014408 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000014409
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014410 CastExpr = result.get();
Richard Trieuba63ce62011-09-09 01:45:06 +000014411 VK = CastExpr->getValueKind();
14412 CastKind = CK_NoOp;
John McCall39439732011-04-09 22:50:59 +000014413
Richard Trieuba63ce62011-09-09 01:45:06 +000014414 return CastExpr;
John McCall31996342011-04-07 08:22:57 +000014415}
14416
Douglas Gregord8fb1e32011-12-01 01:37:36 +000014417ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
14418 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
14419}
14420
John McCallcc5788c2013-03-04 07:34:02 +000014421ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
14422 Expr *arg, QualType &paramType) {
14423 // If the syntactic form of the argument is not an explicit cast of
14424 // any sort, just do default argument promotion.
14425 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
14426 if (!castArg) {
14427 ExprResult result = DefaultArgumentPromotion(arg);
14428 if (result.isInvalid()) return ExprError();
14429 paramType = result.get()->getType();
14430 return result;
John McCallea0a39e2012-11-14 00:49:39 +000014431 }
14432
John McCallcc5788c2013-03-04 07:34:02 +000014433 // Otherwise, use the type that was written in the explicit cast.
14434 assert(!arg->hasPlaceholderType());
14435 paramType = castArg->getTypeAsWritten();
14436
14437 // Copy-initialize a parameter of that type.
14438 InitializedEntity entity =
14439 InitializedEntity::InitializeParameter(Context, paramType,
14440 /*consumed*/ false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000014441 return PerformCopyInitialization(entity, callLoc, arg);
John McCallea0a39e2012-11-14 00:49:39 +000014442}
14443
Richard Trieuba63ce62011-09-09 01:45:06 +000014444static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
14445 Expr *orig = E;
John McCall2d2e8702011-04-11 07:02:50 +000014446 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000014447 while (true) {
Richard Trieuba63ce62011-09-09 01:45:06 +000014448 E = E->IgnoreParenImpCasts();
14449 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
14450 E = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000014451 diagID = diag::err_uncasted_call_of_unknown_any;
14452 } else {
John McCall31996342011-04-07 08:22:57 +000014453 break;
John McCall2d2e8702011-04-11 07:02:50 +000014454 }
John McCall31996342011-04-07 08:22:57 +000014455 }
14456
John McCall2d2e8702011-04-11 07:02:50 +000014457 SourceLocation loc;
14458 NamedDecl *d;
Richard Trieuba63ce62011-09-09 01:45:06 +000014459 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000014460 loc = ref->getLocation();
14461 d = ref->getDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000014462 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000014463 loc = mem->getMemberLoc();
14464 d = mem->getMemberDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000014465 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000014466 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidisa6011e22011-10-03 06:36:51 +000014467 loc = msg->getSelectorStartLoc();
John McCall2d2e8702011-04-11 07:02:50 +000014468 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000014469 if (!d) {
14470 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
14471 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
14472 << orig->getSourceRange();
14473 return ExprError();
14474 }
John McCall2d2e8702011-04-11 07:02:50 +000014475 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +000014476 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14477 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000014478 return ExprError();
14479 }
14480
14481 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000014482
14483 // Never recoverable.
14484 return ExprError();
14485}
14486
John McCall36e7fe32010-10-12 00:20:44 +000014487/// Check for operands with placeholder types and complain if found.
14488/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000014489ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
Kaelyn Takata15867822014-11-21 18:48:04 +000014490 if (!getLangOpts().CPlusPlus) {
14491 // C cannot handle TypoExpr nodes on either side of a binop because it
14492 // doesn't handle dependent types properly, so make sure any TypoExprs have
14493 // been dealt with before checking the operands.
14494 ExprResult Result = CorrectDelayedTyposInExpr(E);
14495 if (!Result.isUsable()) return ExprError();
14496 E = Result.get();
14497 }
14498
John McCall4124c492011-10-17 18:40:02 +000014499 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000014500 if (!placeholderType) return E;
John McCall4124c492011-10-17 18:40:02 +000014501
14502 switch (placeholderType->getKind()) {
John McCall36e7fe32010-10-12 00:20:44 +000014503
John McCall31996342011-04-07 08:22:57 +000014504 // Overloaded expressions.
John McCall4124c492011-10-17 18:40:02 +000014505 case BuiltinType::Overload: {
John McCall50a2c2c2011-10-11 23:14:30 +000014506 // Try to resolve a single function template specialization.
14507 // This is obligatory.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000014508 ExprResult result = E;
John McCall50a2c2c2011-10-11 23:14:30 +000014509 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
14510 return result;
14511
14512 // If that failed, try to recover with a call.
14513 } else {
14514 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
14515 /*complain*/ true);
14516 return result;
14517 }
14518 }
John McCall31996342011-04-07 08:22:57 +000014519
John McCall0009fcc2011-04-26 20:42:42 +000014520 // Bound member functions.
John McCall4124c492011-10-17 18:40:02 +000014521 case BuiltinType::BoundMember: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000014522 ExprResult result = E;
David Majnemerced8bdf2015-02-25 17:36:15 +000014523 const Expr *BME = E->IgnoreParens();
14524 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
14525 // Try to give a nicer diagnostic if it is a bound member that we recognize.
14526 if (isa<CXXPseudoDestructorExpr>(BME)) {
14527 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
14528 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
14529 if (ME->getMemberNameInfo().getName().getNameKind() ==
14530 DeclarationName::CXXDestructorName)
14531 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
14532 }
14533 tryToRecoverWithCall(result, PD,
John McCall50a2c2c2011-10-11 23:14:30 +000014534 /*complain*/ true);
14535 return result;
John McCall4124c492011-10-17 18:40:02 +000014536 }
14537
14538 // ARC unbridged casts.
14539 case BuiltinType::ARCUnbridgedCast: {
14540 Expr *realCast = stripARCUnbridgedCast(E);
14541 diagnoseARCUnbridgedCast(realCast);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000014542 return realCast;
John McCall4124c492011-10-17 18:40:02 +000014543 }
John McCall0009fcc2011-04-26 20:42:42 +000014544
John McCall31996342011-04-07 08:22:57 +000014545 // Expressions of unknown type.
John McCall4124c492011-10-17 18:40:02 +000014546 case BuiltinType::UnknownAny:
John McCall31996342011-04-07 08:22:57 +000014547 return diagnoseUnknownAnyExpr(*this, E);
14548
John McCall526ab472011-10-25 17:37:35 +000014549 // Pseudo-objects.
14550 case BuiltinType::PseudoObject:
14551 return checkPseudoObjectRValue(E);
14552
Reid Klecknerf392ec62014-07-11 23:54:29 +000014553 case BuiltinType::BuiltinFn: {
14554 // Accept __noop without parens by implicitly converting it to a call expr.
14555 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
14556 if (DRE) {
14557 auto *FD = cast<FunctionDecl>(DRE->getDecl());
14558 if (FD->getBuiltinID() == Builtin::BI__noop) {
14559 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
14560 CK_BuiltinFnToFnPtr).get();
14561 return new (Context) CallExpr(Context, E, None, Context.IntTy,
14562 VK_RValue, SourceLocation());
14563 }
14564 }
14565
Eli Friedman34866c72012-08-31 00:14:07 +000014566 Diag(E->getLocStart(), diag::err_builtin_fn_use);
14567 return ExprError();
Reid Klecknerf392ec62014-07-11 23:54:29 +000014568 }
Eli Friedman34866c72012-08-31 00:14:07 +000014569
Alexey Bataev1a3320e2015-08-25 14:24:04 +000014570 // Expressions of unknown type.
14571 case BuiltinType::OMPArraySection:
14572 Diag(E->getLocStart(), diag::err_omp_array_section_use);
14573 return ExprError();
14574
John McCalle314e272011-10-18 21:02:43 +000014575 // Everything else should be impossible.
14576#define BUILTIN_TYPE(Id, SingletonId) \
14577 case BuiltinType::Id:
14578#define PLACEHOLDER_TYPE(Id, SingletonId)
14579#include "clang/AST/BuiltinTypes.def"
John McCall4124c492011-10-17 18:40:02 +000014580 break;
14581 }
14582
14583 llvm_unreachable("invalid placeholder type!");
John McCall36e7fe32010-10-12 00:20:44 +000014584}
Richard Trieu2c850c02011-04-21 21:44:26 +000014585
Richard Trieuba63ce62011-09-09 01:45:06 +000014586bool Sema::CheckCaseExpression(Expr *E) {
14587 if (E->isTypeDependent())
Richard Trieu2c850c02011-04-21 21:44:26 +000014588 return true;
Richard Trieuba63ce62011-09-09 01:45:06 +000014589 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
14590 return E->getType()->isIntegralOrEnumerationType();
Richard Trieu2c850c02011-04-21 21:44:26 +000014591 return false;
14592}
Ted Kremeneke65b0862012-03-06 20:05:56 +000014593
14594/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
14595ExprResult
14596Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
14597 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
14598 "Unknown Objective-C Boolean value!");
Fariborz Jahanianf2578572012-08-30 18:49:41 +000014599 QualType BoolT = Context.ObjCBuiltinBoolTy;
14600 if (!Context.getBOOLDecl()) {
Fariborz Jahanianeab17302012-10-16 17:08:11 +000014601 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
Fariborz Jahanianf2578572012-08-30 18:49:41 +000014602 Sema::LookupOrdinaryName);
Fariborz Jahanian379e5362012-10-16 16:21:20 +000014603 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
Fariborz Jahanianf2578572012-08-30 18:49:41 +000014604 NamedDecl *ND = Result.getFoundDecl();
14605 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
14606 Context.setBOOLDecl(TD);
14607 }
14608 }
14609 if (Context.getBOOLDecl())
14610 BoolT = Context.getBOOLType();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000014611 return new (Context)
14612 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
Ted Kremeneke65b0862012-03-06 20:05:56 +000014613}