blob: 68fd92fbe1a68693a3bc7123d52633ab1703f00b [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.
Manman Ren073db022016-03-10 18:53:19 +000052bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +000053 // 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.
Manman Ren073db022016-03-10 18:53:19 +000070 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
Sebastian Redl5999aec2011-10-16 18:19:16 +000071 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.
Aaron Ballman0bcd6c12016-03-09 16:48:08 +000079 if (const auto *A = D->getAttr<UnusedAttr>()) {
80 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
81 // should diagnose them.
82 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused) {
83 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
84 if (DC && !DC->hasAttr<UnusedAttr>())
85 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
86 }
Fariborz Jahanian66c93f42012-09-06 16:43:18 +000087 }
88}
89
Nico Weber0055a192015-03-19 19:18:22 +000090static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
91 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
92 if (!OMD)
93 return false;
94 const ObjCInterfaceDecl *OID = OMD->getClassInterface();
95 if (!OID)
96 return false;
97
98 for (const ObjCCategoryDecl *Cat : OID->visible_categories())
99 if (ObjCMethodDecl *CatMeth =
100 Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
101 if (!CatMeth->hasAttr<AvailabilityAttr>())
102 return true;
103 return false;
104}
105
106static AvailabilityResult
107DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
108 const ObjCInterfaceDecl *UnknownObjCClass,
109 bool ObjCPropertyAccess) {
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000110 // See if this declaration is unavailable or deprecated.
111 std::string Message;
Ted Kremenekc004b4d2015-05-14 22:07:25 +0000112 AvailabilityResult Result = D->getAvailability(&Message);
113
114 // For typedefs, if the typedef declaration appears available look
115 // to the underlying type to see if it is more restrictive.
David Blaikief0f00dc2015-05-14 22:47:19 +0000116 while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Ted Kremenekc004b4d2015-05-14 22:07:25 +0000117 if (Result == AR_Available) {
118 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
119 D = TT->getDecl();
120 Result = D->getAvailability(&Message);
121 continue;
122 }
123 }
124 break;
125 }
Fariborz Jahanian285b6b62014-06-18 17:58:27 +0000126
127 // Forward class declarations get their attributes from their definition.
128 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
Ted Kremenekc004b4d2015-05-14 22:07:25 +0000129 if (IDecl->getDefinition()) {
Fariborz Jahanian285b6b62014-06-18 17:58:27 +0000130 D = IDecl->getDefinition();
Ted Kremenekc004b4d2015-05-14 22:07:25 +0000131 Result = D->getAvailability(&Message);
132 }
Fariborz Jahanian285b6b62014-06-18 17:58:27 +0000133 }
Ted Kremenekc004b4d2015-05-14 22:07:25 +0000134
Fariborz Jahanian25d09c22011-11-28 19:45:58 +0000135 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
136 if (Result == AR_Available) {
137 const DeclContext *DC = ECD->getDeclContext();
138 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
139 Result = TheEnumDecl->getAvailability(&Message);
140 }
Jordan Rose2bd991a2012-10-10 16:42:54 +0000141
Craig Topperc3ec1492014-05-26 06:22:03 +0000142 const ObjCPropertyDecl *ObjCPDecl = nullptr;
Nico Weber0055a192015-03-19 19:18:22 +0000143 if (Result == AR_Deprecated || Result == AR_Unavailable ||
Manman Renb636b902016-02-17 22:05:48 +0000144 Result == AR_NotYetIntroduced) {
Jordan Rose2bd991a2012-10-10 16:42:54 +0000145 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
146 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000147 AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
Jordan Rose2bd991a2012-10-10 16:42:54 +0000148 if (PDeclResult == Result)
149 ObjCPDecl = PD;
150 }
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000151 }
Jordan Rose2bd991a2012-10-10 16:42:54 +0000152 }
Fariborz Jahanian25d09c22011-11-28 19:45:58 +0000153
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000154 switch (Result) {
155 case AR_Available:
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000156 break;
Nico Weber55905142015-03-06 06:01:06 +0000157
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000158 case AR_Deprecated:
Ted Kremenekcb42dbe2013-11-20 17:24:03 +0000159 if (S.getCurContextAvailability() != AR_Deprecated)
Ted Kremenekb79ee572013-12-18 23:30:06 +0000160 S.EmitAvailabilityWarning(Sema::AD_Deprecation,
Fariborz Jahanian89ea9612014-06-16 17:25:41 +0000161 D, Message, Loc, UnknownObjCClass, ObjCPDecl,
162 ObjCPropertyAccess);
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000163 break;
Ted Kremenekb79ee572013-12-18 23:30:06 +0000164
Nico Weber0055a192015-03-19 19:18:22 +0000165 case AR_NotYetIntroduced: {
166 // Don't do this for enums, they can't be redeclared.
167 if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
168 break;
169
Duncan P. N. Exon Smith5d6790c2016-03-08 06:12:54 +0000170 bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
Nico Weber0055a192015-03-19 19:18:22 +0000171 // Objective-C method declarations in categories are not modelled as
172 // redeclarations, so manually look for a redeclaration in a category
173 // if necessary.
174 if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
175 Warn = false;
176 // In general, D will point to the most recent redeclaration. However,
177 // for `@class A;` decls, this isn't true -- manually go through the
178 // redecl chain in that case.
179 if (Warn && isa<ObjCInterfaceDecl>(D))
180 for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
181 Redecl = Redecl->getPreviousDecl())
182 if (!Redecl->hasAttr<AvailabilityAttr>() ||
183 Redecl->getAttr<AvailabilityAttr>()->isInherited())
184 Warn = false;
185
186 if (Warn)
187 S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc,
188 UnknownObjCClass, ObjCPDecl,
189 ObjCPropertyAccess);
190 break;
191 }
192
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000193 case AR_Unavailable:
Ted Kremenekb79ee572013-12-18 23:30:06 +0000194 if (S.getCurContextAvailability() != AR_Unavailable)
195 S.EmitAvailabilityWarning(Sema::AD_Unavailable,
Fariborz Jahanian89ea9612014-06-16 17:25:41 +0000196 D, Message, Loc, UnknownObjCClass, ObjCPDecl,
197 ObjCPropertyAccess);
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000198 break;
Ted Kremenekb79ee572013-12-18 23:30:06 +0000199
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000200 }
201 return Result;
202}
203
Eli Friedmanebea0f22013-07-18 23:29:14 +0000204/// \brief Emit a note explaining that this function is deleted.
Richard Smith852265f2012-03-30 20:53:28 +0000205void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
Eli Friedmanebea0f22013-07-18 23:29:14 +0000206 assert(Decl->isDeleted());
207
Richard Smith852265f2012-03-30 20:53:28 +0000208 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
209
Eli Friedmanebea0f22013-07-18 23:29:14 +0000210 if (Method && Method->isDeleted() && Method->isDefaulted()) {
Richard Smith6f1e2c62012-04-02 20:59:25 +0000211 // If the method was explicitly defaulted, point at that declaration.
212 if (!Method->isImplicit())
213 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
214
215 // Try to diagnose why this special member function was implicitly
216 // deleted. This might fail, if that reason no longer applies.
Richard Smith852265f2012-03-30 20:53:28 +0000217 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +0000218 if (CSM != CXXInvalid)
219 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
220
221 return;
Richard Smith852265f2012-03-30 20:53:28 +0000222 }
223
Eli Friedmanebea0f22013-07-18 23:29:14 +0000224 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
225 if (CXXConstructorDecl *BaseCD =
226 const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
227 Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
228 if (BaseCD->isDeleted()) {
229 NoteDeletedFunction(BaseCD);
230 } else {
231 // FIXME: An explanation of why exactly it can't be inherited
232 // would be nice.
233 Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
234 }
235 return;
236 }
237 }
238
Ted Kremenekb79ee572013-12-18 23:30:06 +0000239 Diag(Decl->getLocation(), diag::note_availability_specified_here)
240 << Decl << true;
Richard Smith852265f2012-03-30 20:53:28 +0000241}
242
Jordan Rose28cd12f2012-06-18 22:09:19 +0000243/// \brief Determine whether a FunctionDecl was ever declared with an
244/// explicit storage class.
245static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
Aaron Ballman86c93902014-03-06 23:45:36 +0000246 for (auto I : D->redecls()) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000247 if (I->getStorageClass() != SC_None)
Jordan Rose28cd12f2012-06-18 22:09:19 +0000248 return true;
249 }
250 return false;
251}
252
253/// \brief Check whether we're in an extern inline function and referring to a
Jordan Rosede9e9762012-06-20 18:50:06 +0000254/// variable or function with internal linkage (C11 6.7.4p3).
Jordan Rose28cd12f2012-06-18 22:09:19 +0000255///
Jordan Rose28cd12f2012-06-18 22:09:19 +0000256/// This is only a warning because we used to silently accept this code, but
Jordan Rosede9e9762012-06-20 18:50:06 +0000257/// in many cases it will not behave correctly. This is not enabled in C++ mode
258/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
259/// and so while there may still be user mistakes, most of the time we can't
260/// prove that there are errors.
Jordan Rose28cd12f2012-06-18 22:09:19 +0000261static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
262 const NamedDecl *D,
263 SourceLocation Loc) {
Jordan Rosede9e9762012-06-20 18:50:06 +0000264 // This is disabled under C++; there are too many ways for this to fire in
265 // contexts where the warning is a false positive, or where it is technically
266 // correct but benign.
267 if (S.getLangOpts().CPlusPlus)
268 return;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000269
270 // Check if this is an inlined function or method.
271 FunctionDecl *Current = S.getCurFunctionDecl();
272 if (!Current)
273 return;
274 if (!Current->isInlined())
275 return;
Rafael Espindola3ae00052013-05-13 00:12:11 +0000276 if (!Current->isExternallyVisible())
Jordan Rose28cd12f2012-06-18 22:09:19 +0000277 return;
Rafael Espindola3ae00052013-05-13 00:12:11 +0000278
Jordan Rose28cd12f2012-06-18 22:09:19 +0000279 // Check if the decl has internal linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +0000280 if (D->getFormalLinkage() != InternalLinkage)
Jordan Rose28cd12f2012-06-18 22:09:19 +0000281 return;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000282
Jordan Rose815fe262012-06-21 05:54:50 +0000283 // Downgrade from ExtWarn to Extension if
284 // (1) the supposedly external inline function is in the main file,
285 // and probably won't be included anywhere else.
286 // (2) the thing we're referencing is a pure function.
287 // (3) the thing we're referencing is another inline function.
288 // This last can give us false negatives, but it's better than warning on
289 // wrappers for simple C library functions.
290 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
Eli Friedman5ba37d52013-08-22 00:27:10 +0000291 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
Jordan Rose815fe262012-06-21 05:54:50 +0000292 if (!DowngradeWarning && UsedFn)
293 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
294
Richard Smith1b98ccc2014-07-19 01:39:17 +0000295 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
296 : diag::ext_internal_in_extern_inline)
Jordan Rose815fe262012-06-21 05:54:50 +0000297 << /*IsVar=*/!UsedFn << D;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000298
John McCallc87d9722013-04-02 02:48:58 +0000299 S.MaybeSuggestAddingStaticToDecl(Current);
Jordan Rose28cd12f2012-06-18 22:09:19 +0000300
Alp Toker2afa8782014-05-28 12:20:14 +0000301 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
302 << D;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000303}
304
John McCallc87d9722013-04-02 02:48:58 +0000305void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
Rafael Espindola8db352d2013-10-17 15:37:26 +0000306 const FunctionDecl *First = Cur->getFirstDecl();
John McCallc87d9722013-04-02 02:48:58 +0000307
308 // Suggest "static" on the function, if possible.
309 if (!hasAnyExplicitStorageClass(First)) {
310 SourceLocation DeclBegin = First->getSourceRange().getBegin();
311 Diag(DeclBegin, diag::note_convert_inline_to_static)
312 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
313 }
314}
315
Douglas Gregor171c45a2009-02-18 21:56:37 +0000316/// \brief Determine whether the use of this declaration is valid, and
317/// emit any corresponding diagnostics.
318///
319/// This routine diagnoses various problems with referencing
320/// declarations that can occur when using a declaration. For example,
321/// it might warn if a deprecated or unavailable declaration is being
322/// used, or produce an error (and return true) if a C++0x deleted
323/// function is being used.
324///
325/// \returns true if there was an error (this declaration cannot be
326/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +0000327///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +0000328bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian89ea9612014-06-16 17:25:41 +0000329 const ObjCInterfaceDecl *UnknownObjCClass,
330 bool ObjCPropertyAccess) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000331 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000332 // If there were any diagnostics suppressed by template argument deduction,
333 // emit them now.
Craig Topperdfe29ae2015-12-21 06:35:56 +0000334 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000335 if (Pos != SuppressedDiagnostics.end()) {
Craig Topperdfe29ae2015-12-21 06:35:56 +0000336 for (const PartialDiagnosticAt &Suppressed : Pos->second)
337 Diag(Suppressed.first, Suppressed.second);
Richard Smithb63b6ee2014-01-22 01:43:19 +0000338
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000339 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000340 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000341 // entry from the table, because we want to avoid ever emitting these
342 // diagnostics again.
Craig Topperdfe29ae2015-12-21 06:35:56 +0000343 Pos->second.clear();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000344 }
Richard Smithb63b6ee2014-01-22 01:43:19 +0000345
346 // C++ [basic.start.main]p3:
347 // The function 'main' shall not be used within a program.
348 if (cast<FunctionDecl>(D)->isMain())
349 Diag(Loc, diag::ext_main_used);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000350 }
351
Richard Smith30482bc2011-02-20 03:19:35 +0000352 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +0000353 if (ParsingInitForAutoVars.count(D)) {
Richard Smithe301ba22015-11-11 02:02:15 +0000354 const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType();
355
Richard Smithb2bc2e62011-02-21 20:05:19 +0000356 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
Richard Smithe301ba22015-11-11 02:02:15 +0000357 << D->getDeclName() << (unsigned)AT->getKeyword();
Richard Smithb2bc2e62011-02-21 20:05:19 +0000358 return true;
Richard Smith30482bc2011-02-20 03:19:35 +0000359 }
360
Douglas Gregor171c45a2009-02-18 21:56:37 +0000361 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +0000362 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +0000363 if (FD->isDeleted()) {
364 Diag(Loc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +0000365 NoteDeletedFunction(FD);
Douglas Gregor171c45a2009-02-18 21:56:37 +0000366 return true;
367 }
Richard Smith2a7d4812013-05-04 07:00:32 +0000368
369 // If the function has a deduced return type, and we can't deduce it,
370 // then we can't use it either.
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000371 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +0000372 DeduceReturnType(FD, Loc))
373 return true;
Douglas Gregorde681d42009-02-24 04:26:15 +0000374 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000375
376 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
377 // Only the variables omp_in and omp_out are allowed in the combiner.
378 // Only the variables omp_priv and omp_orig are allowed in the
379 // initializer-clause.
380 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
381 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
382 isa<VarDecl>(D)) {
383 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
384 << getCurFunction()->HasOMPDeclareReductionCombiner;
385 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
386 return true;
387 }
Nico Weber0055a192015-03-19 19:18:22 +0000388 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
389 ObjCPropertyAccess);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000390
Fariborz Jahanian66c93f42012-09-06 16:43:18 +0000391 DiagnoseUnusedOfDecl(*this, D, Loc);
Jordan Rose2684c682012-06-15 18:19:48 +0000392
Jordan Rose28cd12f2012-06-18 22:09:19 +0000393 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
Jordan Rose2684c682012-06-15 18:19:48 +0000394
Douglas Gregor171c45a2009-02-18 21:56:37 +0000395 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000396}
397
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000398/// \brief Retrieve the message suffix that should be added to a
399/// diagnostic complaining about the given function being deleted or
400/// unavailable.
401std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000402 std::string Message;
403 if (FD->getAvailability(&Message))
404 return ": " + Message;
405
406 return std::string();
407}
408
John McCallb46f2872011-09-09 07:56:05 +0000409/// DiagnoseSentinelCalls - This routine checks whether a call or
410/// message-send is to a declaration with the sentinel attribute, and
411/// if so, it checks that the requirements of the sentinel are
412/// satisfied.
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000413void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000414 ArrayRef<Expr *> Args) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000415 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000416 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000417 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000418
John McCallb46f2872011-09-09 07:56:05 +0000419 // The number of formal parameters of the declaration.
420 unsigned numFormalParams;
Mike Stump11289f42009-09-09 15:08:12 +0000421
John McCallb46f2872011-09-09 07:56:05 +0000422 // The kind of declaration. This is also an index into a %select in
423 // the diagnostic.
424 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
425
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000426 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000427 numFormalParams = MD->param_size();
428 calleeType = CT_Method;
Mike Stump12b8ce12009-08-04 21:02:39 +0000429 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000430 numFormalParams = FD->param_size();
431 calleeType = CT_Function;
432 } else if (isa<VarDecl>(D)) {
433 QualType type = cast<ValueDecl>(D)->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +0000434 const FunctionType *fn = nullptr;
John McCallb46f2872011-09-09 07:56:05 +0000435 if (const PointerType *ptr = type->getAs<PointerType>()) {
436 fn = ptr->getPointeeType()->getAs<FunctionType>();
437 if (!fn) return;
438 calleeType = CT_Function;
439 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
440 fn = ptr->getPointeeType()->castAs<FunctionType>();
441 calleeType = CT_Block;
442 } else {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000443 return;
John McCallb46f2872011-09-09 07:56:05 +0000444 }
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000445
John McCallb46f2872011-09-09 07:56:05 +0000446 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000447 numFormalParams = proto->getNumParams();
John McCallb46f2872011-09-09 07:56:05 +0000448 } else {
449 numFormalParams = 0;
450 }
451 } else {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000452 return;
453 }
John McCallb46f2872011-09-09 07:56:05 +0000454
455 // "nullPos" is the number of formal parameters at the end which
456 // effectively count as part of the variadic arguments. This is
457 // useful if you would prefer to not have *any* formal parameters,
458 // but the language forces you to have at least one.
459 unsigned nullPos = attr->getNullPos();
460 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
461 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
462
463 // The number of arguments which should follow the sentinel.
464 unsigned numArgsAfterSentinel = attr->getSentinel();
465
466 // If there aren't enough arguments for all the formal parameters,
467 // the sentinel, and the args after the sentinel, complain.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000468 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000469 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000470 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000471 return;
472 }
John McCallb46f2872011-09-09 07:56:05 +0000473
474 // Otherwise, find the sentinel expression.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000475 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
John McCall7ddbcf42010-05-06 23:53:00 +0000476 if (!sentinelExpr) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000477 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +0000478 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000479
Reid Kleckner92493e52014-11-13 23:19:36 +0000480 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
481 // or 'NULL' if those are actually defined in the context. Only use
John McCallb46f2872011-09-09 07:56:05 +0000482 // 'nil' for ObjC methods, where it's much more likely that the
483 // variadic arguments form a list of object pointers.
484 SourceLocation MissingNilLoc
Craig Topper07fa1762015-11-15 02:31:46 +0000485 = getLocForEndOfToken(sentinelExpr->getLocEnd());
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000486 std::string NullValue;
Richard Smith20e883e2015-04-29 23:20:19 +0000487 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000488 NullValue = "nil";
Reid Kleckner92493e52014-11-13 23:19:36 +0000489 else if (getLangOpts().CPlusPlus11)
490 NullValue = "nullptr";
Richard Smith20e883e2015-04-29 23:20:19 +0000491 else if (PP.isMacroDefined("NULL"))
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000492 NullValue = "NULL";
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000493 else
John McCallb46f2872011-09-09 07:56:05 +0000494 NullValue = "(void*) 0";
Eli Friedman9ab36372011-09-27 23:46:37 +0000495
496 if (MissingNilLoc.isInvalid())
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000497 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
Eli Friedman9ab36372011-09-27 23:46:37 +0000498 else
499 Diag(MissingNilLoc, diag::warn_missing_sentinel)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000500 << int(calleeType)
Eli Friedman9ab36372011-09-27 23:46:37 +0000501 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000502 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000503}
504
Richard Trieuba63ce62011-09-09 01:45:06 +0000505SourceRange Sema::getExprRange(Expr *E) const {
506 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor87f95b02009-02-26 21:00:50 +0000507}
508
Chris Lattner513165e2008-07-25 21:10:04 +0000509//===----------------------------------------------------------------------===//
510// Standard Promotions and Conversions
511//===----------------------------------------------------------------------===//
512
Chris Lattner513165e2008-07-25 21:10:04 +0000513/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000514ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
John McCall50a2c2c2011-10-11 23:14:30 +0000515 // Handle any placeholder expressions which made it here.
516 if (E->getType()->isPlaceholderType()) {
517 ExprResult result = CheckPlaceholderExpr(E);
518 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000519 E = result.get();
John McCall50a2c2c2011-10-11 23:14:30 +0000520 }
521
Chris Lattner513165e2008-07-25 21:10:04 +0000522 QualType Ty = E->getType();
523 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
524
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +0000525 if (Ty->isFunctionType()) {
526 // If we are here, we are not calling a function but taking
527 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
528 if (getLangOpts().OpenCL) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000529 if (Diagnose)
530 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +0000531 return ExprError();
532 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000533
534 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
535 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
536 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
537 return ExprError();
538
John Wiegley01296292011-04-08 18:41:53 +0000539 E = ImpCastExprToType(E, Context.getPointerType(Ty),
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000540 CK_FunctionToPointerDecay).get();
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +0000541 } else if (Ty->isArrayType()) {
Chris Lattner61f60a02008-07-25 21:33:13 +0000542 // In C90 mode, arrays only promote to pointers if the array expression is
543 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
544 // type 'array of type' is converted to an expression that has type 'pointer
545 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
546 // that has type 'array of type' ...". The relevant change is "an lvalue"
547 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000548 //
549 // C++ 4.2p1:
550 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
551 // T" can be converted to an rvalue of type "pointer to T".
552 //
David Blaikiebbafb8a2012-03-11 07:00:24 +0000553 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000554 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000555 CK_ArrayToPointerDecay).get();
Chris Lattner61f60a02008-07-25 21:33:13 +0000556 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000557 return E;
Chris Lattner513165e2008-07-25 21:10:04 +0000558}
559
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000560static void CheckForNullPointerDereference(Sema &S, Expr *E) {
561 // Check to see if we are dereferencing a null pointer. If so,
562 // and if not volatile-qualified, this is undefined behavior that the
563 // optimizer will delete, so warn about it. People sometimes try to use this
564 // to get a deterministic trap and are surprised by clang's behavior. This
565 // only handles the pattern "*null", which is a very syntactic check.
566 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
567 if (UO->getOpcode() == UO_Deref &&
568 UO->getSubExpr()->IgnoreParenCasts()->
569 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
570 !UO->getType().isVolatileQualified()) {
571 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
572 S.PDiag(diag::warn_indirection_through_null)
573 << UO->getSubExpr()->getSourceRange());
574 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
575 S.PDiag(diag::note_indirection_through_null));
576 }
577}
578
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +0000579static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +0000580 SourceLocation AssignLoc,
581 const Expr* RHS) {
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +0000582 const ObjCIvarDecl *IV = OIRE->getDecl();
583 if (!IV)
584 return;
585
586 DeclarationName MemberName = IV->getDeclName();
587 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
588 if (!Member || !Member->isStr("isa"))
589 return;
590
591 const Expr *Base = OIRE->getBase();
592 QualType BaseType = Base->getType();
593 if (OIRE->isArrow())
594 BaseType = BaseType->getPointeeType();
595 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
596 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000597 ObjCInterfaceDecl *ClassDeclared = nullptr;
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +0000598 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
599 if (!ClassDeclared->getSuperClass()
600 && (*ClassDeclared->ivar_begin()) == IV) {
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +0000601 if (RHS) {
602 NamedDecl *ObjectSetClass =
603 S.LookupSingleName(S.TUScope,
604 &S.Context.Idents.get("object_setClass"),
605 SourceLocation(), S.LookupOrdinaryName);
606 if (ObjectSetClass) {
Craig Topper07fa1762015-11-15 02:31:46 +0000607 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +0000608 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
609 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
610 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
611 AssignLoc), ",") <<
612 FixItHint::CreateInsertion(RHSLocEnd, ")");
613 }
614 else
615 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
616 } else {
617 NamedDecl *ObjectGetClass =
618 S.LookupSingleName(S.TUScope,
619 &S.Context.Idents.get("object_getClass"),
620 SourceLocation(), S.LookupOrdinaryName);
621 if (ObjectGetClass)
622 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
623 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
624 FixItHint::CreateReplacement(
625 SourceRange(OIRE->getOpLoc(),
626 OIRE->getLocEnd()), ")");
627 else
628 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
629 }
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +0000630 S.Diag(IV->getLocation(), diag::note_ivar_decl);
631 }
632 }
633}
634
John Wiegley01296292011-04-08 18:41:53 +0000635ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000636 // Handle any placeholder expressions which made it here.
637 if (E->getType()->isPlaceholderType()) {
638 ExprResult result = CheckPlaceholderExpr(E);
639 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000640 E = result.get();
John McCall50a2c2c2011-10-11 23:14:30 +0000641 }
642
John McCallf3735e02010-12-01 04:43:34 +0000643 // C++ [conv.lval]p1:
644 // A glvalue of a non-function, non-array type T can be
645 // converted to a prvalue.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000646 if (!E->isGLValue()) return E;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +0000647
John McCall27584242010-12-06 20:48:59 +0000648 QualType T = E->getType();
649 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000650
John McCall27584242010-12-06 20:48:59 +0000651 // We don't want to throw lvalue-to-rvalue casts on top of
652 // expressions of certain types in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000653 if (getLangOpts().CPlusPlus &&
John McCall27584242010-12-06 20:48:59 +0000654 (E->getType() == Context.OverloadTy ||
655 T->isDependentType() ||
656 T->isRecordType()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000657 return E;
John McCall27584242010-12-06 20:48:59 +0000658
659 // The C standard is actually really unclear on this point, and
660 // DR106 tells us what the result should be but not why. It's
661 // generally best to say that void types just doesn't undergo
662 // lvalue-to-rvalue at all. Note that expressions of unqualified
663 // 'void' type are never l-values, but qualified void can be.
664 if (T->isVoidType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000665 return E;
John McCall27584242010-12-06 20:48:59 +0000666
John McCall6ced97a2013-02-12 01:29:43 +0000667 // OpenCL usually rejects direct accesses to values of 'half' type.
668 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
669 T->isHalfType()) {
670 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
671 << 0 << T;
672 return ExprError();
673 }
674
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000675 CheckForNullPointerDereference(*this, E);
Fariborz Jahanian06bb7f72013-03-28 19:50:55 +0000676 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
677 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
678 &Context.Idents.get("object_getClass"),
679 SourceLocation(), LookupOrdinaryName);
680 if (ObjectGetClass)
681 Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
682 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
683 FixItHint::CreateReplacement(
684 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
685 else
686 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
687 }
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +0000688 else if (const ObjCIvarRefExpr *OIRE =
689 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
Craig Topperc3ec1492014-05-26 06:22:03 +0000690 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
691
John McCall27584242010-12-06 20:48:59 +0000692 // C++ [conv.lval]p1:
693 // [...] If T is a non-class type, the type of the prvalue is the
694 // cv-unqualified version of T. Otherwise, the type of the
695 // rvalue is T.
696 //
697 // C99 6.3.2.1p2:
698 // If the lvalue has qualified type, the value has the unqualified
699 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000700 // type of the lvalue.
John McCall27584242010-12-06 20:48:59 +0000701 if (T.hasQualifiers())
702 T = T.getUnqualifiedType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000703
Richard Smithdb0ac552015-12-18 22:40:25 +0000704 // Under the MS ABI, lock down the inheritance model now.
David Majnemercca07d72015-09-10 07:20:05 +0000705 if (T->isMemberPointerType() &&
706 Context.getTargetInfo().getCXXABI().isMicrosoft())
Richard Smithdb0ac552015-12-18 22:40:25 +0000707 (void)isCompleteType(E->getExprLoc(), T);
David Majnemercca07d72015-09-10 07:20:05 +0000708
Eli Friedman3bda6b12012-02-02 23:15:15 +0000709 UpdateMarkingForLValueToRValue(E);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +0000710
711 // Loading a __weak object implicitly retains the value, so we need a cleanup to
712 // balance that.
713 if (getLangOpts().ObjCAutoRefCount &&
714 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
715 ExprNeedsCleanups = true;
Eli Friedman3bda6b12012-02-02 23:15:15 +0000716
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000717 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
718 nullptr, VK_RValue);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000719
Douglas Gregorc79862f2012-04-12 17:51:55 +0000720 // C11 6.3.2.1p2:
721 // ... if the lvalue has atomic type, the value has the non-atomic version
722 // of the type of the lvalue ...
723 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
724 T = Atomic->getValueType().getUnqualifiedType();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000725 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
726 nullptr, VK_RValue);
Douglas Gregorc79862f2012-04-12 17:51:55 +0000727 }
728
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000729 return Res;
John McCall27584242010-12-06 20:48:59 +0000730}
731
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000732ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
733 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
John Wiegley01296292011-04-08 18:41:53 +0000734 if (Res.isInvalid())
735 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000736 Res = DefaultLvalueConversion(Res.get());
John Wiegley01296292011-04-08 18:41:53 +0000737 if (Res.isInvalid())
738 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000739 return Res;
Douglas Gregorb92a1562010-02-03 00:27:59 +0000740}
741
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +0000742/// CallExprUnaryConversions - a special case of an unary conversion
743/// performed on a function designator of a call expression.
744ExprResult Sema::CallExprUnaryConversions(Expr *E) {
745 QualType Ty = E->getType();
746 ExprResult Res = E;
747 // Only do implicit cast for a function type, but not for a pointer
748 // to function type.
749 if (Ty->isFunctionType()) {
750 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000751 CK_FunctionToPointerDecay).get();
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +0000752 if (Res.isInvalid())
753 return ExprError();
754 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000755 Res = DefaultLvalueConversion(Res.get());
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +0000756 if (Res.isInvalid())
757 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000758 return Res.get();
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +0000759}
Douglas Gregorb92a1562010-02-03 00:27:59 +0000760
Chris Lattner513165e2008-07-25 21:10:04 +0000761/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000762/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000763/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000764/// apply if the array is an argument to the sizeof or address (&) operators.
765/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000766ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000767 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000768 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
769 if (Res.isInvalid())
Fariborz Jahanian47ef4662013-03-06 00:37:40 +0000770 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000771 E = Res.get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000772
John McCallf3735e02010-12-01 04:43:34 +0000773 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000774 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000775
Joey Goulydd7f4562013-01-23 11:56:20 +0000776 // Half FP have to be promoted to float unless it is natively supported
777 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000778 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000779
John McCallf3735e02010-12-01 04:43:34 +0000780 // Try to perform integral promotions if the object has a theoretically
781 // promotable type.
782 if (Ty->isIntegralOrUnscopedEnumerationType()) {
783 // C99 6.3.1.1p2:
784 //
785 // The following may be used in an expression wherever an int or
786 // unsigned int may be used:
787 // - an object or expression with an integer type whose integer
788 // conversion rank is less than or equal to the rank of int
789 // and unsigned int.
790 // - A bit-field of type _Bool, int, signed int, or unsigned int.
791 //
792 // If an int can represent all values of the original type, the
793 // value is converted to an int; otherwise, it is converted to an
794 // unsigned int. These are called the integer promotions. All
795 // other types are unchanged by the integer promotions.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000796
John McCallf3735e02010-12-01 04:43:34 +0000797 QualType PTy = Context.isPromotableBitField(E);
798 if (!PTy.isNull()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000799 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000800 return E;
John McCallf3735e02010-12-01 04:43:34 +0000801 }
802 if (Ty->isPromotableIntegerType()) {
803 QualType PT = Context.getPromotedIntegerType(Ty);
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000804 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000805 return E;
John McCallf3735e02010-12-01 04:43:34 +0000806 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000807 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000808 return E;
Chris Lattner513165e2008-07-25 21:10:04 +0000809}
810
Chris Lattner2ce500f2008-07-25 22:25:12 +0000811/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Tim Northoverda165072013-01-30 09:46:55 +0000812/// do not have a prototype. Arguments that have type float or __fp16
813/// are promoted to double. All other argument types are converted by
814/// UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000815ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
816 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000817 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000818
John Wiegley01296292011-04-08 18:41:53 +0000819 ExprResult Res = UsualUnaryConversions(E);
820 if (Res.isInvalid())
Fariborz Jahanian47ef4662013-03-06 00:37:40 +0000821 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000822 E = Res.get();
John McCall9bc26772010-12-06 18:36:11 +0000823
Tim Northoverda165072013-01-30 09:46:55 +0000824 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
825 // double.
826 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
827 if (BTy && (BTy->getKind() == BuiltinType::Half ||
828 BTy->getKind() == BuiltinType::Float))
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000829 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
John Wiegley01296292011-04-08 18:41:53 +0000830
John McCall4bb057d2011-08-27 22:06:17 +0000831 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall0562caa2011-08-29 23:55:37 +0000832 // promotion, even on class types, but note:
833 // C++11 [conv.lval]p2:
834 // When an lvalue-to-rvalue conversion occurs in an unevaluated
835 // operand or a subexpression thereof the value contained in the
836 // referenced object is not accessed. Otherwise, if the glvalue
837 // has a class type, the conversion copy-initializes a temporary
838 // of type T from the glvalue and the result of the conversion
839 // is a prvalue for the temporary.
Eli Friedman05e28012012-01-17 02:13:45 +0000840 // FIXME: add some way to gate this entire thing for correctness in
841 // potentially potentially evaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +0000842 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
Eli Friedman05e28012012-01-17 02:13:45 +0000843 ExprResult Temp = PerformCopyInitialization(
844 InitializedEntity::InitializeTemporary(E->getType()),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000845 E->getExprLoc(), E);
Eli Friedman05e28012012-01-17 02:13:45 +0000846 if (Temp.isInvalid())
847 return ExprError();
848 E = Temp.get();
John McCall29ad95b2011-08-27 01:09:30 +0000849 }
850
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000851 return E;
Chris Lattner2ce500f2008-07-25 22:25:12 +0000852}
853
Richard Smith55ce3522012-06-25 20:30:08 +0000854/// Determine the degree of POD-ness for an expression.
855/// Incomplete types are considered POD, since this check can be performed
856/// when we're in an unevaluated context.
857Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
Jordan Rose3e0ec582012-07-19 18:10:23 +0000858 if (Ty->isIncompleteType()) {
Richard Smithd7293d72013-08-05 18:49:43 +0000859 // C++11 [expr.call]p7:
860 // After these conversions, if the argument does not have arithmetic,
861 // enumeration, pointer, pointer to member, or class type, the program
862 // is ill-formed.
863 //
864 // Since we've already performed array-to-pointer and function-to-pointer
865 // decay, the only such type in C++ is cv void. This also handles
866 // initializer lists as variadic arguments.
867 if (Ty->isVoidType())
868 return VAK_Invalid;
869
Jordan Rose3e0ec582012-07-19 18:10:23 +0000870 if (Ty->isObjCObjectType())
871 return VAK_Invalid;
Richard Smith55ce3522012-06-25 20:30:08 +0000872 return VAK_Valid;
Jordan Rose3e0ec582012-07-19 18:10:23 +0000873 }
874
875 if (Ty.isCXX98PODType(Context))
876 return VAK_Valid;
877
Richard Smith16488472012-11-16 00:53:38 +0000878 // C++11 [expr.call]p7:
879 // Passing a potentially-evaluated argument of class type (Clause 9)
Richard Smith55ce3522012-06-25 20:30:08 +0000880 // having a non-trivial copy constructor, a non-trivial move constructor,
Richard Smith16488472012-11-16 00:53:38 +0000881 // or a non-trivial destructor, with no corresponding parameter,
Richard Smith55ce3522012-06-25 20:30:08 +0000882 // is conditionally-supported with implementation-defined semantics.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000883 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
Richard Smith55ce3522012-06-25 20:30:08 +0000884 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
Richard Smith16488472012-11-16 00:53:38 +0000885 if (!Record->hasNonTrivialCopyConstructor() &&
886 !Record->hasNonTrivialMoveConstructor() &&
887 !Record->hasNonTrivialDestructor())
Richard Smith55ce3522012-06-25 20:30:08 +0000888 return VAK_ValidInCXX11;
889
890 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
891 return VAK_Valid;
Richard Smithd7293d72013-08-05 18:49:43 +0000892
893 if (Ty->isObjCObjectType())
894 return VAK_Invalid;
895
Hans Wennborgd9dd4d22014-09-29 23:06:57 +0000896 if (getLangOpts().MSVCCompat)
897 return VAK_MSVCUndefined;
898
Richard Smithd7293d72013-08-05 18:49:43 +0000899 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
900 // permitted to reject them. We should consider doing so.
901 return VAK_Undefined;
Richard Smith55ce3522012-06-25 20:30:08 +0000902}
903
Richard Smithd7293d72013-08-05 18:49:43 +0000904void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
Richard Smith55ce3522012-06-25 20:30:08 +0000905 // Don't allow one to pass an Objective-C interface to a vararg.
Richard Smithd7293d72013-08-05 18:49:43 +0000906 const QualType &Ty = E->getType();
907 VarArgKind VAK = isValidVarArgType(Ty);
Richard Smith55ce3522012-06-25 20:30:08 +0000908
909 // Complain about passing non-POD types through varargs.
Richard Smithd7293d72013-08-05 18:49:43 +0000910 switch (VAK) {
Richard Smithd7293d72013-08-05 18:49:43 +0000911 case VAK_ValidInCXX11:
912 DiagRuntimeBehavior(
Craig Topperc3ec1492014-05-26 06:22:03 +0000913 E->getLocStart(), nullptr,
Richard Smithd7293d72013-08-05 18:49:43 +0000914 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
Richard Smith2868a732014-02-28 01:36:39 +0000915 << Ty << CT);
916 // Fall through.
917 case VAK_Valid:
918 if (Ty->isRecordType()) {
919 // This is unlikely to be what the user intended. If the class has a
920 // 'c_str' member function, the user probably meant to call that.
Craig Topperc3ec1492014-05-26 06:22:03 +0000921 DiagRuntimeBehavior(E->getLocStart(), nullptr,
Richard Smith2868a732014-02-28 01:36:39 +0000922 PDiag(diag::warn_pass_class_arg_to_vararg)
923 << Ty << CT << hasCStrMethod(E) << ".c_str()");
924 }
Richard Smithd7293d72013-08-05 18:49:43 +0000925 break;
926
927 case VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +0000928 case VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +0000929 DiagRuntimeBehavior(
Craig Topperc3ec1492014-05-26 06:22:03 +0000930 E->getLocStart(), nullptr,
Richard Smithd7293d72013-08-05 18:49:43 +0000931 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
932 << getLangOpts().CPlusPlus11 << Ty << CT);
933 break;
934
935 case VAK_Invalid:
936 if (Ty->isObjCObjectType())
937 DiagRuntimeBehavior(
Craig Topperc3ec1492014-05-26 06:22:03 +0000938 E->getLocStart(), nullptr,
Richard Smithd7293d72013-08-05 18:49:43 +0000939 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
940 << Ty << CT);
941 else
942 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
943 << isa<InitListExpr>(E) << Ty << CT;
944 break;
Richard Smith55ce3522012-06-25 20:30:08 +0000945 }
Richard Smith55ce3522012-06-25 20:30:08 +0000946}
947
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000948/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
Jordan Rose3e0ec582012-07-19 18:10:23 +0000949/// will create a trap if the resulting type is not a POD type.
John Wiegley01296292011-04-08 18:41:53 +0000950ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000951 FunctionDecl *FDecl) {
Richard Smith7659b122012-06-27 20:29:39 +0000952 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
John McCall4124c492011-10-17 18:40:02 +0000953 // Strip the unbridged-cast placeholder expression off, if applicable.
954 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
955 (CT == VariadicMethod ||
956 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
957 E = stripARCUnbridgedCast(E);
958
959 // Otherwise, do normal placeholder checking.
960 } else {
961 ExprResult ExprRes = CheckPlaceholderExpr(E);
962 if (ExprRes.isInvalid())
963 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000964 E = ExprRes.get();
John McCall4124c492011-10-17 18:40:02 +0000965 }
966 }
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000967
John McCall4124c492011-10-17 18:40:02 +0000968 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000969 if (ExprRes.isInvalid())
970 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000971 E = ExprRes.get();
Mike Stump11289f42009-09-09 15:08:12 +0000972
Richard Smith55ce3522012-06-25 20:30:08 +0000973 // Diagnostics regarding non-POD argument types are
974 // emitted along with format string checking in Sema::CheckFunctionCall().
Richard Smithd7293d72013-08-05 18:49:43 +0000975 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
Richard Smith55ce3522012-06-25 20:30:08 +0000976 // Turn this into a trap.
977 CXXScopeSpec SS;
978 SourceLocation TemplateKWLoc;
979 UnqualifiedId Name;
980 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
981 E->getLocStart());
982 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
983 Name, true, false);
984 if (TrapFn.isInvalid())
985 return ExprError();
John McCall31168b02011-06-15 23:02:42 +0000986
Richard Smith55ce3522012-06-25 20:30:08 +0000987 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
Dmitri Gribenko78852e92013-05-05 20:40:26 +0000988 E->getLocStart(), None,
Richard Smith55ce3522012-06-25 20:30:08 +0000989 E->getLocEnd());
990 if (Call.isInvalid())
991 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000992
Richard Smith55ce3522012-06-25 20:30:08 +0000993 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
994 Call.get(), E);
995 if (Comma.isInvalid())
996 return ExprError();
997 return Comma.get();
Douglas Gregor253cadf2011-05-21 16:27:21 +0000998 }
Richard Smith55ce3522012-06-25 20:30:08 +0000999
David Blaikiebbafb8a2012-03-11 07:00:24 +00001000 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian3854a552012-03-01 23:42:00 +00001001 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahanianbf482812012-03-02 17:05:03 +00001002 diag::err_call_incomplete_argument))
Fariborz Jahanian3854a552012-03-01 23:42:00 +00001003 return ExprError();
Richard Smith55ce3522012-06-25 20:30:08 +00001004
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001005 return E;
Anders Carlssona7d069d2009-01-16 16:48:51 +00001006}
1007
Richard Trieu7aa58f12011-09-02 20:58:51 +00001008/// \brief Converts an integer to complex float type. Helper function of
1009/// UsualArithmeticConversions()
1010///
1011/// \return false if the integer expression is an integer type and is
1012/// successfully converted to the complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +00001013static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1014 ExprResult &ComplexExpr,
1015 QualType IntTy,
1016 QualType ComplexTy,
1017 bool SkipCast) {
1018 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1019 if (SkipCast) return false;
1020 if (IntTy->isIntegerType()) {
1021 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001022 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1023 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +00001024 CK_FloatingRealToComplex);
1025 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +00001026 assert(IntTy->isComplexIntegerType());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001027 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +00001028 CK_IntegralComplexToFloatingComplex);
1029 }
1030 return false;
1031}
1032
Richard Trieu7aa58f12011-09-02 20:58:51 +00001033/// \brief Handle arithmetic conversion with complex types. Helper function of
1034/// UsualArithmeticConversions()
Richard Trieu5065cdd2011-09-06 18:25:09 +00001035static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1036 ExprResult &RHS, QualType LHSType,
1037 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001038 bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +00001039 // if we have an integer operand, the result is the complex type.
Richard Trieu5065cdd2011-09-06 18:25:09 +00001040 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +00001041 /*skipCast*/false))
Richard Trieu5065cdd2011-09-06 18:25:09 +00001042 return LHSType;
1043 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001044 /*skipCast*/IsCompAssign))
Richard Trieu5065cdd2011-09-06 18:25:09 +00001045 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +00001046
1047 // This handles complex/complex, complex/float, or float/complex.
1048 // When both operands are complex, the shorter operand is converted to the
1049 // type of the longer, and that is the type of the result. This corresponds
1050 // to what is done when combining two real floating-point operands.
1051 // The fun begins when size promotion occur across type domains.
1052 // From H&S 6.3.4: When one operand is complex and the other is a real
1053 // floating-point type, the less precise type is converted, within it's
1054 // real or complex domain, to the precision of the other type. For example,
1055 // when combining a "long double" with a "double _Complex", the
1056 // "double _Complex" is promoted to "long double _Complex".
1057
Chandler Carrutha216cad2014-10-11 00:57:18 +00001058 // Compute the rank of the two types, regardless of whether they are complex.
1059 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +00001060
Chandler Carrutha216cad2014-10-11 00:57:18 +00001061 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1062 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1063 QualType LHSElementType =
1064 LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1065 QualType RHSElementType =
1066 RHSComplexType ? RHSComplexType->getElementType() : RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +00001067
Chandler Carrutha216cad2014-10-11 00:57:18 +00001068 QualType ResultType = S.Context.getComplexType(LHSElementType);
1069 if (Order < 0) {
1070 // Promote the precision of the LHS if not an assignment.
1071 ResultType = S.Context.getComplexType(RHSElementType);
1072 if (!IsCompAssign) {
1073 if (LHSComplexType)
1074 LHS =
1075 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1076 else
1077 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1078 }
1079 } else if (Order > 0) {
1080 // Promote the precision of the RHS.
1081 if (RHSComplexType)
1082 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1083 else
1084 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1085 }
1086 return ResultType;
Richard Trieu7aa58f12011-09-02 20:58:51 +00001087}
1088
1089/// \brief Hande arithmetic conversion from integer to float. Helper function
1090/// of UsualArithmeticConversions()
Richard Trieuba63ce62011-09-09 01:45:06 +00001091static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1092 ExprResult &IntExpr,
1093 QualType FloatTy, QualType IntTy,
1094 bool ConvertFloat, bool ConvertInt) {
1095 if (IntTy->isIntegerType()) {
1096 if (ConvertInt)
Richard Trieu7aa58f12011-09-02 20:58:51 +00001097 // Convert intExpr to the lhs floating point type.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001098 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +00001099 CK_IntegralToFloating);
Richard Trieuba63ce62011-09-09 01:45:06 +00001100 return FloatTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +00001101 }
1102
1103 // Convert both sides to the appropriate complex float.
Richard Trieuba63ce62011-09-09 01:45:06 +00001104 assert(IntTy->isComplexIntegerType());
1105 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +00001106
1107 // _Complex int -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +00001108 if (ConvertInt)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001109 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +00001110 CK_IntegralComplexToFloatingComplex);
1111
1112 // float -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +00001113 if (ConvertFloat)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001114 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +00001115 CK_FloatingRealToComplex);
1116
1117 return result;
1118}
1119
1120/// \brief Handle arithmethic conversion with floating point types. Helper
1121/// function of UsualArithmeticConversions()
Richard Trieucfe3f212011-09-06 18:38:41 +00001122static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1123 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001124 QualType RHSType, bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +00001125 bool LHSFloat = LHSType->isRealFloatingType();
1126 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu7aa58f12011-09-02 20:58:51 +00001127
1128 // If we have two real floating types, convert the smaller operand
1129 // to the bigger result.
1130 if (LHSFloat && RHSFloat) {
Richard Trieucfe3f212011-09-06 18:38:41 +00001131 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +00001132 if (order > 0) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001133 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
Richard Trieucfe3f212011-09-06 18:38:41 +00001134 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +00001135 }
1136
1137 assert(order < 0 && "illegal float comparison");
Richard Trieuba63ce62011-09-09 01:45:06 +00001138 if (!IsCompAssign)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001139 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
Richard Trieucfe3f212011-09-06 18:38:41 +00001140 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +00001141 }
1142
Ahmed Bougacha5b639082015-05-29 22:54:57 +00001143 if (LHSFloat) {
1144 // Half FP has to be promoted to float unless it is natively supported
1145 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1146 LHSType = S.Context.FloatTy;
1147
Richard Trieucfe3f212011-09-06 18:38:41 +00001148 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001149 /*convertFloat=*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +00001150 /*convertInt=*/ true);
Ahmed Bougacha5b639082015-05-29 22:54:57 +00001151 }
Richard Trieu7aa58f12011-09-02 20:58:51 +00001152 assert(RHSFloat);
Richard Trieucfe3f212011-09-06 18:38:41 +00001153 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +00001154 /*convertInt=*/ true,
Richard Trieuba63ce62011-09-09 01:45:06 +00001155 /*convertFloat=*/!IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +00001156}
1157
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001158/// \brief Diagnose attempts to convert between __float128 and long double if
1159/// there is no support for such conversion. Helper function of
1160/// UsualArithmeticConversions().
1161static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1162 QualType RHSType) {
1163 /* No issue converting if at least one of the types is not a floating point
1164 type or the two types have the same rank.
1165 */
1166 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1167 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1168 return false;
1169
1170 assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1171 "The remaining types must be floating point types.");
1172
1173 auto *LHSComplex = LHSType->getAs<ComplexType>();
1174 auto *RHSComplex = RHSType->getAs<ComplexType>();
1175
1176 QualType LHSElemType = LHSComplex ?
1177 LHSComplex->getElementType() : LHSType;
1178 QualType RHSElemType = RHSComplex ?
1179 RHSComplex->getElementType() : RHSType;
1180
1181 // No issue if the two types have the same representation
1182 if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1183 &S.Context.getFloatTypeSemantics(RHSElemType))
1184 return false;
1185
1186 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1187 RHSElemType == S.Context.LongDoubleTy);
1188 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1189 RHSElemType == S.Context.Float128Ty);
1190
1191 /* We've handled the situation where __float128 and long double have the same
1192 representation. The only other allowable conversion is if long double is
1193 really just double.
1194 */
1195 return Float128AndLongDouble &&
1196 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1197 &llvm::APFloat::IEEEdouble);
1198}
1199
Bill Schmidteb03ae22013-02-01 15:34:29 +00001200typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
Richard Trieu7aa58f12011-09-02 20:58:51 +00001201
Bill Schmidteb03ae22013-02-01 15:34:29 +00001202namespace {
1203/// These helper callbacks are placed in an anonymous namespace to
1204/// permit their use as function template parameters.
1205ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1206 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1207}
Richard Trieu7aa58f12011-09-02 20:58:51 +00001208
Bill Schmidteb03ae22013-02-01 15:34:29 +00001209ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1210 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1211 CK_IntegralComplexCast);
1212}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001213}
Richard Trieu7aa58f12011-09-02 20:58:51 +00001214
1215/// \brief Handle integer arithmetic conversions. Helper function of
1216/// UsualArithmeticConversions()
Bill Schmidteb03ae22013-02-01 15:34:29 +00001217template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001218static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1219 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001220 QualType RHSType, bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +00001221 // The rules for this case are in C99 6.3.1.8
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001222 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1223 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1224 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1225 if (LHSSigned == RHSSigned) {
Richard Trieu7aa58f12011-09-02 20:58:51 +00001226 // Same signedness; use the higher-ranked type
1227 if (order >= 0) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001228 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001229 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +00001230 } else if (!IsCompAssign)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001231 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001232 return RHSType;
1233 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +00001234 // The unsigned type has greater than or equal rank to the
1235 // signed type, so use the unsigned type
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001236 if (RHSSigned) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001237 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001238 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +00001239 } else if (!IsCompAssign)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001240 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001241 return RHSType;
1242 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +00001243 // The two types are different widths; if we are here, that
1244 // means the signed type is larger than the unsigned type, so
1245 // use the signed type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001246 if (LHSSigned) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001247 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001248 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +00001249 } else if (!IsCompAssign)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001250 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001251 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +00001252 } else {
1253 // The signed type is higher-ranked than the unsigned type,
1254 // but isn't actually any bigger (like unsigned int and long
1255 // on most 32-bit systems). Use the unsigned type corresponding
1256 // to the signed type.
1257 QualType result =
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001258 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001259 RHS = (*doRHSCast)(S, RHS.get(), result);
Richard Trieuba63ce62011-09-09 01:45:06 +00001260 if (!IsCompAssign)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001261 LHS = (*doLHSCast)(S, LHS.get(), result);
Richard Trieu7aa58f12011-09-02 20:58:51 +00001262 return result;
1263 }
1264}
1265
Bill Schmidteb03ae22013-02-01 15:34:29 +00001266/// \brief Handle conversions with GCC complex int extension. Helper function
1267/// of UsualArithmeticConversions()
1268static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1269 ExprResult &RHS, QualType LHSType,
1270 QualType RHSType,
1271 bool IsCompAssign) {
1272 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1273 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1274
1275 if (LHSComplexInt && RHSComplexInt) {
1276 QualType LHSEltType = LHSComplexInt->getElementType();
1277 QualType RHSEltType = RHSComplexInt->getElementType();
1278 QualType ScalarType =
1279 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1280 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1281
1282 return S.Context.getComplexType(ScalarType);
1283 }
1284
1285 if (LHSComplexInt) {
1286 QualType LHSEltType = LHSComplexInt->getElementType();
1287 QualType ScalarType =
1288 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1289 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1290 QualType ComplexType = S.Context.getComplexType(ScalarType);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001291 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
Bill Schmidteb03ae22013-02-01 15:34:29 +00001292 CK_IntegralRealToComplex);
1293
1294 return ComplexType;
1295 }
1296
1297 assert(RHSComplexInt);
1298
1299 QualType RHSEltType = RHSComplexInt->getElementType();
1300 QualType ScalarType =
1301 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1302 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1303 QualType ComplexType = S.Context.getComplexType(ScalarType);
1304
1305 if (!IsCompAssign)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001306 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
Bill Schmidteb03ae22013-02-01 15:34:29 +00001307 CK_IntegralRealToComplex);
1308 return ComplexType;
1309}
1310
Chris Lattner513165e2008-07-25 21:10:04 +00001311/// UsualArithmeticConversions - Performs various conversions that are common to
1312/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +00001313/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +00001314/// responsible for emitting appropriate error diagnostics.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001315QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00001316 bool IsCompAssign) {
1317 if (!IsCompAssign) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001318 LHS = UsualUnaryConversions(LHS.get());
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001319 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001320 return QualType();
1321 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00001322
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001323 RHS = UsualUnaryConversions(RHS.get());
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001324 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001325 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001326
Mike Stump11289f42009-09-09 15:08:12 +00001327 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +00001328 // For example, "const float" and "float" are equivalent.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001329 QualType LHSType =
1330 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1331 QualType RHSType =
1332 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001333
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001334 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1335 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1336 LHSType = AtomicLHS->getValueType();
1337
Douglas Gregora11693b2008-11-12 17:17:38 +00001338 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001339 if (LHSType == RHSType)
1340 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +00001341
1342 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1343 // The caller can deal with this (e.g. pointer + int).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001344 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001345 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001346
John McCalld005ac92010-11-13 08:17:45 +00001347 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001348 QualType LHSUnpromotedType = LHSType;
1349 if (LHSType->isPromotableIntegerType())
1350 LHSType = Context.getPromotedIntegerType(LHSType);
1351 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +00001352 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001353 LHSType = LHSBitfieldPromoteTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00001354 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001355 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +00001356
John McCalld005ac92010-11-13 08:17:45 +00001357 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001358 if (LHSType == RHSType)
1359 return LHSType;
John McCalld005ac92010-11-13 08:17:45 +00001360
1361 // At this point, we have two different arithmetic types.
1362
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001363 // Diagnose attempts to convert between __float128 and long double where
1364 // such conversions currently can't be handled.
1365 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1366 return QualType();
1367
John McCalld005ac92010-11-13 08:17:45 +00001368 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001369 if (LHSType->isComplexType() || RHSType->isComplexType())
1370 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001371 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001372
1373 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001374 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1375 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001376 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001377
1378 // Handle GCC complex int extension.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001379 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer499c68b2011-09-06 19:57:14 +00001380 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001381 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001382
1383 // Finally, we have two differing integer types.
Bill Schmidteb03ae22013-02-01 15:34:29 +00001384 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1385 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
Douglas Gregora11693b2008-11-12 17:17:38 +00001386}
1387
Bill Schmidteb03ae22013-02-01 15:34:29 +00001388
Chris Lattner513165e2008-07-25 21:10:04 +00001389//===----------------------------------------------------------------------===//
1390// Semantic Analysis for various Expression Types
1391//===----------------------------------------------------------------------===//
1392
1393
Peter Collingbourne91147592011-04-15 00:35:48 +00001394ExprResult
1395Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1396 SourceLocation DefaultLoc,
1397 SourceLocation RParenLoc,
1398 Expr *ControllingExpr,
Dmitri Gribenko82360372013-05-10 13:06:58 +00001399 ArrayRef<ParsedType> ArgTypes,
1400 ArrayRef<Expr *> ArgExprs) {
Richard Trieuba63ce62011-09-09 01:45:06 +00001401 unsigned NumAssocs = ArgTypes.size();
1402 assert(NumAssocs == ArgExprs.size());
Peter Collingbourne91147592011-04-15 00:35:48 +00001403
Peter Collingbourne91147592011-04-15 00:35:48 +00001404 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1405 for (unsigned i = 0; i < NumAssocs; ++i) {
Dmitri Gribenko82360372013-05-10 13:06:58 +00001406 if (ArgTypes[i])
1407 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
Peter Collingbourne91147592011-04-15 00:35:48 +00001408 else
Craig Topperc3ec1492014-05-26 06:22:03 +00001409 Types[i] = nullptr;
Peter Collingbourne91147592011-04-15 00:35:48 +00001410 }
1411
1412 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
Dmitri Gribenko82360372013-05-10 13:06:58 +00001413 ControllingExpr,
1414 llvm::makeArrayRef(Types, NumAssocs),
1415 ArgExprs);
Benjamin Kramer34623762011-04-15 11:21:57 +00001416 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +00001417 return ER;
1418}
1419
1420ExprResult
1421Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1422 SourceLocation DefaultLoc,
1423 SourceLocation RParenLoc,
1424 Expr *ControllingExpr,
Dmitri Gribenko82360372013-05-10 13:06:58 +00001425 ArrayRef<TypeSourceInfo *> Types,
1426 ArrayRef<Expr *> Exprs) {
1427 unsigned NumAssocs = Types.size();
1428 assert(NumAssocs == Exprs.size());
Aaron Ballmanb035cd72015-11-05 00:06:05 +00001429
1430 // Decay and strip qualifiers for the controlling expression type, and handle
1431 // placeholder type replacement. See committee discussion from WG14 DR423.
Aaron Ballman558995c2016-02-23 18:55:15 +00001432 {
1433 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
1434 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1435 if (R.isInvalid())
1436 return ExprError();
1437 ControllingExpr = R.get();
1438 }
John McCall587b3482013-02-12 02:08:12 +00001439
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00001440 // The controlling expression is an unevaluated operand, so side effects are
1441 // likely unintended.
1442 if (ActiveTemplateInstantiations.empty() &&
1443 ControllingExpr->HasSideEffects(Context, false))
1444 Diag(ControllingExpr->getExprLoc(),
1445 diag::warn_side_effects_unevaluated_context);
1446
Peter Collingbourne91147592011-04-15 00:35:48 +00001447 bool TypeErrorFound = false,
1448 IsResultDependent = ControllingExpr->isTypeDependent(),
1449 ContainsUnexpandedParameterPack
1450 = ControllingExpr->containsUnexpandedParameterPack();
1451
1452 for (unsigned i = 0; i < NumAssocs; ++i) {
1453 if (Exprs[i]->containsUnexpandedParameterPack())
1454 ContainsUnexpandedParameterPack = true;
1455
1456 if (Types[i]) {
1457 if (Types[i]->getType()->containsUnexpandedParameterPack())
1458 ContainsUnexpandedParameterPack = true;
1459
1460 if (Types[i]->getType()->isDependentType()) {
1461 IsResultDependent = true;
1462 } else {
Benjamin Kramere56f3932011-12-23 17:00:35 +00001463 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbourne91147592011-04-15 00:35:48 +00001464 // complete object type other than a variably modified type."
1465 unsigned D = 0;
1466 if (Types[i]->getType()->isIncompleteType())
1467 D = diag::err_assoc_type_incomplete;
1468 else if (!Types[i]->getType()->isObjectType())
1469 D = diag::err_assoc_type_nonobject;
1470 else if (Types[i]->getType()->isVariablyModifiedType())
1471 D = diag::err_assoc_type_variably_modified;
1472
1473 if (D != 0) {
1474 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1475 << Types[i]->getTypeLoc().getSourceRange()
1476 << Types[i]->getType();
1477 TypeErrorFound = true;
1478 }
1479
Benjamin Kramere56f3932011-12-23 17:00:35 +00001480 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbourne91147592011-04-15 00:35:48 +00001481 // selection shall specify compatible types."
1482 for (unsigned j = i+1; j < NumAssocs; ++j)
1483 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1484 Context.typesAreCompatible(Types[i]->getType(),
1485 Types[j]->getType())) {
1486 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1487 diag::err_assoc_compatible_types)
1488 << Types[j]->getTypeLoc().getSourceRange()
1489 << Types[j]->getType()
1490 << Types[i]->getType();
1491 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1492 diag::note_compat_assoc)
1493 << Types[i]->getTypeLoc().getSourceRange()
1494 << Types[i]->getType();
1495 TypeErrorFound = true;
1496 }
1497 }
1498 }
1499 }
1500 if (TypeErrorFound)
1501 return ExprError();
1502
1503 // If we determined that the generic selection is result-dependent, don't
1504 // try to compute the result expression.
1505 if (IsResultDependent)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001506 return new (Context) GenericSelectionExpr(
1507 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1508 ContainsUnexpandedParameterPack);
Peter Collingbourne91147592011-04-15 00:35:48 +00001509
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001510 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +00001511 unsigned DefaultIndex = -1U;
1512 for (unsigned i = 0; i < NumAssocs; ++i) {
1513 if (!Types[i])
1514 DefaultIndex = i;
1515 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1516 Types[i]->getType()))
1517 CompatIndices.push_back(i);
1518 }
1519
Benjamin Kramere56f3932011-12-23 17:00:35 +00001520 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbourne91147592011-04-15 00:35:48 +00001521 // type compatible with at most one of the types named in its generic
1522 // association list."
1523 if (CompatIndices.size() > 1) {
1524 // We strip parens here because the controlling expression is typically
1525 // parenthesized in macro definitions.
1526 ControllingExpr = ControllingExpr->IgnoreParens();
1527 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1528 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1529 << (unsigned) CompatIndices.size();
Craig Topperdfe29ae2015-12-21 06:35:56 +00001530 for (unsigned I : CompatIndices) {
1531 Diag(Types[I]->getTypeLoc().getBeginLoc(),
Peter Collingbourne91147592011-04-15 00:35:48 +00001532 diag::note_compat_assoc)
Craig Topperdfe29ae2015-12-21 06:35:56 +00001533 << Types[I]->getTypeLoc().getSourceRange()
1534 << Types[I]->getType();
Peter Collingbourne91147592011-04-15 00:35:48 +00001535 }
1536 return ExprError();
1537 }
1538
Benjamin Kramere56f3932011-12-23 17:00:35 +00001539 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbourne91147592011-04-15 00:35:48 +00001540 // its controlling expression shall have type compatible with exactly one of
1541 // the types named in its generic association list."
1542 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1543 // We strip parens here because the controlling expression is typically
1544 // parenthesized in macro definitions.
1545 ControllingExpr = ControllingExpr->IgnoreParens();
1546 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1547 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1548 return ExprError();
1549 }
1550
Benjamin Kramere56f3932011-12-23 17:00:35 +00001551 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbourne91147592011-04-15 00:35:48 +00001552 // type name that is compatible with the type of the controlling expression,
1553 // then the result expression of the generic selection is the expression
1554 // in that generic association. Otherwise, the result expression of the
1555 // generic selection is the expression in the default generic association."
1556 unsigned ResultIndex =
1557 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1558
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001559 return new (Context) GenericSelectionExpr(
1560 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1561 ContainsUnexpandedParameterPack, ResultIndex);
Peter Collingbourne91147592011-04-15 00:35:48 +00001562}
1563
Richard Smith75b67d62012-03-08 01:34:56 +00001564/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1565/// location of the token and the offset of the ud-suffix within it.
1566static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1567 unsigned Offset) {
1568 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001569 S.getLangOpts());
Richard Smith75b67d62012-03-08 01:34:56 +00001570}
1571
Richard Smithbcc22fc2012-03-09 08:00:36 +00001572/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1573/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1574static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1575 IdentifierInfo *UDSuffix,
1576 SourceLocation UDSuffixLoc,
1577 ArrayRef<Expr*> Args,
1578 SourceLocation LitEndLoc) {
1579 assert(Args.size() <= 2 && "too many arguments for literal operator");
1580
1581 QualType ArgTy[2];
1582 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1583 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1584 if (ArgTy[ArgIdx]->isArrayType())
1585 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1586 }
1587
1588 DeclarationName OpName =
1589 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1590 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1591 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1592
1593 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1594 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
Richard Smithb8b41d32013-10-07 19:57:58 +00001595 /*AllowRaw*/false, /*AllowTemplate*/false,
1596 /*AllowStringTemplate*/false) == Sema::LOLR_Error)
Richard Smithbcc22fc2012-03-09 08:00:36 +00001597 return ExprError();
1598
1599 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1600}
1601
Steve Naroff83895f72007-09-16 03:34:24 +00001602/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001603/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1604/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1605/// multiple tokens. However, the common case is that StringToks points to one
1606/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001607///
John McCalldadc5752010-08-24 06:29:42 +00001608ExprResult
Craig Topper9d5583e2014-06-26 04:58:39 +00001609Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1610 assert(!StringToks.empty() && "Must have at least one string!");
Chris Lattner5b183d82006-11-10 05:03:26 +00001611
Craig Topper9d5583e2014-06-26 04:58:39 +00001612 StringLiteralParser Literal(StringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001613 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001614 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001615
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001616 SmallVector<SourceLocation, 4> StringTokLocs;
Craig Topperdfe29ae2015-12-21 06:35:56 +00001617 for (const Token &Tok : StringToks)
1618 StringTokLocs.push_back(Tok.getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001619
Richard Smithb8b41d32013-10-07 19:57:58 +00001620 QualType CharTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001621 StringLiteral::StringKind Kind = StringLiteral::Ascii;
Richard Smithb8b41d32013-10-07 19:57:58 +00001622 if (Literal.isWide()) {
1623 CharTy = Context.getWideCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001624 Kind = StringLiteral::Wide;
Richard Smithb8b41d32013-10-07 19:57:58 +00001625 } else if (Literal.isUTF8()) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00001626 Kind = StringLiteral::UTF8;
Richard Smithb8b41d32013-10-07 19:57:58 +00001627 } else if (Literal.isUTF16()) {
1628 CharTy = Context.Char16Ty;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001629 Kind = StringLiteral::UTF16;
Richard Smithb8b41d32013-10-07 19:57:58 +00001630 } else if (Literal.isUTF32()) {
1631 CharTy = Context.Char32Ty;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001632 Kind = StringLiteral::UTF32;
Richard Smithb8b41d32013-10-07 19:57:58 +00001633 } else if (Literal.isPascal()) {
1634 CharTy = Context.UnsignedCharTy;
1635 }
Douglas Gregorfb65e592011-07-27 05:40:30 +00001636
Richard Smithb8b41d32013-10-07 19:57:58 +00001637 QualType CharTyConst = CharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001638 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001639 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Richard Smithb8b41d32013-10-07 19:57:58 +00001640 CharTyConst.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001641
Chris Lattner36fc8792008-02-11 00:02:17 +00001642 // Get an array type for the string, according to C99 6.4.5. This includes
1643 // the nul terminator character as well as the string length for pascal
1644 // strings.
Richard Smithb8b41d32013-10-07 19:57:58 +00001645 QualType StrTy = Context.getConstantArrayType(CharTyConst,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001646 llvm::APInt(32, Literal.GetNumStringChars()+1),
Richard Smithb8b41d32013-10-07 19:57:58 +00001647 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001648
Joey Gouly561bba22013-11-14 18:26:10 +00001649 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1650 if (getLangOpts().OpenCL) {
1651 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1652 }
1653
Chris Lattner5b183d82006-11-10 05:03:26 +00001654 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smithc67fdd42012-03-07 08:35:16 +00001655 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1656 Kind, Literal.Pascal, StrTy,
1657 &StringTokLocs[0],
1658 StringTokLocs.size());
1659 if (Literal.getUDSuffix().empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001660 return Lit;
Richard Smithc67fdd42012-03-07 08:35:16 +00001661
1662 // We're building a user-defined literal.
1663 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smith75b67d62012-03-08 01:34:56 +00001664 SourceLocation UDSuffixLoc =
1665 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1666 Literal.getUDSuffixOffset());
Richard Smithc67fdd42012-03-07 08:35:16 +00001667
Richard Smithbcc22fc2012-03-09 08:00:36 +00001668 // Make sure we're allowed user-defined literals here.
1669 if (!UDLScope)
1670 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1671
Richard Smithc67fdd42012-03-07 08:35:16 +00001672 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1673 // operator "" X (str, len)
1674 QualType SizeType = Context.getSizeType();
Richard Smithb8b41d32013-10-07 19:57:58 +00001675
1676 DeclarationName OpName =
1677 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1678 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1679 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1680
1681 QualType ArgTy[] = {
1682 Context.getArrayDecayedType(StrTy), SizeType
1683 };
1684
1685 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1686 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1687 /*AllowRaw*/false, /*AllowTemplate*/false,
1688 /*AllowStringTemplate*/true)) {
1689
1690 case LOLR_Cooked: {
1691 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1692 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1693 StringTokLocs[0]);
1694 Expr *Args[] = { Lit, LenArg };
1695
1696 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1697 }
1698
1699 case LOLR_StringTemplate: {
1700 TemplateArgumentListInfo ExplicitArgs;
1701
1702 unsigned CharBits = Context.getIntWidth(CharTy);
1703 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1704 llvm::APSInt Value(CharBits, CharIsUnsigned);
1705
1706 TemplateArgument TypeArg(CharTy);
1707 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1708 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1709
1710 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1711 Value = Lit->getCodeUnit(I);
1712 TemplateArgument Arg(Context, Value, CharTy);
1713 TemplateArgumentLocInfo ArgInfo;
1714 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1715 }
1716 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1717 &ExplicitArgs);
1718 }
1719 case LOLR_Raw:
1720 case LOLR_Template:
1721 llvm_unreachable("unexpected literal operator lookup result");
1722 case LOLR_Error:
1723 return ExprError();
1724 }
1725 llvm_unreachable("unexpected literal operator lookup result");
Chris Lattner5b183d82006-11-10 05:03:26 +00001726}
1727
John McCalldadc5752010-08-24 06:29:42 +00001728ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001729Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001730 SourceLocation Loc,
1731 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001732 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001733 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001734}
1735
John McCallf4cd4f92011-02-09 01:13:10 +00001736/// BuildDeclRefExpr - Build an expression that references a
1737/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001738ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001739Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001740 const DeclarationNameInfo &NameInfo,
Larisse Voufo39a1e502013-08-06 01:03:05 +00001741 const CXXScopeSpec *SS, NamedDecl *FoundD,
1742 const TemplateArgumentListInfo *TemplateArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001743 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00001744 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1745 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
Jacques Pienaar5bdd6772014-12-16 20:12:38 +00001746 if (CheckCUDATarget(Caller, Callee)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00001747 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
Jacques Pienaar5bdd6772014-12-16 20:12:38 +00001748 << IdentifyCUDATarget(Callee) << D->getIdentifier()
1749 << IdentifyCUDATarget(Caller);
Peter Collingbourne7277fe82011-10-02 23:49:40 +00001750 Diag(D->getLocation(), diag::note_previous_decl)
1751 << D->getIdentifier();
1752 return ExprError();
1753 }
1754 }
1755
Alexey Bataev07649fb2014-12-16 08:01:48 +00001756 bool RefersToCapturedVariable =
Alexey Bataevf841bd92014-12-16 07:00:22 +00001757 isa<VarDecl>(D) &&
1758 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
John McCall113bee02012-03-10 09:33:50 +00001759
Larisse Voufo39a1e502013-08-06 01:03:05 +00001760 DeclRefExpr *E;
1761 if (isa<VarTemplateSpecializationDecl>(D)) {
1762 VarTemplateSpecializationDecl *VarSpec =
1763 cast<VarTemplateSpecializationDecl>(D);
1764
Alexey Bataev19acc3d2015-01-12 10:17:46 +00001765 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1766 : NestedNameSpecifierLoc(),
1767 VarSpec->getTemplateKeywordLoc(), D,
1768 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1769 FoundD, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001770 } else {
1771 assert(!TemplateArgs && "No template arguments for non-variable"
Alp Tokerf6a24ce2013-12-05 16:25:25 +00001772 " template specialization references");
Alexey Bataev07649fb2014-12-16 08:01:48 +00001773 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1774 : NestedNameSpecifierLoc(),
1775 SourceLocation(), D, RefersToCapturedVariable,
1776 NameInfo, Ty, VK, FoundD);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001777 }
Mike Stump11289f42009-09-09 15:08:12 +00001778
Eli Friedmanfa0df832012-02-02 03:46:19 +00001779 MarkDeclRefReferenced(E);
John McCall086a4642010-11-24 05:12:34 +00001780
John McCall460ce582015-10-22 18:38:17 +00001781 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001782 Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1783 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
Fariborz Jahanian6f829e32013-05-21 21:20:26 +00001784 recordUseOfEvaluatedWeak(E);
Jordan Rose657b5f42012-09-28 22:21:35 +00001785
Olivier Goffart63a20832016-05-09 07:09:51 +00001786 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1787 UnusedPrivateFields.remove(FD);
1788 // Just in case we're building an illegal pointer-to-member.
1789 if (FD->isBitField())
1790 E->setObjectKind(OK_BitField);
1791 }
John McCall086a4642010-11-24 05:12:34 +00001792
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001793 return E;
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001794}
1795
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001796/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001797/// possibly a list of template arguments.
1798///
1799/// If this produces template arguments, it is permitted to call
1800/// DecomposeTemplateName.
1801///
1802/// This actually loses a lot of source location information for
1803/// non-standard name kinds; we should consider preserving that in
1804/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001805void
1806Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1807 TemplateArgumentListInfo &Buffer,
1808 DeclarationNameInfo &NameInfo,
1809 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001810 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1811 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1812 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1813
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001814 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
John McCall10eae182009-11-30 22:42:35 +00001815 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001816 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001817
John McCall3e56fd42010-08-23 07:28:44 +00001818 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001819 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001820 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001821 TemplateArgs = &Buffer;
1822 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001823 NameInfo = GetNameFromUnqualifiedId(Id);
Craig Topperc3ec1492014-05-26 06:22:03 +00001824 TemplateArgs = nullptr;
John McCall10eae182009-11-30 22:42:35 +00001825 }
1826}
1827
Kaelyn Takatab16e6322014-11-20 22:06:40 +00001828static void emitEmptyLookupTypoDiagnostic(
1829 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1830 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1831 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1832 DeclContext *Ctx =
1833 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1834 if (!TC) {
1835 // Emit a special diagnostic for failed member lookups.
1836 // FIXME: computing the declaration context might fail here (?)
1837 if (Ctx)
1838 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1839 << SS.getRange();
1840 else
1841 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1842 return;
1843 }
1844
1845 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1846 bool DroppedSpecifier =
1847 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
Richard Smithde6d6c42015-12-29 19:43:10 +00001848 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1849 ? diag::note_implicit_param_decl
1850 : diag::note_previous_decl;
Kaelyn Takatab16e6322014-11-20 22:06:40 +00001851 if (!Ctx)
1852 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1853 SemaRef.PDiag(NoteID));
1854 else
1855 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1856 << Typo << Ctx << DroppedSpecifier
1857 << SS.getRange(),
1858 SemaRef.PDiag(NoteID));
1859}
1860
John McCalld681c392009-12-16 08:11:27 +00001861/// Diagnose an empty lookup.
1862///
1863/// \return false if new lookup candidates were found
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001864bool
1865Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1866 std::unique_ptr<CorrectionCandidateCallback> CCC,
1867 TemplateArgumentListInfo *ExplicitTemplateArgs,
Kaelyn Takatab16e6322014-11-20 22:06:40 +00001868 ArrayRef<Expr *> Args, TypoExpr **Out) {
John McCalld681c392009-12-16 08:11:27 +00001869 DeclarationName Name = R.getLookupName();
1870
John McCalld681c392009-12-16 08:11:27 +00001871 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001872 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001873 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1874 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001875 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001876 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001877 diagnostic_suggest = diag::err_undeclared_use_suggest;
1878 }
John McCalld681c392009-12-16 08:11:27 +00001879
Douglas Gregor598b08f2009-12-31 05:20:13 +00001880 // If the original lookup was an unqualified lookup, fake an
1881 // unqualified lookup. This is useful when (for example) the
1882 // original lookup would not have found something because it was a
1883 // dependent name.
Richard Smith42fd9ef2015-10-05 20:05:21 +00001884 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
Francois Pichetde232cb2011-11-25 01:10:54 +00001885 while (DC) {
John McCalld681c392009-12-16 08:11:27 +00001886 if (isa<CXXRecordDecl>(DC)) {
1887 LookupQualifiedName(R, DC);
1888
1889 if (!R.empty()) {
1890 // Don't give errors about ambiguities in this lookup.
1891 R.suppressDiagnostics();
1892
Francois Pichet857f9d62011-11-17 03:44:24 +00001893 // During a default argument instantiation the CurContext points
1894 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1895 // function parameter list, hence add an explicit check.
1896 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1897 ActiveTemplateInstantiations.back().Kind ==
1898 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCalld681c392009-12-16 08:11:27 +00001899 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1900 bool isInstance = CurMethod &&
1901 CurMethod->isInstance() &&
Francois Pichet857f9d62011-11-17 03:44:24 +00001902 DC == CurMethod->getParent() && !isDefaultArgument;
John McCalld681c392009-12-16 08:11:27 +00001903
1904 // Give a code modification hint to insert 'this->'.
1905 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1906 // Actually quite difficult!
Alp Tokerbfa39342014-01-14 12:51:41 +00001907 if (getLangOpts().MSVCCompat)
Reid Kleckner10ca24c2014-06-11 00:01:28 +00001908 diagnostic = diag::ext_found_via_dependent_bases_lookup;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001909 if (isInstance) {
Nico Weber3c10fb12012-06-22 16:39:39 +00001910 Diag(R.getNameLoc(), diagnostic) << Name
1911 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
Nico Weber3c10fb12012-06-22 16:39:39 +00001912 CheckCXXThisCapture(R.getNameLoc());
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001913 } else {
John McCalld681c392009-12-16 08:11:27 +00001914 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001915 }
John McCalld681c392009-12-16 08:11:27 +00001916
1917 // Do we really want to note all of these?
Craig Topperdfe29ae2015-12-21 06:35:56 +00001918 for (NamedDecl *D : R)
1919 Diag(D->getLocation(), diag::note_dependent_var_use);
John McCalld681c392009-12-16 08:11:27 +00001920
Francois Pichet857f9d62011-11-17 03:44:24 +00001921 // Return true if we are inside a default argument instantiation
1922 // and the found name refers to an instance member function, otherwise
1923 // the function calling DiagnoseEmptyLookup will try to create an
1924 // implicit member call and this is wrong for default argument.
1925 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1926 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1927 return true;
1928 }
1929
John McCalld681c392009-12-16 08:11:27 +00001930 // Tell the callee to try to recover.
1931 return false;
1932 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001933
1934 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001935 }
Francois Pichetde232cb2011-11-25 01:10:54 +00001936
1937 // In Microsoft mode, if we are performing lookup from within a friend
1938 // function definition declared at class scope then we must set
1939 // DC to the lexical parent to be able to search into the parent
1940 // class.
Alp Tokerbfa39342014-01-14 12:51:41 +00001941 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
Francois Pichetde232cb2011-11-25 01:10:54 +00001942 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1943 DC->getLexicalParent()->isRecord())
1944 DC = DC->getLexicalParent();
1945 else
1946 DC = DC->getParent();
John McCalld681c392009-12-16 08:11:27 +00001947 }
1948
Douglas Gregor598b08f2009-12-31 05:20:13 +00001949 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001950 TypoCorrection Corrected;
Kaelyn Takatab16e6322014-11-20 22:06:40 +00001951 if (S && Out) {
1952 SourceLocation TypoLoc = R.getNameLoc();
1953 assert(!ExplicitTemplateArgs &&
1954 "Diagnosing an empty lookup with explicit template args!");
1955 *Out = CorrectTypoDelayed(
1956 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1957 [=](const TypoCorrection &TC) {
1958 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1959 diagnostic, diagnostic_suggest);
1960 },
1961 nullptr, CTK_ErrorRecovery);
1962 if (*Out)
1963 return true;
1964 } else if (S && (Corrected =
1965 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1966 &SS, std::move(CCC), CTK_ErrorRecovery))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001967 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
Richard Smithf9b15102013-08-17 00:46:16 +00001968 bool DroppedSpecifier =
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00001969 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001970 R.setLookupName(Corrected.getCorrection());
1971
Richard Smithf9b15102013-08-17 00:46:16 +00001972 bool AcceptableWithRecovery = false;
1973 bool AcceptableWithoutRecovery = false;
Richard Smithde6d6c42015-12-29 19:43:10 +00001974 NamedDecl *ND = Corrected.getFoundDecl();
Richard Smithf9b15102013-08-17 00:46:16 +00001975 if (ND) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001976 if (Corrected.isOverloaded()) {
Richard Smith100b24a2014-04-17 01:52:14 +00001977 OverloadCandidateSet OCS(R.getNameLoc(),
1978 OverloadCandidateSet::CSK_Normal);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001979 OverloadCandidateSet::iterator Best;
Craig Topperdfe29ae2015-12-21 06:35:56 +00001980 for (NamedDecl *CD : Corrected) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001981 if (FunctionTemplateDecl *FTD =
Craig Topperdfe29ae2015-12-21 06:35:56 +00001982 dyn_cast<FunctionTemplateDecl>(CD))
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001983 AddTemplateOverloadCandidate(
1984 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001985 Args, OCS);
Craig Topperdfe29ae2015-12-21 06:35:56 +00001986 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001987 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1988 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001989 Args, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001990 }
1991 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001992 case OR_Success:
Richard Smithde6d6c42015-12-29 19:43:10 +00001993 ND = Best->FoundDecl;
Richard Smithf9b15102013-08-17 00:46:16 +00001994 Corrected.setCorrectionDecl(ND);
1995 break;
1996 default:
1997 // FIXME: Arbitrarily pick the first declaration for the note.
1998 Corrected.setCorrectionDecl(ND);
1999 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00002000 }
2001 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002002 R.addDecl(ND);
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00002003 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2004 CXXRecordDecl *Record = nullptr;
2005 if (Corrected.getCorrectionSpecifier()) {
2006 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2007 Record = Ty->getAsCXXRecordDecl();
2008 }
2009 if (!Record)
2010 Record = cast<CXXRecordDecl>(
2011 ND->getDeclContext()->getRedeclContext());
2012 R.setNamingClass(Record);
2013 }
Ted Kremenekc6ebda12013-02-21 21:40:44 +00002014
Richard Smithde6d6c42015-12-29 19:43:10 +00002015 auto *UnderlyingND = ND->getUnderlyingDecl();
2016 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2017 isa<FunctionTemplateDecl>(UnderlyingND);
Richard Smithf9b15102013-08-17 00:46:16 +00002018 // FIXME: If we ended up with a typo for a type name or
2019 // Objective-C class name, we're in trouble because the parser
2020 // is in the wrong place to recover. Suggest the typo
2021 // correction, but don't make it a fix-it since we're not going
2022 // to recover well anyway.
2023 AcceptableWithoutRecovery =
Richard Smithde6d6c42015-12-29 19:43:10 +00002024 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002025 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00002026 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002027 // because we aren't able to recover.
Richard Smithf9b15102013-08-17 00:46:16 +00002028 AcceptableWithoutRecovery = true;
2029 }
2030
2031 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
Richard Smithde6d6c42015-12-29 19:43:10 +00002032 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
Richard Smithf9b15102013-08-17 00:46:16 +00002033 ? diag::note_implicit_param_decl
2034 : diag::note_previous_decl;
Douglas Gregor25363982010-01-01 00:15:04 +00002035 if (SS.isEmpty())
Richard Smithf9b15102013-08-17 00:46:16 +00002036 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2037 PDiag(NoteID), AcceptableWithRecovery);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002038 else
Richard Smithf9b15102013-08-17 00:46:16 +00002039 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2040 << Name << computeDeclContext(SS, false)
2041 << DroppedSpecifier << SS.getRange(),
2042 PDiag(NoteID), AcceptableWithRecovery);
2043
2044 // Tell the callee whether to try to recover.
2045 return !AcceptableWithRecovery;
Douglas Gregor25363982010-01-01 00:15:04 +00002046 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00002047 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002048 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00002049
2050 // Emit a special diagnostic for failed member lookups.
2051 // FIXME: computing the declaration context might fail here (?)
2052 if (!SS.isEmpty()) {
2053 Diag(R.getNameLoc(), diag::err_no_member)
2054 << Name << computeDeclContext(SS, false)
2055 << SS.getRange();
2056 return true;
2057 }
2058
John McCalld681c392009-12-16 08:11:27 +00002059 // Give up, we can't recover.
2060 Diag(R.getNameLoc(), diagnostic) << Name;
2061 return true;
2062}
2063
Reid Kleckner10ca24c2014-06-11 00:01:28 +00002064/// In Microsoft mode, if we are inside a template class whose parent class has
2065/// dependent base classes, and we can't resolve an unqualified identifier, then
2066/// assume the identifier is a member of a dependent base class. We can only
2067/// recover successfully in static methods, instance methods, and other contexts
2068/// where 'this' is available. This doesn't precisely match MSVC's
2069/// instantiation model, but it's close enough.
2070static Expr *
2071recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2072 DeclarationNameInfo &NameInfo,
2073 SourceLocation TemplateKWLoc,
2074 const TemplateArgumentListInfo *TemplateArgs) {
2075 // Only try to recover from lookup into dependent bases in static methods or
2076 // contexts where 'this' is available.
2077 QualType ThisType = S.getCurrentThisType();
2078 const CXXRecordDecl *RD = nullptr;
2079 if (!ThisType.isNull())
2080 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2081 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2082 RD = MD->getParent();
2083 if (!RD || !RD->hasAnyDependentBases())
2084 return nullptr;
2085
2086 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2087 // is available, suggest inserting 'this->' as a fixit.
2088 SourceLocation Loc = NameInfo.getLoc();
Reid Kleckner13a97992014-06-11 21:57:15 +00002089 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2090 DB << NameInfo.getName() << RD;
Reid Kleckner10ca24c2014-06-11 00:01:28 +00002091
2092 if (!ThisType.isNull()) {
2093 DB << FixItHint::CreateInsertion(Loc, "this->");
2094 return CXXDependentScopeMemberExpr::Create(
2095 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2096 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2097 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2098 }
2099
2100 // Synthesize a fake NNS that points to the derived class. This will
2101 // perform name lookup during template instantiation.
2102 CXXScopeSpec SS;
2103 auto *NNS =
2104 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2105 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2106 return DependentScopeDeclRefExpr::Create(
2107 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2108 TemplateArgs);
2109}
2110
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002111ExprResult
2112Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2113 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2114 bool HasTrailingLParen, bool IsAddressOfOperand,
2115 std::unique_ptr<CorrectionCandidateCallback> CCC,
Kaelyn Takatab16e6322014-11-20 22:06:40 +00002116 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002117 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCalle66edc12009-11-24 19:00:30 +00002118 "cannot be direct & operand and have a trailing lparen");
John McCalle66edc12009-11-24 19:00:30 +00002119 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00002120 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00002121
John McCall10eae182009-11-30 22:42:35 +00002122 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00002123
2124 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002125 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00002126 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00002127 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00002128
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002129 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00002130 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002131 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002132
John McCalle66edc12009-11-24 19:00:30 +00002133 // C++ [temp.dep.expr]p3:
2134 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00002135 // -- an identifier that was declared with a dependent type,
2136 // (note: handled after lookup)
2137 // -- a template-id that is dependent,
2138 // (note: handled in BuildTemplateIdExpr)
2139 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00002140 // -- a nested-name-specifier that contains a class-name that
2141 // names a dependent type.
2142 // Determine whether this is a member of an unknown specialization;
2143 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00002144 bool DependentID = false;
2145 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2146 Name.getCXXNameType()->isDependentType()) {
2147 DependentID = true;
2148 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002149 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00002150 if (RequireCompleteDeclContext(SS, DC))
2151 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00002152 } else {
2153 DependentID = true;
2154 }
2155 }
2156
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002157 if (DependentID)
Abramo Bagnara7945c982012-01-27 09:46:47 +00002158 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2159 IsAddressOfOperand, TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002160
John McCalle66edc12009-11-24 19:00:30 +00002161 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00002162 LookupResult R(*this, NameInfo,
2163 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2164 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00002165 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00002166 // Lookup the template name again to correctly establish the context in
2167 // which it was found. This is really unfortunate as we already did the
2168 // lookup to determine that it was a template name in the first place. If
2169 // this becomes a performance hit, we can work harder to preserve those
2170 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00002171 bool MemberOfUnknownSpecialization;
2172 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2173 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00002174
2175 if (MemberOfUnknownSpecialization ||
2176 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnara7945c982012-01-27 09:46:47 +00002177 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2178 IsAddressOfOperand, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00002179 } else {
Benjamin Kramer46921442012-01-20 14:57:34 +00002180 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002181 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00002182
Douglas Gregora5226932011-02-04 13:35:07 +00002183 // If the result might be in a dependent base class, this is a dependent
2184 // id-expression.
2185 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnara7945c982012-01-27 09:46:47 +00002186 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2187 IsAddressOfOperand, TemplateArgs);
2188
John McCalle66edc12009-11-24 19:00:30 +00002189 // If this reference is in an Objective-C method, then we need to do
2190 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002191 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00002192 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00002193 if (E.isInvalid())
2194 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002195
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002196 if (Expr *Ex = E.getAs<Expr>())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002197 return Ex;
Steve Naroffebf4cb42008-06-02 23:03:37 +00002198 }
Chris Lattner59a25942008-03-31 00:36:02 +00002199 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00002200
John McCalle66edc12009-11-24 19:00:30 +00002201 if (R.isAmbiguous())
2202 return ExprError();
2203
Reid Kleckner59148b32014-06-09 23:16:24 +00002204 // This could be an implicitly declared function reference (legal in C90,
2205 // extension in C99, forbidden in C++).
2206 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2207 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2208 if (D) R.addDecl(D);
2209 }
2210
Douglas Gregor171c45a2009-02-18 21:56:37 +00002211 // Determine whether this name might be a candidate for
2212 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00002213 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00002214
John McCalle66edc12009-11-24 19:00:30 +00002215 if (R.empty() && !ADL) {
Reid Kleckner59148b32014-06-09 23:16:24 +00002216 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
Reid Kleckner10ca24c2014-06-11 00:01:28 +00002217 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2218 TemplateKWLoc, TemplateArgs))
2219 return E;
John McCalle66edc12009-11-24 19:00:30 +00002220 }
2221
Nikola Smiljanic1c125682014-07-09 05:42:35 +00002222 // Don't diagnose an empty lookup for inline assembly.
Reid Kleckner59148b32014-06-09 23:16:24 +00002223 if (IsInlineAsmIdentifier)
2224 return ExprError();
2225
John McCalle66edc12009-11-24 19:00:30 +00002226 // If this name wasn't predeclared and if this is not a function
2227 // call, diagnose the problem.
Kaelyn Takatab16e6322014-11-20 22:06:40 +00002228 TypoExpr *TE = nullptr;
2229 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2230 II, SS.isValid() ? SS.getScopeRep() : nullptr);
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002231 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00002232 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2233 "Typo correction callback misconfigured");
Kaelyn Takatab16e6322014-11-20 22:06:40 +00002234 if (CCC) {
2235 // Make sure the callback knows what the typo being diagnosed is.
2236 CCC->setTypoName(II);
2237 if (SS.isValid())
2238 CCC->setTypoNNS(SS.getScopeRep());
2239 }
Kaelyn Takata15867822014-11-21 18:48:04 +00002240 if (DiagnoseEmptyLookup(S, SS, R,
2241 CCC ? std::move(CCC) : std::move(DefaultValidator),
2242 nullptr, None, &TE)) {
Kaelyn Takatab16e6322014-11-20 22:06:40 +00002243 if (TE && KeywordReplacement) {
2244 auto &State = getTypoExprState(TE);
2245 auto BestTC = State.Consumer->getNextCorrection();
2246 if (BestTC.isKeyword()) {
2247 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2248 if (State.DiagHandler)
2249 State.DiagHandler(BestTC);
2250 KeywordReplacement->startToken();
2251 KeywordReplacement->setKind(II->getTokenID());
2252 KeywordReplacement->setIdentifierInfo(II);
2253 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2254 // Clean up the state associated with the TypoExpr, since it has
2255 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2256 clearDelayedTypo(TE);
2257 // Signal that a correction to a keyword was performed by returning a
2258 // valid-but-null ExprResult.
2259 return (Expr*)nullptr;
2260 }
2261 State.Consumer->resetCorrectionStream();
2262 }
2263 return TE ? TE : ExprError();
2264 }
Francois Pichetd8e4e412011-09-24 10:38:05 +00002265
Reid Kleckner59148b32014-06-09 23:16:24 +00002266 assert(!R.empty() &&
2267 "DiagnoseEmptyLookup returned false but added no results");
2268
2269 // If we found an Objective-C instance variable, let
2270 // LookupInObjCMethod build the appropriate expression to
2271 // reference the ivar.
2272 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2273 R.clear();
2274 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2275 // In a hopelessly buggy code, Objective-C instance variable
2276 // lookup fails and no expression will be built to reference it.
2277 if (!E.isInvalid() && !E.get())
Chad Rosierb9aff1e2013-05-24 18:32:55 +00002278 return ExprError();
Reid Kleckner59148b32014-06-09 23:16:24 +00002279 return E;
Steve Naroff92e30f82007-04-02 22:35:25 +00002280 }
Chris Lattner17ed4872006-11-20 04:58:19 +00002281 }
Mike Stump11289f42009-09-09 15:08:12 +00002282
John McCalle66edc12009-11-24 19:00:30 +00002283 // This is guaranteed from this point on.
2284 assert(!R.empty() || ADL);
2285
John McCall2d74de92009-12-01 22:10:20 +00002286 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00002287 // C++ [class.mfct.non-static]p3:
2288 // When an id-expression that is not part of a class member access
2289 // syntax and not used to form a pointer to member is used in the
2290 // body of a non-static member function of class X, if name lookup
2291 // resolves the name in the id-expression to a non-static non-type
2292 // member of some class C, the id-expression is transformed into a
2293 // class member access expression using (*this) as the
2294 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00002295 //
2296 // But we don't actually need to do this for '&' operands if R
2297 // resolved to a function or overloaded function set, because the
2298 // expression is ill-formed if it actually works out to be a
2299 // non-static member function:
2300 //
2301 // C++ [expr.ref]p4:
2302 // Otherwise, if E1.E2 refers to a non-static member function. . .
2303 // [t]he expression can be used only as the left-hand operand of a
2304 // member function call.
2305 //
2306 // There are other safeguards against such uses, but it's important
2307 // to get this right here so that we don't end up making a
2308 // spuriously dependent expression if we're inside a dependent
2309 // instance method.
John McCall57500772009-12-16 12:17:52 +00002310 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00002311 bool MightBeImplicitMember;
Richard Trieuba63ce62011-09-09 01:45:06 +00002312 if (!IsAddressOfOperand)
John McCall8d08b9b2010-08-27 09:08:28 +00002313 MightBeImplicitMember = true;
2314 else if (!SS.isEmpty())
2315 MightBeImplicitMember = false;
2316 else if (R.isOverloadedResult())
2317 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00002318 else if (R.isUnresolvableResult())
2319 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00002320 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00002321 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
Reid Kleckner0a0c8892013-06-19 16:37:23 +00002322 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2323 isa<MSPropertyDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00002324
2325 if (MightBeImplicitMember)
Abramo Bagnara7945c982012-01-27 09:46:47 +00002326 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00002327 R, TemplateArgs, S);
John McCallb53bbd42009-11-22 01:44:31 +00002328 }
2329
Larisse Voufo39a1e502013-08-06 01:03:05 +00002330 if (TemplateArgs || TemplateKWLoc.isValid()) {
2331
2332 // In C++1y, if this is a variable template id, then check it
2333 // in BuildTemplateIdExpr().
2334 // The single lookup result must be a variable template declaration.
2335 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2336 Id.TemplateId->Kind == TNK_Var_template) {
2337 assert(R.getAsSingle<VarTemplateDecl>() &&
2338 "There should only be one declaration found.");
2339 }
2340
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002341 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002342 }
John McCallb53bbd42009-11-22 01:44:31 +00002343
John McCalle66edc12009-11-24 19:00:30 +00002344 return BuildDeclarationNameExpr(SS, R, ADL);
2345}
2346
John McCall10eae182009-11-30 22:42:35 +00002347/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2348/// declaration name, generally during template instantiation.
2349/// There's a large number of things which don't need to be done along
2350/// this path.
Aaron Ballman6924dcd2015-09-01 14:49:24 +00002351ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2352 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2353 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
Richard Smith40c180d2012-10-23 19:56:01 +00002354 DeclContext *DC = computeDeclContext(SS, false);
2355 if (!DC)
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002356 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002357 NameInfo, /*TemplateArgs=*/nullptr);
John McCalle66edc12009-11-24 19:00:30 +00002358
John McCall0b66eb32010-05-01 00:40:08 +00002359 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00002360 return ExprError();
2361
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002362 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00002363 LookupQualifiedName(R, DC);
2364
2365 if (R.isAmbiguous())
2366 return ExprError();
2367
Richard Smith40c180d2012-10-23 19:56:01 +00002368 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2369 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002370 NameInfo, /*TemplateArgs=*/nullptr);
Richard Smith40c180d2012-10-23 19:56:01 +00002371
John McCalle66edc12009-11-24 19:00:30 +00002372 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002373 Diag(NameInfo.getLoc(), diag::err_no_member)
2374 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002375 return ExprError();
2376 }
2377
Reid Kleckner32506ed2014-06-12 23:03:48 +00002378 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2379 // Diagnose a missing typename if this resolved unambiguously to a type in
2380 // a dependent context. If we can recover with a type, downgrade this to
2381 // a warning in Microsoft compatibility mode.
2382 unsigned DiagID = diag::err_typename_missing;
2383 if (RecoveryTSI && getLangOpts().MSVCCompat)
2384 DiagID = diag::ext_typename_missing;
2385 SourceLocation Loc = SS.getBeginLoc();
2386 auto D = Diag(Loc, DiagID);
2387 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2388 << SourceRange(Loc, NameInfo.getEndLoc());
2389
2390 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2391 // context.
2392 if (!RecoveryTSI)
2393 return ExprError();
2394
2395 // Only issue the fixit if we're prepared to recover.
2396 D << FixItHint::CreateInsertion(Loc, "typename ");
2397
2398 // Recover by pretending this was an elaborated type.
2399 QualType Ty = Context.getTypeDeclType(TD);
2400 TypeLocBuilder TLB;
2401 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2402
2403 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2404 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2405 QTL.setElaboratedKeywordLoc(SourceLocation());
2406 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2407
2408 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2409
2410 return ExprEmpty();
Reid Kleckner377c1592014-06-10 23:29:48 +00002411 }
2412
Richard Smithdb2630f2012-10-21 03:28:35 +00002413 // Defend against this resolving to an implicit member access. We usually
2414 // won't get here if this might be a legitimate a class member (we end up in
2415 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2416 // a pointer-to-member or in an unevaluated context in C++11.
2417 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2418 return BuildPossibleImplicitMemberExpr(SS,
2419 /*TemplateKWLoc=*/SourceLocation(),
Aaron Ballman6924dcd2015-09-01 14:49:24 +00002420 R, /*TemplateArgs=*/nullptr, S);
Richard Smithdb2630f2012-10-21 03:28:35 +00002421
2422 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
John McCalle66edc12009-11-24 19:00:30 +00002423}
2424
2425/// LookupInObjCMethod - The parser has read a name in, and Sema has
2426/// detected that we're currently inside an ObjC method. Perform some
2427/// additional lookup.
2428///
2429/// Ideally, most of this would be done by lookup, but there's
2430/// actually quite a lot of extra work involved.
2431///
2432/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00002433ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002434Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00002435 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00002436 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00002437 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Fariborz Jahanian223ca5c2013-02-18 17:22:23 +00002438
2439 // Check for error condition which is already reported.
2440 if (!CurMethod)
2441 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002442
John McCalle66edc12009-11-24 19:00:30 +00002443 // There are two cases to handle here. 1) scoped lookup could have failed,
2444 // in which case we should look for an ivar. 2) scoped lookup could have
2445 // found a decl, but that decl is outside the current instance method (i.e.
2446 // a global variable). In these two cases, we do a lookup for an ivar with
2447 // this name, if the lookup sucedes, we replace it our current decl.
2448
2449 // If we're in a class method, we don't normally want to look for
2450 // ivars. But if we don't find anything else, and there's an
2451 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00002452 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00002453
2454 bool LookForIvars;
2455 if (Lookup.empty())
2456 LookForIvars = true;
2457 else if (IsClassMethod)
2458 LookForIvars = false;
2459 else
2460 LookForIvars = (Lookup.isSingleResult() &&
2461 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Craig Topperc3ec1492014-05-26 06:22:03 +00002462 ObjCInterfaceDecl *IFace = nullptr;
John McCalle66edc12009-11-24 19:00:30 +00002463 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00002464 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00002465 ObjCInterfaceDecl *ClassDeclared;
Craig Topperc3ec1492014-05-26 06:22:03 +00002466 ObjCIvarDecl *IV = nullptr;
Argyrios Kyrtzidis4e8b1362011-10-19 02:25:16 +00002467 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCalle66edc12009-11-24 19:00:30 +00002468 // Diagnose using an ivar in a class method.
2469 if (IsClassMethod)
2470 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2471 << IV->getDeclName());
2472
2473 // If we're referencing an invalid decl, just return this as a silent
2474 // error node. The error diagnostic was already emitted on the decl.
2475 if (IV->isInvalidDecl())
2476 return ExprError();
2477
2478 // Check if referencing a field with __attribute__((deprecated)).
2479 if (DiagnoseUseOfDecl(IV, Loc))
2480 return ExprError();
2481
2482 // Diagnose the use of an ivar outside of the declaring class.
2483 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00002484 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002485 !getLangOpts().DebuggerSupport)
John McCalle66edc12009-11-24 19:00:30 +00002486 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2487
2488 // FIXME: This should use a new expr for a direct reference, don't
2489 // turn this into Self->ivar, just return a BareIVarExpr or something.
2490 IdentifierInfo &II = Context.Idents.get("self");
2491 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002492 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00002493 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00002494 CXXScopeSpec SelfScopeSpec;
Abramo Bagnara7945c982012-01-27 09:46:47 +00002495 SourceLocation TemplateKWLoc;
2496 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00002497 SelfName, false, false);
2498 if (SelfExpr.isInvalid())
2499 return ExprError();
2500
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002501 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00002502 if (SelfExpr.isInvalid())
2503 return ExprError();
John McCall27584242010-12-06 20:48:59 +00002504
Nick Lewycky45b50522013-02-02 00:25:55 +00002505 MarkAnyDeclReferenced(Loc, IV, true);
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00002506
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00002507 ObjCMethodFamily MF = CurMethod->getMethodFamily();
Fariborz Jahaniana934a022013-02-14 19:07:19 +00002508 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2509 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00002510 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
Jordan Rose657b5f42012-09-28 22:21:35 +00002511
Nico Weber21ad7e52014-07-27 04:09:29 +00002512 ObjCIvarRefExpr *Result = new (Context)
Douglas Gregore83b9562015-07-07 03:57:53 +00002513 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2514 IV->getLocation(), SelfExpr.get(), true, true);
Jordan Rose657b5f42012-09-28 22:21:35 +00002515
2516 if (getLangOpts().ObjCAutoRefCount) {
2517 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002518 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Fariborz Jahanian6f829e32013-05-21 21:20:26 +00002519 recordUseOfEvaluatedWeak(Result);
Jordan Rose657b5f42012-09-28 22:21:35 +00002520 }
Fariborz Jahanian4a675082012-10-03 17:55:29 +00002521 if (CurContext->isClosure())
2522 Diag(Loc, diag::warn_implicitly_retains_self)
2523 << FixItHint::CreateInsertion(Loc, "self->");
Jordan Rose657b5f42012-09-28 22:21:35 +00002524 }
2525
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002526 return Result;
John McCalle66edc12009-11-24 19:00:30 +00002527 }
Chris Lattner87313662010-04-12 05:10:17 +00002528 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00002529 // We should warn if a local variable hides an ivar.
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00002530 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2531 ObjCInterfaceDecl *ClassDeclared;
2532 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2533 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor0b144e12011-12-15 00:29:59 +00002534 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00002535 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2536 }
John McCalle66edc12009-11-24 19:00:30 +00002537 }
Fariborz Jahanian028b9e12011-12-20 22:21:08 +00002538 } else if (Lookup.isSingleResult() &&
2539 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2540 // If accessing a stand-alone ivar in a class method, this is an error.
2541 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2542 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2543 << IV->getDeclName());
John McCalle66edc12009-11-24 19:00:30 +00002544 }
2545
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002546 if (Lookup.empty() && II && AllowBuiltinCreation) {
2547 // FIXME. Consolidate this with similar code in LookupName.
2548 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002549 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002550 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2551 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2552 S, Lookup.isForRedeclaration(),
2553 Lookup.getNameLoc());
2554 if (D) Lookup.addDecl(D);
2555 }
2556 }
2557 }
John McCalle66edc12009-11-24 19:00:30 +00002558 // Sentinel value saying that we didn't do anything special.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002559 return ExprResult((Expr *)nullptr);
Douglas Gregor3256d042009-06-30 15:47:41 +00002560}
John McCalld14a8642009-11-21 08:51:07 +00002561
John McCall16df1e52010-03-30 21:47:33 +00002562/// \brief Cast a base object to a member's actual type.
2563///
2564/// Logically this happens in three phases:
2565///
2566/// * First we cast from the base type to the naming class.
2567/// The naming class is the class into which we were looking
2568/// when we found the member; it's the qualifier type if a
2569/// qualifier was provided, and otherwise it's the base type.
2570///
2571/// * Next we cast from the naming class to the declaring class.
2572/// If the member we found was brought into a class's scope by
2573/// a using declaration, this is that class; otherwise it's
2574/// the class declaring the member.
2575///
2576/// * Finally we cast from the declaring class to the "true"
2577/// declaring class of the member. This conversion does not
2578/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00002579ExprResult
2580Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002581 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002582 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002583 NamedDecl *Member) {
2584 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2585 if (!RD)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002586 return From;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002587
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002588 QualType DestRecordType;
2589 QualType DestType;
2590 QualType FromRecordType;
2591 QualType FromType = From->getType();
2592 bool PointerConversions = false;
2593 if (isa<FieldDecl>(Member)) {
2594 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002595
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002596 if (FromType->getAs<PointerType>()) {
2597 DestType = Context.getPointerType(DestRecordType);
2598 FromRecordType = FromType->getPointeeType();
2599 PointerConversions = true;
2600 } else {
2601 DestType = DestRecordType;
2602 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002603 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002604 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2605 if (Method->isStatic())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002606 return From;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002607
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002608 DestType = Method->getThisType(Context);
2609 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002610
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002611 if (FromType->getAs<PointerType>()) {
2612 FromRecordType = FromType->getPointeeType();
2613 PointerConversions = true;
2614 } else {
2615 FromRecordType = FromType;
2616 DestType = DestRecordType;
2617 }
2618 } else {
2619 // No conversion necessary.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002620 return From;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002621 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002622
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002623 if (DestType->isDependentType() || FromType->isDependentType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002624 return From;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002625
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002626 // If the unqualified types are the same, no conversion is necessary.
2627 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002628 return From;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002629
John McCall16df1e52010-03-30 21:47:33 +00002630 SourceRange FromRange = From->getSourceRange();
2631 SourceLocation FromLoc = FromRange.getBegin();
2632
Eli Friedmanbe4b3632011-09-27 21:58:52 +00002633 ExprValueKind VK = From->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002634
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002635 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002636 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002637 // class name.
2638 //
2639 // If the member was a qualified name and the qualified referred to a
2640 // specific base subobject type, we'll cast to that intermediate type
2641 // first and then to the object in which the member is declared. That allows
2642 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2643 //
2644 // class Base { public: int x; };
2645 // class Derived1 : public Base { };
2646 // class Derived2 : public Base { };
2647 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2648 //
2649 // void VeryDerived::f() {
2650 // x = 17; // error: ambiguous base subobjects
2651 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2652 // }
David Majnemer13657812013-08-05 04:53:41 +00002653 if (Qualifier && Qualifier->getAsType()) {
John McCall16df1e52010-03-30 21:47:33 +00002654 QualType QType = QualType(Qualifier->getAsType(), 0);
John McCall16df1e52010-03-30 21:47:33 +00002655 assert(QType->isRecordType() && "lookup done with non-record type");
2656
2657 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2658
2659 // In C++98, the qualifier type doesn't actually have to be a base
2660 // type of the object type, in which case we just ignore it.
2661 // Otherwise build the appropriate casts.
Richard Smith0f59cb32015-12-18 21:45:41 +00002662 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002663 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002664 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002665 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002666 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002667
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002668 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002669 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002670 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002671 VK, &BasePath).get();
John McCall16df1e52010-03-30 21:47:33 +00002672
2673 FromType = QType;
2674 FromRecordType = QRecordType;
2675
2676 // If the qualifier type was the same as the destination type,
2677 // we're done.
2678 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002679 return From;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002680 }
2681 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002682
John McCall16df1e52010-03-30 21:47:33 +00002683 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002684
John McCall16df1e52010-03-30 21:47:33 +00002685 // If we actually found the member through a using declaration, cast
2686 // down to the using declaration's type.
2687 //
2688 // Pointer equality is fine here because only one declaration of a
2689 // class ever has member declarations.
2690 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2691 assert(isa<UsingShadowDecl>(FoundDecl));
2692 QualType URecordType = Context.getTypeDeclType(
2693 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2694
2695 // We only need to do this if the naming-class to declaring-class
2696 // conversion is non-trivial.
2697 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00002698 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002699 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002700 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002701 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002702 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002703
John McCall16df1e52010-03-30 21:47:33 +00002704 QualType UType = URecordType;
2705 if (PointerConversions)
2706 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002707 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002708 VK, &BasePath).get();
John McCall16df1e52010-03-30 21:47:33 +00002709 FromType = UType;
2710 FromRecordType = URecordType;
2711 }
2712
2713 // We don't do access control for the conversion from the
2714 // declaring class to the true declaring class.
2715 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002716 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002717
John McCallcf142162010-08-07 06:22:56 +00002718 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002719 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2720 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002721 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002722 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002723
John Wiegley01296292011-04-08 18:41:53 +00002724 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2725 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002726}
Douglas Gregor3256d042009-06-30 15:47:41 +00002727
John McCalle66edc12009-11-24 19:00:30 +00002728bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002729 const LookupResult &R,
2730 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002731 // Only when used directly as the postfix-expression of a call.
2732 if (!HasTrailingLParen)
2733 return false;
2734
2735 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002736 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002737 return false;
2738
2739 // Only in C++ or ObjC++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002740 if (!getLangOpts().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002741 return false;
2742
2743 // Turn off ADL when we find certain kinds of declarations during
2744 // normal lookup:
Craig Topperdfe29ae2015-12-21 06:35:56 +00002745 for (NamedDecl *D : R) {
John McCalld14a8642009-11-21 08:51:07 +00002746 // C++0x [basic.lookup.argdep]p3:
2747 // -- a declaration of a class member
2748 // Since using decls preserve this property, we check this on the
2749 // original decl.
John McCall57500772009-12-16 12:17:52 +00002750 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002751 return false;
2752
2753 // C++0x [basic.lookup.argdep]p3:
2754 // -- a block-scope function declaration that is not a
2755 // using-declaration
2756 // NOTE: we also trigger this for function templates (in fact, we
2757 // don't check the decl type at all, since all other decl types
2758 // turn off ADL anyway).
2759 if (isa<UsingShadowDecl>(D))
2760 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Richard Smith541b38b2013-09-20 01:15:31 +00002761 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
John McCalld14a8642009-11-21 08:51:07 +00002762 return false;
2763
2764 // C++0x [basic.lookup.argdep]p3:
2765 // -- a declaration that is neither a function or a function
2766 // template
2767 // And also for builtin functions.
2768 if (isa<FunctionDecl>(D)) {
2769 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2770
2771 // But also builtin functions.
2772 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2773 return false;
2774 } else if (!isa<FunctionTemplateDecl>(D))
2775 return false;
2776 }
2777
2778 return true;
2779}
2780
2781
John McCalld14a8642009-11-21 08:51:07 +00002782/// Diagnoses obvious problems with the use of the given declaration
2783/// as an expression. This is only actually called for lookups that
2784/// were not overloaded, and it doesn't promise that the declaration
2785/// will in fact be used.
2786static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002787 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002788 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2789 return true;
2790 }
2791
2792 if (isa<ObjCInterfaceDecl>(D)) {
2793 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2794 return true;
2795 }
2796
2797 if (isa<NamespaceDecl>(D)) {
2798 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2799 return true;
2800 }
2801
2802 return false;
2803}
2804
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00002805ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2806 LookupResult &R, bool NeedsADL,
2807 bool AcceptInvalidDecl) {
John McCall3a60c872009-12-08 22:45:53 +00002808 // If this is a single, fully-resolved result and we don't need ADL,
2809 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002810 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Daniel Jasper689ae012013-03-22 10:01:35 +00002811 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00002812 R.getRepresentativeDecl(), nullptr,
2813 AcceptInvalidDecl);
John McCalld14a8642009-11-21 08:51:07 +00002814
2815 // We only need to check the declaration if there's exactly one
2816 // result, because in the overloaded case the results can only be
2817 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002818 if (R.isSingleResult() &&
2819 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002820 return ExprError();
2821
John McCall58cc69d2010-01-27 01:50:18 +00002822 // Otherwise, just build an unresolved lookup expression. Suppress
2823 // any lookup-related diagnostics; we'll hash these out later, when
2824 // we've picked a target.
2825 R.suppressDiagnostics();
2826
John McCalld14a8642009-11-21 08:51:07 +00002827 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002828 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002829 SS.getWithLocInContext(Context),
2830 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002831 NeedsADL, R.isOverloadedResult(),
2832 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002833
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002834 return ULE;
John McCalld14a8642009-11-21 08:51:07 +00002835}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002836
John McCalld14a8642009-11-21 08:51:07 +00002837/// \brief Complete semantic analysis for a reference to the given declaration.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002838ExprResult Sema::BuildDeclarationNameExpr(
2839 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00002840 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2841 bool AcceptInvalidDecl) {
John McCalld14a8642009-11-21 08:51:07 +00002842 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002843 assert(!isa<FunctionTemplateDecl>(D) &&
2844 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002845
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002846 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002847 if (CheckDeclInExpr(*this, Loc, D))
2848 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002849
Douglas Gregore7488b92009-12-01 16:58:18 +00002850 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2851 // Specifically diagnose references to class templates that are missing
2852 // a template argument list.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002853 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2854 << Template << SS.getRange();
Douglas Gregore7488b92009-12-01 16:58:18 +00002855 Diag(Template->getLocation(), diag::note_template_decl_here);
2856 return ExprError();
2857 }
2858
2859 // Make sure that we're referring to a value.
2860 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2861 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002862 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002863 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002864 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002865 return ExprError();
2866 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002867
Douglas Gregor171c45a2009-02-18 21:56:37 +00002868 // Check whether this declaration can be used. Note that we suppress
2869 // this check when we're going to perform argument-dependent lookup
2870 // on this function name, because this might not be the function
2871 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002872 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002873 return ExprError();
2874
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002875 // Only create DeclRefExpr's for valid Decl's.
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00002876 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002877 return ExprError();
2878
John McCallf3a88602011-02-03 08:15:49 +00002879 // Handle members of anonymous structs and unions. If we got here,
2880 // and the reference is to a class member indirect field, then this
2881 // must be the subject of a pointer-to-member expression.
2882 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2883 if (!indirectField->isCXXClassMember())
2884 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2885 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002886
Eli Friedman9bb33f52012-02-03 02:04:35 +00002887 {
John McCallf4cd4f92011-02-09 01:13:10 +00002888 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002889 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002890
2891 switch (D->getKind()) {
2892 // Ignore all the non-ValueDecl kinds.
2893#define ABSTRACT_DECL(kind)
2894#define VALUE(type, base)
2895#define DECL(type, base) \
2896 case Decl::type:
2897#include "clang/AST/DeclNodes.inc"
2898 llvm_unreachable("invalid value decl kind");
John McCallf4cd4f92011-02-09 01:13:10 +00002899
2900 // These shouldn't make it here.
2901 case Decl::ObjCAtDefsField:
2902 case Decl::ObjCIvar:
2903 llvm_unreachable("forming non-member reference to ivar?");
John McCallf4cd4f92011-02-09 01:13:10 +00002904
2905 // Enum constants are always r-values and never references.
2906 // Unresolved using declarations are dependent.
2907 case Decl::EnumConstant:
2908 case Decl::UnresolvedUsingValue:
Alexey Bataevc5b1d322016-03-04 09:22:22 +00002909 case Decl::OMPDeclareReduction:
John McCallf4cd4f92011-02-09 01:13:10 +00002910 valueKind = VK_RValue;
2911 break;
2912
2913 // Fields and indirect fields that got here must be for
2914 // pointer-to-member expressions; we just call them l-values for
2915 // internal consistency, because this subexpression doesn't really
2916 // exist in the high-level semantics.
2917 case Decl::Field:
2918 case Decl::IndirectField:
David Blaikiebbafb8a2012-03-11 07:00:24 +00002919 assert(getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002920 "building reference to field in C?");
2921
2922 // These can't have reference type in well-formed programs, but
2923 // for internal consistency we do this anyway.
2924 type = type.getNonReferenceType();
2925 valueKind = VK_LValue;
2926 break;
2927
2928 // Non-type template parameters are either l-values or r-values
2929 // depending on the type.
2930 case Decl::NonTypeTemplateParm: {
2931 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2932 type = reftype->getPointeeType();
2933 valueKind = VK_LValue; // even if the parameter is an r-value reference
2934 break;
2935 }
2936
2937 // For non-references, we need to strip qualifiers just in case
2938 // the template parameter was declared as 'const int' or whatever.
2939 valueKind = VK_RValue;
2940 type = type.getUnqualifiedType();
2941 break;
2942 }
2943
2944 case Decl::Var:
Larisse Voufo39a1e502013-08-06 01:03:05 +00002945 case Decl::VarTemplateSpecialization:
2946 case Decl::VarTemplatePartialSpecialization:
Alexey Bataev4244be22016-02-11 05:35:55 +00002947 case Decl::OMPCapturedExpr:
John McCallf4cd4f92011-02-09 01:13:10 +00002948 // In C, "extern void blah;" is valid and is an r-value.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002949 if (!getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002950 !type.hasQualifiers() &&
2951 type->isVoidType()) {
2952 valueKind = VK_RValue;
2953 break;
2954 }
2955 // fallthrough
2956
2957 case Decl::ImplicitParam:
Douglas Gregor812d8f62012-02-18 05:51:20 +00002958 case Decl::ParmVar: {
John McCallf4cd4f92011-02-09 01:13:10 +00002959 // These are always l-values.
2960 valueKind = VK_LValue;
2961 type = type.getNonReferenceType();
Eli Friedman9bb33f52012-02-03 02:04:35 +00002962
Douglas Gregor812d8f62012-02-18 05:51:20 +00002963 // FIXME: Does the addition of const really only apply in
2964 // potentially-evaluated contexts? Since the variable isn't actually
2965 // captured in an unevaluated context, it seems that the answer is no.
David Blaikie131fcb42012-08-06 22:47:24 +00002966 if (!isUnevaluatedContext()) {
Douglas Gregor812d8f62012-02-18 05:51:20 +00002967 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2968 if (!CapturedType.isNull())
2969 type = CapturedType;
2970 }
2971
John McCallf4cd4f92011-02-09 01:13:10 +00002972 break;
Douglas Gregor812d8f62012-02-18 05:51:20 +00002973 }
2974
John McCallf4cd4f92011-02-09 01:13:10 +00002975 case Decl::Function: {
Eli Friedman34866c72012-08-31 00:14:07 +00002976 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2977 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2978 type = Context.BuiltinFnTy;
2979 valueKind = VK_RValue;
2980 break;
2981 }
2982 }
2983
John McCall2979fe02011-04-12 00:42:48 +00002984 const FunctionType *fty = type->castAs<FunctionType>();
2985
2986 // If we're referring to a function with an __unknown_anytype
2987 // result type, make the entire expression __unknown_anytype.
Alp Toker314cc812014-01-25 16:55:45 +00002988 if (fty->getReturnType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00002989 type = Context.UnknownAnyTy;
2990 valueKind = VK_RValue;
2991 break;
2992 }
2993
John McCallf4cd4f92011-02-09 01:13:10 +00002994 // Functions are l-values in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002995 if (getLangOpts().CPlusPlus) {
John McCallf4cd4f92011-02-09 01:13:10 +00002996 valueKind = VK_LValue;
2997 break;
2998 }
2999
3000 // C99 DR 316 says that, if a function type comes from a
3001 // function definition (without a prototype), that type is only
3002 // used for checking compatibility. Therefore, when referencing
3003 // the function, we pretend that we don't have the full function
3004 // type.
John McCall2979fe02011-04-12 00:42:48 +00003005 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3006 isa<FunctionProtoType>(fty))
Alp Toker314cc812014-01-25 16:55:45 +00003007 type = Context.getFunctionNoProtoType(fty->getReturnType(),
John McCall2979fe02011-04-12 00:42:48 +00003008 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00003009
3010 // Functions are r-values in C.
3011 valueKind = VK_RValue;
3012 break;
3013 }
3014
John McCall5e77d762013-04-16 07:28:30 +00003015 case Decl::MSProperty:
3016 valueKind = VK_LValue;
3017 break;
3018
John McCallf4cd4f92011-02-09 01:13:10 +00003019 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00003020 // If we're referring to a method with an __unknown_anytype
3021 // result type, make the entire expression __unknown_anytype.
3022 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00003023 if (const FunctionProtoType *proto
3024 = dyn_cast<FunctionProtoType>(VD->getType()))
Alp Toker314cc812014-01-25 16:55:45 +00003025 if (proto->getReturnType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003026 type = Context.UnknownAnyTy;
3027 valueKind = VK_RValue;
3028 break;
3029 }
3030
John McCallf4cd4f92011-02-09 01:13:10 +00003031 // C++ methods are l-values if static, r-values if non-static.
3032 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3033 valueKind = VK_LValue;
3034 break;
3035 }
3036 // fallthrough
3037
3038 case Decl::CXXConversion:
3039 case Decl::CXXDestructor:
3040 case Decl::CXXConstructor:
3041 valueKind = VK_RValue;
3042 break;
3043 }
3044
Larisse Voufo39a1e502013-08-06 01:03:05 +00003045 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3046 TemplateArgs);
John McCallf4cd4f92011-02-09 01:13:10 +00003047 }
Chris Lattner17ed4872006-11-20 04:58:19 +00003048}
Chris Lattnere168f762006-11-10 05:29:30 +00003049
Alexey Bataevec474782014-10-09 08:45:04 +00003050static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3051 SmallString<32> &Target) {
3052 Target.resize(CharByteWidth * (Source.size() + 1));
3053 char *ResultPtr = &Target[0];
3054 const UTF8 *ErrorPtr;
3055 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3056 (void)success;
3057 assert(success);
3058 Target.resize(ResultPtr - &Target[0]);
3059}
3060
Wei Panc354d212013-09-16 13:57:27 +00003061ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3062 PredefinedExpr::IdentType IT) {
3063 // Pick the current block, lambda, captured statement or function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003064 Decl *currentDecl = nullptr;
Benjamin Kramer90f54222013-08-21 11:45:27 +00003065 if (const BlockScopeInfo *BSI = getCurBlock())
3066 currentDecl = BSI->TheDecl;
3067 else if (const LambdaScopeInfo *LSI = getCurLambda())
3068 currentDecl = LSI->CallOperator;
Wei Pan8d6b19a2013-08-26 14:27:34 +00003069 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3070 currentDecl = CSI->TheCapturedDecl;
Benjamin Kramer90f54222013-08-21 11:45:27 +00003071 else
3072 currentDecl = getCurFunctionOrMethodDecl();
Benjamin Kramer6928cf72012-12-06 15:42:21 +00003073
Anders Carlsson2fb08242009-09-08 18:24:21 +00003074 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00003075 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00003076 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00003077 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003078
Anders Carlsson0b209a82009-09-11 01:22:35 +00003079 QualType ResTy;
Alexey Bataevec474782014-10-09 08:45:04 +00003080 StringLiteral *SL = nullptr;
Wei Panc354d212013-09-16 13:57:27 +00003081 if (cast<DeclContext>(currentDecl)->isDependentContext())
Anders Carlsson0b209a82009-09-11 01:22:35 +00003082 ResTy = Context.DependentTy;
Wei Panc354d212013-09-16 13:57:27 +00003083 else {
3084 // Pre-defined identifiers are of type char[x], where x is the length of
3085 // the string.
Alexey Bataevec474782014-10-09 08:45:04 +00003086 auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3087 unsigned Length = Str.length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003088
Anders Carlsson0b209a82009-09-11 01:22:35 +00003089 llvm::APInt LengthI(32, Length + 1);
Alexey Bataevec474782014-10-09 08:45:04 +00003090 if (IT == PredefinedExpr::LFunction) {
Hans Wennborg0d81e012013-05-10 10:08:40 +00003091 ResTy = Context.WideCharTy.withConst();
Alexey Bataevec474782014-10-09 08:45:04 +00003092 SmallString<32> RawChars;
3093 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3094 Str, RawChars);
3095 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3096 /*IndexTypeQuals*/ 0);
3097 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3098 /*Pascal*/ false, ResTy, Loc);
3099 } else {
Nico Weber3a691a32012-06-23 02:07:59 +00003100 ResTy = Context.CharTy.withConst();
Alexey Bataevec474782014-10-09 08:45:04 +00003101 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3102 /*IndexTypeQuals*/ 0);
3103 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3104 /*Pascal*/ false, ResTy, Loc);
3105 }
Anders Carlsson0b209a82009-09-11 01:22:35 +00003106 }
Wei Panc354d212013-09-16 13:57:27 +00003107
Alexey Bataevec474782014-10-09 08:45:04 +00003108 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
Chris Lattnere168f762006-11-10 05:29:30 +00003109}
3110
Wei Panc354d212013-09-16 13:57:27 +00003111ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3112 PredefinedExpr::IdentType IT;
3113
3114 switch (Kind) {
3115 default: llvm_unreachable("Unknown simple primary expr!");
3116 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3117 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
David Majnemerbed356a2013-11-06 23:31:56 +00003118 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
Reid Kleckner52eddda2014-04-08 18:13:24 +00003119 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
Wei Panc354d212013-09-16 13:57:27 +00003120 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3121 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3122 }
3123
3124 return BuildPredefinedExpr(Loc, IT);
3125}
3126
Richard Smithbcc22fc2012-03-09 08:00:36 +00003127ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003128 SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00003129 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003130 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00003131 if (Invalid)
3132 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003133
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00003134 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00003135 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00003136 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00003137 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00003138
Chris Lattnerc3847ba2009-12-30 21:19:39 +00003139 QualType Ty;
Seth Cantrell02f86052012-01-18 12:27:06 +00003140 if (Literal.isWide())
Hans Wennborg0d81e012013-05-10 10:08:40 +00003141 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00003142 else if (Literal.isUTF16())
Seth Cantrell02f86052012-01-18 12:27:06 +00003143 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregorfb65e592011-07-27 05:40:30 +00003144 else if (Literal.isUTF32())
Seth Cantrell02f86052012-01-18 12:27:06 +00003145 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003146 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell02f86052012-01-18 12:27:06 +00003147 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00003148 else
3149 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00003150
Douglas Gregorfb65e592011-07-27 05:40:30 +00003151 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3152 if (Literal.isWide())
3153 Kind = CharacterLiteral::Wide;
3154 else if (Literal.isUTF16())
3155 Kind = CharacterLiteral::UTF16;
3156 else if (Literal.isUTF32())
3157 Kind = CharacterLiteral::UTF32;
Aaron Ballman9a17c852016-01-07 20:59:26 +00003158 else if (Literal.isUTF8())
3159 Kind = CharacterLiteral::UTF8;
Douglas Gregorfb65e592011-07-27 05:40:30 +00003160
Richard Smith75b67d62012-03-08 01:34:56 +00003161 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3162 Tok.getLocation());
3163
3164 if (Literal.getUDSuffix().empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003165 return Lit;
Richard Smith75b67d62012-03-08 01:34:56 +00003166
3167 // We're building a user-defined literal.
3168 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3169 SourceLocation UDSuffixLoc =
3170 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3171
Richard Smithbcc22fc2012-03-09 08:00:36 +00003172 // Make sure we're allowed user-defined literals here.
3173 if (!UDLScope)
3174 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3175
Richard Smith75b67d62012-03-08 01:34:56 +00003176 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3177 // operator "" X (ch)
Richard Smithbcc22fc2012-03-09 08:00:36 +00003178 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003179 Lit, Tok.getLocation());
Steve Naroffae4143e2007-04-26 20:39:23 +00003180}
3181
Ted Kremeneke65b0862012-03-06 20:05:56 +00003182ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3183 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003184 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3185 Context.IntTy, Loc);
Ted Kremeneke65b0862012-03-06 20:05:56 +00003186}
3187
Richard Smith39570d002012-03-08 08:45:32 +00003188static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3189 QualType Ty, SourceLocation Loc) {
3190 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3191
3192 using llvm::APFloat;
3193 APFloat Val(Format);
3194
3195 APFloat::opStatus result = Literal.GetFloatValue(Val);
3196
3197 // Overflow is always an error, but underflow is only an error if
3198 // we underflowed to zero (APFloat reports denormals as underflow).
3199 if ((result & APFloat::opOverflow) ||
3200 ((result & APFloat::opUnderflow) && Val.isZero())) {
3201 unsigned diagnostic;
3202 SmallString<20> buffer;
3203 if (result & APFloat::opOverflow) {
3204 diagnostic = diag::warn_float_overflow;
3205 APFloat::getLargest(Format).toString(buffer);
3206 } else {
3207 diagnostic = diag::warn_float_underflow;
3208 APFloat::getSmallest(Format).toString(buffer);
3209 }
3210
3211 S.Diag(Loc, diagnostic)
3212 << Ty
3213 << StringRef(buffer.data(), buffer.size());
3214 }
3215
3216 bool isExact = (result == APFloat::opOK);
3217 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3218}
3219
Tyler Nowickic724a83e2014-10-12 20:46:07 +00003220bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3221 assert(E && "Invalid expression");
3222
3223 if (E->isValueDependent())
3224 return false;
3225
3226 QualType QT = E->getType();
3227 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3228 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3229 return true;
3230 }
3231
3232 llvm::APSInt ValueAPS;
3233 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3234
3235 if (R.isInvalid())
3236 return true;
3237
3238 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3239 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3240 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3241 << ValueAPS.toString(10) << ValueIsPositive;
3242 return true;
3243 }
3244
3245 return false;
3246}
3247
Richard Smithbcc22fc2012-03-09 08:00:36 +00003248ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00003249 // Fast path for a single digit (which is quite common). A single digit
Richard Smithbcc22fc2012-03-09 08:00:36 +00003250 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Steve Narofff2fb89e2007-03-13 20:29:44 +00003251 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00003252 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremeneke65b0862012-03-06 20:05:56 +00003253 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Steve Narofff2fb89e2007-03-13 20:29:44 +00003254 }
Ted Kremeneke9814182009-01-13 23:19:12 +00003255
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00003256 SmallString<128> SpellingBuffer;
3257 // NumericLiteralParser wants to overread by one character. Add padding to
3258 // the buffer in case the token is copied to the buffer. If getSpelling()
3259 // returns a StringRef to the memory buffer, it should have a null char at
3260 // the EOF, so it is also safe.
3261 SpellingBuffer.resize(Tok.getLength() + 1);
Sebastian Redlffbcf962009-01-18 18:53:16 +00003262
Chris Lattner67ca9252007-05-21 01:08:44 +00003263 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00003264 bool Invalid = false;
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00003265 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00003266 if (Invalid)
3267 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003268
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00003269 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00003270 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00003271 return ExprError();
3272
Richard Smith39570d002012-03-08 08:45:32 +00003273 if (Literal.hasUDSuffix()) {
3274 // We're building a user-defined literal.
3275 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3276 SourceLocation UDSuffixLoc =
3277 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3278
Richard Smithbcc22fc2012-03-09 08:00:36 +00003279 // Make sure we're allowed user-defined literals here.
3280 if (!UDLScope)
3281 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smith39570d002012-03-08 08:45:32 +00003282
Richard Smithbcc22fc2012-03-09 08:00:36 +00003283 QualType CookedTy;
Richard Smith39570d002012-03-08 08:45:32 +00003284 if (Literal.isFloatingLiteral()) {
3285 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3286 // long double, the literal is treated as a call of the form
3287 // operator "" X (f L)
Richard Smithbcc22fc2012-03-09 08:00:36 +00003288 CookedTy = Context.LongDoubleTy;
Richard Smith39570d002012-03-08 08:45:32 +00003289 } else {
3290 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3291 // unsigned long long, the literal is treated as a call of the form
3292 // operator "" X (n ULL)
Richard Smithbcc22fc2012-03-09 08:00:36 +00003293 CookedTy = Context.UnsignedLongLongTy;
Richard Smith39570d002012-03-08 08:45:32 +00003294 }
3295
Richard Smithbcc22fc2012-03-09 08:00:36 +00003296 DeclarationName OpName =
3297 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3298 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3299 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3300
Richard Smithb8b41d32013-10-07 19:57:58 +00003301 SourceLocation TokLoc = Tok.getLocation();
3302
Richard Smithbcc22fc2012-03-09 08:00:36 +00003303 // Perform literal operator lookup to determine if we're building a raw
3304 // literal or a cooked one.
3305 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003306 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
Richard Smithb8b41d32013-10-07 19:57:58 +00003307 /*AllowRaw*/true, /*AllowTemplate*/true,
3308 /*AllowStringTemplate*/false)) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003309 case LOLR_Error:
3310 return ExprError();
3311
3312 case LOLR_Cooked: {
3313 Expr *Lit;
3314 if (Literal.isFloatingLiteral()) {
3315 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3316 } else {
3317 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3318 if (Literal.GetIntegerValue(ResultVal))
Aaron Ballman31f42312014-07-24 14:51:23 +00003319 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3320 << /* Unsigned */ 1;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003321 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3322 Tok.getLocation());
3323 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003324 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
Richard Smithbcc22fc2012-03-09 08:00:36 +00003325 }
3326
3327 case LOLR_Raw: {
3328 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3329 // literal is treated as a call of the form
3330 // operator "" X ("n")
Richard Smithbcc22fc2012-03-09 08:00:36 +00003331 unsigned Length = Literal.getUDSuffixOffset();
3332 QualType StrTy = Context.getConstantArrayType(
Richard Smithbe8229c2013-01-23 23:38:20 +00003333 Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
Richard Smithbcc22fc2012-03-09 08:00:36 +00003334 ArrayType::Normal, 0);
3335 Expr *Lit = StringLiteral::Create(
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00003336 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
Richard Smithbcc22fc2012-03-09 08:00:36 +00003337 /*Pascal*/false, StrTy, &TokLoc, 1);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003338 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
Richard Smithbcc22fc2012-03-09 08:00:36 +00003339 }
3340
Richard Smithb8b41d32013-10-07 19:57:58 +00003341 case LOLR_Template: {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003342 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3343 // template), L is treated as a call fo the form
3344 // operator "" X <'c1', 'c2', ... 'ck'>()
3345 // where n is the source character sequence c1 c2 ... ck.
3346 TemplateArgumentListInfo ExplicitArgs;
3347 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3348 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3349 llvm::APSInt Value(CharBits, CharIsUnsigned);
3350 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00003351 Value = TokSpelling[I];
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003352 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smithbcc22fc2012-03-09 08:00:36 +00003353 TemplateArgumentLocInfo ArgInfo;
3354 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3355 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003356 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003357 &ExplicitArgs);
Richard Smithbcc22fc2012-03-09 08:00:36 +00003358 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003359 case LOLR_StringTemplate:
3360 llvm_unreachable("unexpected literal operator lookup result");
3361 }
Richard Smith39570d002012-03-08 08:45:32 +00003362 }
3363
Chris Lattner1c20a172007-08-26 03:42:43 +00003364 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00003365
Chris Lattner1c20a172007-08-26 03:42:43 +00003366 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00003367 QualType Ty;
Anastasia Stulova5c1a2c52016-02-17 11:34:37 +00003368 if (Literal.isHalf){
3369 if (getOpenCLOptions().cl_khr_fp16)
3370 Ty = Context.HalfTy;
3371 else {
3372 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3373 return ExprError();
3374 }
3375 } else if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00003376 Ty = Context.FloatTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003377 else if (Literal.isLong)
Nemanja Ivanovicd7d45bf2016-04-15 18:04:13 +00003378 Ty = Context.LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003379 else if (Literal.isFloat128)
3380 Ty = Context.Float128Ty;
3381 else
3382 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00003383
Richard Smith39570d002012-03-08 08:45:32 +00003384 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00003385
Peter Collingbournec77f85b2011-03-11 19:24:59 +00003386 if (Ty == Context.DoubleTy) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003387 if (getLangOpts().SinglePrecisionConstants) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003388 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
Fraser Cormackcc6e8942015-01-30 10:51:46 +00003389 } else if (getLangOpts().OpenCL &&
3390 !((getLangOpts().OpenCLVersion >= 120) ||
3391 getOpenCLOptions().cl_khr_fp64)) {
Peter Collingbournec77f85b2011-03-11 19:24:59 +00003392 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003393 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00003394 }
3395 }
Chris Lattner1c20a172007-08-26 03:42:43 +00003396 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00003397 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00003398 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003399 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00003400
Dmitri Gribenko1cd23052012-09-24 18:19:21 +00003401 // 'long long' is a C99 or C++11 feature.
3402 if (!getLangOpts().C99 && Literal.isLongLong) {
3403 if (getLangOpts().CPlusPlus)
3404 Diag(Tok.getLocation(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003405 getLangOpts().CPlusPlus11 ?
Dmitri Gribenko1cd23052012-09-24 18:19:21 +00003406 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3407 else
3408 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3409 }
Neil Boothac582c52007-08-29 22:00:19 +00003410
Chris Lattner67ca9252007-05-21 01:08:44 +00003411 // Get the value in the widest-possible width.
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00003412 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00003413 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00003414
Chris Lattner67ca9252007-05-21 01:08:44 +00003415 if (Literal.GetIntegerValue(ResultVal)) {
Eli Friedman088d39a2013-07-23 00:25:18 +00003416 // If this value didn't fit into uintmax_t, error and force to ull.
Aaron Ballman31f42312014-07-24 14:51:23 +00003417 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3418 << /* Unsigned */ 1;
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003419 Ty = Context.UnsignedLongLongTy;
3420 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00003421 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00003422 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00003423 // If this value fits into a ULL, try to figure out what else it fits into
3424 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00003425
Chris Lattner67ca9252007-05-21 01:08:44 +00003426 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3427 // be an unsigned int.
3428 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3429
3430 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00003431 unsigned Width = 0;
David Majnemer65a407c2014-06-21 18:46:07 +00003432
3433 // Microsoft specific integer suffixes are explicitly sized.
3434 if (Literal.MicrosoftInteger) {
David Majnemer5055dfc2015-07-26 09:02:26 +00003435 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
David Majnemerbe09e8e2015-03-06 18:04:22 +00003436 Width = 8;
3437 Ty = Context.CharTy;
David Majnemer65a407c2014-06-21 18:46:07 +00003438 } else {
3439 Width = Literal.MicrosoftInteger;
3440 Ty = Context.getIntTypeForBitwidth(Width,
3441 /*Signed=*/!Literal.isUnsigned);
3442 }
3443 }
3444
3445 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
Chris Lattner7b939cf2007-08-23 21:58:08 +00003446 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00003447 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003448
Chris Lattner67ca9252007-05-21 01:08:44 +00003449 // Does it fit in a unsigned int?
3450 if (ResultVal.isIntN(IntSize)) {
3451 // Does it fit in a signed int?
3452 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003453 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00003454 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003455 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00003456 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00003457 }
Chris Lattner67ca9252007-05-21 01:08:44 +00003458 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003459
Chris Lattner67ca9252007-05-21 01:08:44 +00003460 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003461 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003462 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003463
Chris Lattner67ca9252007-05-21 01:08:44 +00003464 // Does it fit in a unsigned long?
3465 if (ResultVal.isIntN(LongSize)) {
3466 // Does it fit in a signed long?
3467 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003468 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00003469 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003470 Ty = Context.UnsignedLongTy;
Hubert Tong13234ae2015-06-08 21:59:59 +00003471 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3472 // is compatible.
3473 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3474 const unsigned LongLongSize =
3475 Context.getTargetInfo().getLongLongWidth();
3476 Diag(Tok.getLocation(),
3477 getLangOpts().CPlusPlus
3478 ? Literal.isLong
3479 ? diag::warn_old_implicitly_unsigned_long_cxx
3480 : /*C++98 UB*/ diag::
3481 ext_old_implicitly_unsigned_long_cxx
3482 : diag::warn_old_implicitly_unsigned_long)
3483 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3484 : /*will be ill-formed*/ 1);
3485 Ty = Context.UnsignedLongTy;
3486 }
Chris Lattner55258cf2008-05-09 05:59:00 +00003487 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00003488 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003489 }
3490
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00003491 // Check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003492 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003493 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003494
Chris Lattner67ca9252007-05-21 01:08:44 +00003495 // Does it fit in a unsigned long long?
3496 if (ResultVal.isIntN(LongLongSize)) {
3497 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00003498 // To be compatible with MSVC, hex integer literals ending with the
3499 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00003500 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003501 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003502 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00003503 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003504 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00003505 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00003506 }
3507 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003508
Chris Lattner67ca9252007-05-21 01:08:44 +00003509 // If we still couldn't decide a type, we probably have something that
3510 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003511 if (Ty.isNull()) {
Aaron Ballman31f42312014-07-24 14:51:23 +00003512 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003513 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00003514 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00003515 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003516
Chris Lattner55258cf2008-05-09 05:59:00 +00003517 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00003518 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00003519 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003520 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00003521 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003522
Chris Lattner1c20a172007-08-26 03:42:43 +00003523 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3524 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00003525 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00003526 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00003527
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003528 return Res;
Chris Lattnere168f762006-11-10 05:29:30 +00003529}
3530
Richard Trieuba63ce62011-09-09 01:45:06 +00003531ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003532 assert(E && "ActOnParenExpr() missing expr");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003533 return new (Context) ParenExpr(L, R, E);
Chris Lattnere168f762006-11-10 05:29:30 +00003534}
3535
Chandler Carruth62da79c2011-05-26 08:53:12 +00003536static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3537 SourceLocation Loc,
3538 SourceRange ArgRange) {
3539 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3540 // scalar or vector data type argument..."
3541 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3542 // type (C99 6.2.5p18) or void.
3543 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3544 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3545 << T << ArgRange;
3546 return true;
3547 }
3548
3549 assert((T->isVoidType() || !T->isIncompleteType()) &&
3550 "Scalar types should always be complete");
3551 return false;
3552}
3553
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003554static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3555 SourceLocation Loc,
3556 SourceRange ArgRange,
3557 UnaryExprOrTypeTrait TraitKind) {
Eli Friedman4e28b262013-08-13 22:26:42 +00003558 // Invalid types must be hard errors for SFINAE in C++.
3559 if (S.LangOpts.CPlusPlus)
3560 return true;
3561
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003562 // C99 6.5.3.4p1:
Richard Smith9cf21ae2013-03-18 23:37:25 +00003563 if (T->isFunctionType() &&
3564 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3565 // sizeof(function)/alignof(function) is allowed as an extension.
3566 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3567 << TraitKind << ArgRange;
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003568 return false;
3569 }
3570
Joey Gouly4ba0f1e2013-12-31 15:47:49 +00003571 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3572 // this is an error (OpenCL v1.1 s6.3.k)
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003573 if (T->isVoidType()) {
Joey Gouly4ba0f1e2013-12-31 15:47:49 +00003574 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3575 : diag::ext_sizeof_alignof_void_type;
3576 S.Diag(Loc, DiagID) << TraitKind << ArgRange;
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003577 return false;
3578 }
3579
3580 return true;
3581}
3582
3583static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3584 SourceLocation Loc,
3585 SourceRange ArgRange,
3586 UnaryExprOrTypeTrait TraitKind) {
John McCallf2538342012-07-31 05:14:30 +00003587 // Reject sizeof(interface) and sizeof(interface<proto>) if the
3588 // runtime doesn't allow it.
3589 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003590 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3591 << T << (TraitKind == UETT_SizeOf)
3592 << ArgRange;
3593 return true;
3594 }
3595
3596 return false;
3597}
3598
Benjamin Kramer054faa52013-03-29 21:43:21 +00003599/// \brief Check whether E is a pointer from a decayed array type (the decayed
3600/// pointer type is equal to T) and emit a warning if it is.
3601static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3602 Expr *E) {
3603 // Don't warn if the operation changed the type.
3604 if (T != E->getType())
3605 return;
3606
3607 // Now look for array decays.
3608 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3609 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3610 return;
3611
3612 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3613 << ICE->getType()
3614 << ICE->getSubExpr()->getType();
3615}
3616
Alp Toker95e7ff22014-01-01 05:57:51 +00003617/// \brief Check the constraints on expression operands to unary type expression
Chandler Carruth14502c22011-05-26 08:53:10 +00003618/// and type traits.
3619///
Chandler Carruth7c430c02011-05-27 01:33:31 +00003620/// Completes any types necessary and validates the constraints on the operand
3621/// expression. The logic mostly mirrors the type-based overload, but may modify
3622/// the expression as it completes the type for that expression through template
3623/// instantiation, etc.
Richard Trieuba63ce62011-09-09 01:45:06 +00003624bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth14502c22011-05-26 08:53:10 +00003625 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003626 QualType ExprTy = E->getType();
John McCall768439e2013-05-06 07:40:34 +00003627 assert(!ExprTy->isReferenceType());
Chandler Carruth7c430c02011-05-27 01:33:31 +00003628
3629 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00003630 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3631 E->getSourceRange());
Chandler Carruth7c430c02011-05-27 01:33:31 +00003632
3633 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00003634 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3635 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00003636 return false;
3637
Richard Smithf6d70302014-06-10 23:34:28 +00003638 // 'alignof' applied to an expression only requires the base element type of
3639 // the expression to be complete. 'sizeof' requires the expression's type to
3640 // be complete (and will attempt to complete it if it's an array of unknown
3641 // bound).
3642 if (ExprKind == UETT_AlignOf) {
3643 if (RequireCompleteType(E->getExprLoc(),
3644 Context.getBaseElementType(E->getType()),
3645 diag::err_sizeof_alignof_incomplete_type, ExprKind,
3646 E->getSourceRange()))
3647 return true;
3648 } else {
3649 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3650 ExprKind, E->getSourceRange()))
3651 return true;
3652 }
Chandler Carruth7c430c02011-05-27 01:33:31 +00003653
John McCall768439e2013-05-06 07:40:34 +00003654 // Completing the expression's type may have changed it.
Richard Trieuba63ce62011-09-09 01:45:06 +00003655 ExprTy = E->getType();
John McCall768439e2013-05-06 07:40:34 +00003656 assert(!ExprTy->isReferenceType());
Chandler Carruth7c430c02011-05-27 01:33:31 +00003657
Eli Friedman4e28b262013-08-13 22:26:42 +00003658 if (ExprTy->isFunctionType()) {
3659 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3660 << ExprKind << E->getSourceRange();
3661 return true;
3662 }
3663
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003664 // The operand for sizeof and alignof is in an unevaluated expression context,
3665 // so side effects could result in unintended consequences.
3666 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3667 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3668 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3669
Richard Trieuba63ce62011-09-09 01:45:06 +00003670 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3671 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00003672 return true;
3673
Nico Weber0870deb2011-06-15 02:47:03 +00003674 if (ExprKind == UETT_SizeOf) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003675 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Weber0870deb2011-06-15 02:47:03 +00003676 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3677 QualType OType = PVD->getOriginalType();
3678 QualType Type = PVD->getType();
3679 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003680 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Weber0870deb2011-06-15 02:47:03 +00003681 << Type << OType;
3682 Diag(PVD->getLocation(), diag::note_declared_at);
3683 }
3684 }
3685 }
Benjamin Kramer054faa52013-03-29 21:43:21 +00003686
3687 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3688 // decays into a pointer and returns an unintended result. This is most
3689 // likely a typo for "sizeof(array) op x".
3690 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3691 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3692 BO->getLHS());
3693 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3694 BO->getRHS());
3695 }
Nico Weber0870deb2011-06-15 02:47:03 +00003696 }
3697
Chandler Carruth7c430c02011-05-27 01:33:31 +00003698 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00003699}
3700
3701/// \brief Check the constraints on operands to unary expression and type
3702/// traits.
3703///
3704/// This will complete any types necessary, and validate the various constraints
3705/// on those operands.
3706///
Steve Naroff71b59a92007-06-04 22:22:31 +00003707/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00003708/// C99 6.3.2.1p[2-4] all state:
3709/// Except when it is the operand of the sizeof operator ...
3710///
3711/// C++ [expr.sizeof]p4
3712/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3713/// standard conversions are not applied to the operand of sizeof.
3714///
3715/// This policy is followed for all of the unary trait expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00003716bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00003717 SourceLocation OpLoc,
3718 SourceRange ExprRange,
3719 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003720 if (ExprType->isDependentType())
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003721 return false;
3722
Richard Smithc3fbf682014-06-10 21:11:26 +00003723 // C++ [expr.sizeof]p2:
3724 // When applied to a reference or a reference type, the result
3725 // is the size of the referenced type.
3726 // C++11 [expr.alignof]p3:
3727 // When alignof is applied to a reference type, the result
3728 // shall be the alignment of the referenced type.
Richard Trieuba63ce62011-09-09 01:45:06 +00003729 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3730 ExprType = Ref->getPointeeType();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003731
Richard Smithc3fbf682014-06-10 21:11:26 +00003732 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3733 // When alignof or _Alignof is applied to an array type, the result
3734 // is the alignment of the element type.
Alexey Bataev00396512015-07-02 03:40:19 +00003735 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
Richard Smithc3fbf682014-06-10 21:11:26 +00003736 ExprType = Context.getBaseElementType(ExprType);
3737
Chandler Carruth62da79c2011-05-26 08:53:12 +00003738 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00003739 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003740
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003741 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00003742 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003743 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00003744 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003745
Richard Trieuba63ce62011-09-09 01:45:06 +00003746 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003747 diag::err_sizeof_alignof_incomplete_type,
3748 ExprKind, ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00003749 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003750
Eli Friedman4e28b262013-08-13 22:26:42 +00003751 if (ExprType->isFunctionType()) {
3752 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3753 << ExprKind << ExprRange;
3754 return true;
3755 }
3756
Richard Trieuba63ce62011-09-09 01:45:06 +00003757 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003758 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00003759 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003760
Chris Lattner62975a72009-04-24 00:30:45 +00003761 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00003762}
3763
Chandler Carruth14502c22011-05-26 08:53:10 +00003764static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00003765 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003766
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003767 // Cannot know anything else if the expression is dependent.
3768 if (E->isTypeDependent())
3769 return false;
3770
John McCall768439e2013-05-06 07:40:34 +00003771 if (E->getObjectKind() == OK_BitField) {
Richard Smithe301ba22015-11-11 02:02:15 +00003772 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
Chandler Carruth14502c22011-05-26 08:53:10 +00003773 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003774 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00003775 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00003776
Craig Topperc3ec1492014-05-26 06:22:03 +00003777 ValueDecl *D = nullptr;
John McCall768439e2013-05-06 07:40:34 +00003778 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3779 D = DRE->getDecl();
3780 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3781 D = ME->getMemberDecl();
3782 }
3783
3784 // If it's a field, require the containing struct to have a
3785 // complete definition so that we can compute the layout.
3786 //
Richard Smithc3fbf682014-06-10 21:11:26 +00003787 // This can happen in C++11 onwards, either by naming the member
3788 // in a way that is not transformed into a member access expression
3789 // (in an unevaluated operand, for instance), or by naming the member
3790 // in a trailing-return-type.
John McCall768439e2013-05-06 07:40:34 +00003791 //
3792 // For the record, since __alignof__ on expressions is a GCC
3793 // extension, GCC seems to permit this but always gives the
3794 // nonsensical answer 0.
3795 //
3796 // We don't really need the layout here --- we could instead just
3797 // directly check for all the appropriate alignment-lowing
3798 // attributes --- but that would require duplicating a lot of
3799 // logic that just isn't worth duplicating for such a marginal
3800 // use-case.
3801 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3802 // Fast path this check, since we at least know the record has a
3803 // definition if we can find a member of it.
3804 if (!FD->getParent()->isCompleteDefinition()) {
3805 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3806 << E->getSourceRange();
3807 return true;
3808 }
3809
3810 // Otherwise, if it's a field, and the field doesn't have
3811 // reference type, then it must have a complete type (or be a
3812 // flexible array member, which we explicitly want to
3813 // white-list anyway), which makes the following checks trivial.
3814 if (!FD->getType()->isReferenceType())
Douglas Gregor71235ec2009-05-02 02:18:30 +00003815 return false;
John McCall768439e2013-05-06 07:40:34 +00003816 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00003817
Chandler Carruth14502c22011-05-26 08:53:10 +00003818 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003819}
3820
Chandler Carruth14502c22011-05-26 08:53:10 +00003821bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00003822 E = E->IgnoreParens();
3823
3824 // Cannot know anything else if the expression is dependent.
3825 if (E->isTypeDependent())
3826 return false;
3827
Chandler Carruth14502c22011-05-26 08:53:10 +00003828 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00003829}
3830
Alexey Bataev93a546a2016-01-21 12:54:48 +00003831static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3832 CapturingScopeInfo *CSI) {
3833 assert(T->isVariablyModifiedType());
3834 assert(CSI != nullptr);
3835
3836 // We're going to walk down into the type and look for VLA expressions.
3837 do {
3838 const Type *Ty = T.getTypePtr();
3839 switch (Ty->getTypeClass()) {
3840#define TYPE(Class, Base)
3841#define ABSTRACT_TYPE(Class, Base)
3842#define NON_CANONICAL_TYPE(Class, Base)
3843#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3844#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3845#include "clang/AST/TypeNodes.def"
3846 T = QualType();
3847 break;
3848 // These types are never variably-modified.
3849 case Type::Builtin:
3850 case Type::Complex:
3851 case Type::Vector:
3852 case Type::ExtVector:
3853 case Type::Record:
3854 case Type::Enum:
3855 case Type::Elaborated:
3856 case Type::TemplateSpecialization:
3857 case Type::ObjCObject:
3858 case Type::ObjCInterface:
3859 case Type::ObjCObjectPointer:
3860 case Type::Pipe:
3861 llvm_unreachable("type class is never variably-modified!");
3862 case Type::Adjusted:
3863 T = cast<AdjustedType>(Ty)->getOriginalType();
3864 break;
3865 case Type::Decayed:
3866 T = cast<DecayedType>(Ty)->getPointeeType();
3867 break;
3868 case Type::Pointer:
3869 T = cast<PointerType>(Ty)->getPointeeType();
3870 break;
3871 case Type::BlockPointer:
3872 T = cast<BlockPointerType>(Ty)->getPointeeType();
3873 break;
3874 case Type::LValueReference:
3875 case Type::RValueReference:
3876 T = cast<ReferenceType>(Ty)->getPointeeType();
3877 break;
3878 case Type::MemberPointer:
3879 T = cast<MemberPointerType>(Ty)->getPointeeType();
3880 break;
3881 case Type::ConstantArray:
3882 case Type::IncompleteArray:
3883 // Losing element qualification here is fine.
3884 T = cast<ArrayType>(Ty)->getElementType();
3885 break;
3886 case Type::VariableArray: {
3887 // Losing element qualification here is fine.
3888 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3889
3890 // Unknown size indication requires no size computation.
3891 // Otherwise, evaluate and record it.
3892 if (auto Size = VAT->getSizeExpr()) {
3893 if (!CSI->isVLATypeCaptured(VAT)) {
3894 RecordDecl *CapRecord = nullptr;
3895 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3896 CapRecord = LSI->Lambda;
3897 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3898 CapRecord = CRSI->TheRecordDecl;
3899 }
3900 if (CapRecord) {
3901 auto ExprLoc = Size->getExprLoc();
3902 auto SizeType = Context.getSizeType();
3903 // Build the non-static data member.
3904 auto Field =
3905 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3906 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3907 /*BW*/ nullptr, /*Mutable*/ false,
3908 /*InitStyle*/ ICIS_NoInit);
3909 Field->setImplicit(true);
3910 Field->setAccess(AS_private);
3911 Field->setCapturedVLAType(VAT);
3912 CapRecord->addDecl(Field);
3913
3914 CSI->addVLATypeCapture(ExprLoc, SizeType);
3915 }
3916 }
3917 }
3918 T = VAT->getElementType();
3919 break;
3920 }
3921 case Type::FunctionProto:
3922 case Type::FunctionNoProto:
3923 T = cast<FunctionType>(Ty)->getReturnType();
3924 break;
3925 case Type::Paren:
3926 case Type::TypeOf:
3927 case Type::UnaryTransform:
3928 case Type::Attributed:
3929 case Type::SubstTemplateTypeParm:
3930 case Type::PackExpansion:
3931 // Keep walking after single level desugaring.
3932 T = T.getSingleStepDesugaredType(Context);
3933 break;
3934 case Type::Typedef:
3935 T = cast<TypedefType>(Ty)->desugar();
3936 break;
3937 case Type::Decltype:
3938 T = cast<DecltypeType>(Ty)->desugar();
3939 break;
3940 case Type::Auto:
3941 T = cast<AutoType>(Ty)->getDeducedType();
3942 break;
3943 case Type::TypeOfExpr:
3944 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3945 break;
3946 case Type::Atomic:
3947 T = cast<AtomicType>(Ty)->getValueType();
3948 break;
3949 }
3950 } while (!T.isNull() && T->isVariablyModifiedType());
3951}
3952
Douglas Gregor0950e412009-03-13 21:01:28 +00003953/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00003954ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003955Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3956 SourceLocation OpLoc,
3957 UnaryExprOrTypeTrait ExprKind,
3958 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00003959 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00003960 return ExprError();
3961
John McCallbcd03502009-12-07 02:54:59 +00003962 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00003963
Douglas Gregor0950e412009-03-13 21:01:28 +00003964 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00003965 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00003966 return ExprError();
3967
Alexey Bataev93a546a2016-01-21 12:54:48 +00003968 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3969 if (auto *TT = T->getAs<TypedefType>()) {
Alexey Bataev41ed6b72016-01-25 07:06:23 +00003970 for (auto I = FunctionScopes.rbegin(),
3971 E = std::prev(FunctionScopes.rend());
3972 I != E; ++I) {
3973 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
3974 if (CSI == nullptr)
3975 break;
Alexey Bataev93a546a2016-01-21 12:54:48 +00003976 DeclContext *DC = nullptr;
Alexey Bataev41ed6b72016-01-25 07:06:23 +00003977 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
Alexey Bataev93a546a2016-01-21 12:54:48 +00003978 DC = LSI->CallOperator;
Alexey Bataev41ed6b72016-01-25 07:06:23 +00003979 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
Alexey Bataev93a546a2016-01-21 12:54:48 +00003980 DC = CRSI->TheCapturedDecl;
Alexey Bataev41ed6b72016-01-25 07:06:23 +00003981 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
3982 DC = BSI->TheDecl;
3983 if (DC) {
3984 if (DC->containsDecl(TT->getDecl()))
3985 break;
Alexey Bataev93a546a2016-01-21 12:54:48 +00003986 captureVariablyModifiedType(Context, T, CSI);
Alexey Bataev41ed6b72016-01-25 07:06:23 +00003987 }
Alexey Bataev93a546a2016-01-21 12:54:48 +00003988 }
3989 }
3990 }
3991
Douglas Gregor0950e412009-03-13 21:01:28 +00003992 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003993 return new (Context) UnaryExprOrTypeTraitExpr(
3994 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
Douglas Gregor0950e412009-03-13 21:01:28 +00003995}
3996
3997/// \brief Build a sizeof or alignof expression given an expression
3998/// operand.
John McCalldadc5752010-08-24 06:29:42 +00003999ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00004000Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4001 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00004002 ExprResult PE = CheckPlaceholderExpr(E);
4003 if (PE.isInvalid())
4004 return ExprError();
4005
4006 E = PE.get();
4007
Douglas Gregor0950e412009-03-13 21:01:28 +00004008 // Verify that the operand is valid.
4009 bool isInvalid = false;
4010 if (E->isTypeDependent()) {
4011 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00004012 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00004013 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00004014 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00004015 isInvalid = CheckVecStepExpr(E);
Alexey Bataev00396512015-07-02 03:40:19 +00004016 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4017 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4018 isInvalid = true;
John McCalld25db7e2013-05-06 21:39:12 +00004019 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
Richard Smithe301ba22015-11-11 02:02:15 +00004020 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00004021 isInvalid = true;
4022 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00004023 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00004024 }
4025
4026 if (isInvalid)
4027 return ExprError();
4028
Eli Friedmane0afc982012-01-21 01:01:51 +00004029 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
Benjamin Kramerd81108f2012-11-14 15:08:31 +00004030 PE = TransformToPotentiallyEvaluated(E);
Eli Friedmane0afc982012-01-21 01:01:51 +00004031 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004032 E = PE.get();
Eli Friedmane0afc982012-01-21 01:01:51 +00004033 }
4034
Douglas Gregor0950e412009-03-13 21:01:28 +00004035 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004036 return new (Context) UnaryExprOrTypeTraitExpr(
4037 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
Douglas Gregor0950e412009-03-13 21:01:28 +00004038}
4039
Peter Collingbournee190dee2011-03-11 19:24:49 +00004040/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4041/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00004042/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00004043ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00004044Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004045 UnaryExprOrTypeTrait ExprKind, bool IsType,
Craig Toppere335f252015-10-04 04:53:55 +00004046 void *TyOrEx, SourceRange ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00004047 // If error parsing type, ignore.
Craig Topperc3ec1492014-05-26 06:22:03 +00004048 if (!TyOrEx) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00004049
Richard Trieuba63ce62011-09-09 01:45:06 +00004050 if (IsType) {
John McCallbcd03502009-12-07 02:54:59 +00004051 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00004052 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00004053 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00004054 }
Sebastian Redl6f282892008-11-11 17:56:53 +00004055
Douglas Gregor0950e412009-03-13 21:01:28 +00004056 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00004057 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004058 return Result;
Chris Lattnere168f762006-11-10 05:29:30 +00004059}
4060
John Wiegley01296292011-04-08 18:41:53 +00004061static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004062 bool IsReal) {
John Wiegley01296292011-04-08 18:41:53 +00004063 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00004064 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00004065
John McCall34376a62010-12-04 03:47:34 +00004066 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00004067 if (V.get()->getObjectKind() != OK_Ordinary) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004068 V = S.DefaultLvalueConversion(V.get());
John Wiegley01296292011-04-08 18:41:53 +00004069 if (V.isInvalid())
4070 return QualType();
4071 }
John McCall34376a62010-12-04 03:47:34 +00004072
Chris Lattnere267f5d2007-08-26 05:39:26 +00004073 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00004074 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00004075 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00004076
Chris Lattnere267f5d2007-08-26 05:39:26 +00004077 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00004078 if (V.get()->getType()->isArithmeticType())
4079 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004080
John McCall36226622010-10-12 02:09:17 +00004081 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00004082 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00004083 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004084 if (PR.get() != V.get()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004085 V = PR;
Richard Trieuba63ce62011-09-09 01:45:06 +00004086 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall36226622010-10-12 02:09:17 +00004087 }
4088
Chris Lattnere267f5d2007-08-26 05:39:26 +00004089 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00004090 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuba63ce62011-09-09 01:45:06 +00004091 << (IsReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00004092 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00004093}
4094
4095
Chris Lattnere168f762006-11-10 05:29:30 +00004096
John McCalldadc5752010-08-24 06:29:42 +00004097ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004098Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00004099 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00004100 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00004101 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00004102 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00004103 case tok::plusplus: Opc = UO_PostInc; break;
4104 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00004105 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004106
Sebastian Redla9351792012-02-11 23:51:47 +00004107 // Since this might is a postfix expression, get rid of ParenListExprs.
4108 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4109 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004110 Input = Result.get();
Sebastian Redla9351792012-02-11 23:51:47 +00004111
John McCallb268a282010-08-23 23:25:46 +00004112 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00004113}
4114
John McCallf2538342012-07-31 05:14:30 +00004115/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4116///
4117/// \return true on error
4118static bool checkArithmeticOnObjCPointer(Sema &S,
4119 SourceLocation opLoc,
4120 Expr *op) {
4121 assert(op->getType()->isObjCObjectPointerType());
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +00004122 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4123 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
John McCallf2538342012-07-31 05:14:30 +00004124 return false;
4125
4126 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4127 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4128 << op->getSourceRange();
4129 return true;
4130}
4131
Alexey Bataevf7630272015-11-25 12:01:00 +00004132static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4133 auto *BaseNoParens = Base->IgnoreParens();
4134 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4135 return MSProp->getPropertyDecl()->getType()->isArrayType();
4136 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4137}
4138
John McCalldadc5752010-08-24 06:29:42 +00004139ExprResult
John McCallf22d0ac2013-03-04 01:30:55 +00004140Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4141 Expr *idx, SourceLocation rbLoc) {
Alexey Bataev627cbd32015-08-25 15:15:12 +00004142 if (base && !base->getType().isNull() &&
4143 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004144 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4145 /*Length=*/nullptr, rbLoc);
4146
Nate Begeman5ec4b312009-08-10 23:49:36 +00004147 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCallf22d0ac2013-03-04 01:30:55 +00004148 if (isa<ParenListExpr>(base)) {
4149 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4150 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004151 base = result.get();
John McCallf22d0ac2013-03-04 01:30:55 +00004152 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00004153
John McCallf22d0ac2013-03-04 01:30:55 +00004154 // Handle any non-overload placeholder types in the base and index
4155 // expressions. We can't handle overloads here because the other
4156 // operand might be an overloadable type, in which case the overload
4157 // resolution for the operator overload should get the first crack
4158 // at the overload.
Alexey Bataevf7630272015-11-25 12:01:00 +00004159 bool IsMSPropertySubscript = false;
John McCallf22d0ac2013-03-04 01:30:55 +00004160 if (base->getType()->isNonOverloadPlaceholderType()) {
Alexey Bataevf7630272015-11-25 12:01:00 +00004161 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4162 if (!IsMSPropertySubscript) {
4163 ExprResult result = CheckPlaceholderExpr(base);
4164 if (result.isInvalid())
4165 return ExprError();
4166 base = result.get();
4167 }
John McCallf22d0ac2013-03-04 01:30:55 +00004168 }
4169 if (idx->getType()->isNonOverloadPlaceholderType()) {
4170 ExprResult result = CheckPlaceholderExpr(idx);
4171 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004172 idx = result.get();
John McCallf22d0ac2013-03-04 01:30:55 +00004173 }
Mike Stump11289f42009-09-09 15:08:12 +00004174
John McCallf22d0ac2013-03-04 01:30:55 +00004175 // Build an unanalyzed expression if either operand is type-dependent.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004176 if (getLangOpts().CPlusPlus &&
John McCallf22d0ac2013-03-04 01:30:55 +00004177 (base->isTypeDependent() || idx->isTypeDependent())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004178 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4179 VK_LValue, OK_Ordinary, rbLoc);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00004180 }
4181
Alexey Bataevf7630272015-11-25 12:01:00 +00004182 // MSDN, property (C++)
4183 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4184 // This attribute can also be used in the declaration of an empty array in a
4185 // class or structure definition. For example:
4186 // __declspec(property(get=GetX, put=PutX)) int x[];
4187 // The above statement indicates that x[] can be used with one or more array
4188 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4189 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4190 if (IsMSPropertySubscript) {
4191 // Build MS property subscript expression if base is MS property reference
4192 // or MS property subscript.
4193 return new (Context) MSPropertySubscriptExpr(
4194 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4195 }
4196
John McCallf22d0ac2013-03-04 01:30:55 +00004197 // Use C++ overloaded-operator rules if either operand has record
4198 // type. The spec says to do this if either type is *overloadable*,
4199 // but enum types can't declare subscript operators or conversion
4200 // operators, so there's nothing interesting for overload resolution
4201 // to do if there aren't any record types involved.
4202 //
4203 // ObjC pointers have their own subscripting logic that is not tied
4204 // to overload resolution and so should not take this path.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004205 if (getLangOpts().CPlusPlus &&
John McCallf22d0ac2013-03-04 01:30:55 +00004206 (base->getType()->isRecordType() ||
4207 (!base->getType()->isObjCObjectPointerType() &&
4208 idx->getType()->isRecordType()))) {
4209 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00004210 }
4211
John McCallf22d0ac2013-03-04 01:30:55 +00004212 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00004213}
4214
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004215ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4216 Expr *LowerBound,
4217 SourceLocation ColonLoc, Expr *Length,
4218 SourceLocation RBLoc) {
4219 if (Base->getType()->isPlaceholderType() &&
4220 !Base->getType()->isSpecificPlaceholderType(
4221 BuiltinType::OMPArraySection)) {
4222 ExprResult Result = CheckPlaceholderExpr(Base);
4223 if (Result.isInvalid())
4224 return ExprError();
4225 Base = Result.get();
4226 }
4227 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4228 ExprResult Result = CheckPlaceholderExpr(LowerBound);
4229 if (Result.isInvalid())
4230 return ExprError();
Alexey Bataev31300ed2016-02-04 11:27:03 +00004231 Result = DefaultLvalueConversion(Result.get());
4232 if (Result.isInvalid())
4233 return ExprError();
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004234 LowerBound = Result.get();
4235 }
4236 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4237 ExprResult Result = CheckPlaceholderExpr(Length);
4238 if (Result.isInvalid())
4239 return ExprError();
Alexey Bataev31300ed2016-02-04 11:27:03 +00004240 Result = DefaultLvalueConversion(Result.get());
4241 if (Result.isInvalid())
4242 return ExprError();
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004243 Length = Result.get();
4244 }
4245
4246 // Build an unanalyzed expression if either operand is type-dependent.
4247 if (Base->isTypeDependent() ||
4248 (LowerBound &&
4249 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4250 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4251 return new (Context)
4252 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4253 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4254 }
4255
4256 // Perform default conversions.
Alexey Bataeva1764212015-09-30 09:22:36 +00004257 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004258 QualType ResultTy;
4259 if (OriginalTy->isAnyPointerType()) {
4260 ResultTy = OriginalTy->getPointeeType();
4261 } else if (OriginalTy->isArrayType()) {
4262 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4263 } else {
4264 return ExprError(
4265 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4266 << Base->getSourceRange());
4267 }
4268 // C99 6.5.2.1p1
4269 if (LowerBound) {
4270 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4271 LowerBound);
4272 if (Res.isInvalid())
4273 return ExprError(Diag(LowerBound->getExprLoc(),
4274 diag::err_omp_typecheck_section_not_integer)
4275 << 0 << LowerBound->getSourceRange());
4276 LowerBound = Res.get();
4277
4278 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4279 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4280 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4281 << 0 << LowerBound->getSourceRange();
4282 }
4283 if (Length) {
4284 auto Res =
4285 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4286 if (Res.isInvalid())
4287 return ExprError(Diag(Length->getExprLoc(),
4288 diag::err_omp_typecheck_section_not_integer)
4289 << 1 << Length->getSourceRange());
4290 Length = Res.get();
4291
4292 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4293 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4294 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4295 << 1 << Length->getSourceRange();
4296 }
4297
4298 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4299 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4300 // type. Note that functions are not objects, and that (in C99 parlance)
4301 // incomplete types are not object types.
4302 if (ResultTy->isFunctionType()) {
4303 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4304 << ResultTy << Base->getSourceRange();
4305 return ExprError();
4306 }
4307
4308 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4309 diag::err_omp_section_incomplete_type, Base))
4310 return ExprError();
4311
4312 if (LowerBound) {
4313 llvm::APSInt LowerBoundValue;
4314 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4315 // OpenMP 4.0, [2.4 Array Sections]
4316 // The lower-bound and length must evaluate to non-negative integers.
4317 if (LowerBoundValue.isNegative()) {
4318 Diag(LowerBound->getExprLoc(), diag::err_omp_section_negative)
4319 << 0 << LowerBoundValue.toString(/*Radix=*/10, /*Signed=*/true)
4320 << LowerBound->getSourceRange();
4321 return ExprError();
4322 }
4323 }
4324 }
4325
4326 if (Length) {
4327 llvm::APSInt LengthValue;
4328 if (Length->EvaluateAsInt(LengthValue, Context)) {
4329 // OpenMP 4.0, [2.4 Array Sections]
4330 // The lower-bound and length must evaluate to non-negative integers.
4331 if (LengthValue.isNegative()) {
4332 Diag(Length->getExprLoc(), diag::err_omp_section_negative)
4333 << 1 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4334 << Length->getSourceRange();
4335 return ExprError();
4336 }
4337 }
4338 } else if (ColonLoc.isValid() &&
4339 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4340 !OriginalTy->isVariableArrayType()))) {
4341 // OpenMP 4.0, [2.4 Array Sections]
4342 // When the size of the array dimension is not known, the length must be
4343 // specified explicitly.
4344 Diag(ColonLoc, diag::err_omp_section_length_undefined)
4345 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4346 return ExprError();
4347 }
4348
Alexey Bataev31300ed2016-02-04 11:27:03 +00004349 if (!Base->getType()->isSpecificPlaceholderType(
4350 BuiltinType::OMPArraySection)) {
4351 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4352 if (Result.isInvalid())
4353 return ExprError();
4354 Base = Result.get();
4355 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004356 return new (Context)
4357 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4358 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4359}
4360
John McCalldadc5752010-08-24 06:29:42 +00004361ExprResult
John McCallb268a282010-08-23 23:25:46 +00004362Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004363 Expr *Idx, SourceLocation RLoc) {
John McCallb268a282010-08-23 23:25:46 +00004364 Expr *LHSExp = Base;
4365 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00004366
Chris Lattner36d572b2007-07-16 00:14:47 +00004367 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00004368 if (!LHSExp->getType()->getAs<VectorType>()) {
4369 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4370 if (Result.isInvalid())
4371 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004372 LHSExp = Result.get();
John Wiegley01296292011-04-08 18:41:53 +00004373 }
4374 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4375 if (Result.isInvalid())
4376 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004377 RHSExp = Result.get();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004378
Chris Lattner36d572b2007-07-16 00:14:47 +00004379 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00004380 ExprValueKind VK = VK_LValue;
4381 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00004382
Steve Naroffc1aadb12007-03-28 21:49:40 +00004383 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00004384 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00004385 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00004386 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00004387 Expr *BaseExpr, *IndexExpr;
4388 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004389 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4390 BaseExpr = LHSExp;
4391 IndexExpr = RHSExp;
4392 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004393 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00004394 BaseExpr = LHSExp;
4395 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00004396 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004397 } else if (const ObjCObjectPointerType *PTy =
John McCallf2538342012-07-31 05:14:30 +00004398 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004399 BaseExpr = LHSExp;
4400 IndexExpr = RHSExp;
John McCallf2538342012-07-31 05:14:30 +00004401
4402 // Use custom logic if this should be the pseudo-object subscript
4403 // expression.
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +00004404 if (!LangOpts.isSubscriptPointerArithmetic())
Craig Topperc3ec1492014-05-26 06:22:03 +00004405 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4406 nullptr);
John McCallf2538342012-07-31 05:14:30 +00004407
Steve Naroff7cae42b2009-07-10 23:34:53 +00004408 ResultType = PTy->getPointeeType();
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00004409 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4410 // Handle the uncommon case of "123[Ptr]".
4411 BaseExpr = RHSExp;
4412 IndexExpr = LHSExp;
4413 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004414 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00004415 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004416 // Handle the uncommon case of "123[Ptr]".
4417 BaseExpr = RHSExp;
4418 IndexExpr = LHSExp;
4419 ResultType = PTy->getPointeeType();
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +00004420 if (!LangOpts.isSubscriptPointerArithmetic()) {
John McCallf2538342012-07-31 05:14:30 +00004421 Diag(LLoc, diag::err_subscript_nonfragile_interface)
4422 << ResultType << BaseExpr->getSourceRange();
4423 return ExprError();
4424 }
John McCall9dd450b2009-09-21 23:43:11 +00004425 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00004426 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00004427 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00004428 VK = LHSExp->getValueKind();
4429 if (VK != VK_RValue)
4430 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00004431
Chris Lattner36d572b2007-07-16 00:14:47 +00004432 // FIXME: need to deal with const...
4433 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00004434 } else if (LHSTy->isArrayType()) {
4435 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00004436 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00004437 // wasn't promoted because of the C90 rule that doesn't
4438 // allow promoting non-lvalue arrays. Warn, then
4439 // force the promotion here.
4440 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4441 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004442 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004443 CK_ArrayToPointerDecay).get();
Eli Friedmanab2784f2009-04-25 23:46:54 +00004444 LHSTy = LHSExp->getType();
4445
4446 BaseExpr = LHSExp;
4447 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004448 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00004449 } else if (RHSTy->isArrayType()) {
4450 // Same as previous, except for 123[f().a] case
4451 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4452 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004453 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004454 CK_ArrayToPointerDecay).get();
Eli Friedmanab2784f2009-04-25 23:46:54 +00004455 RHSTy = RHSExp->getType();
4456
4457 BaseExpr = RHSExp;
4458 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004459 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00004460 } else {
Chris Lattner003af242009-04-25 22:50:55 +00004461 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4462 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004463 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00004464 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00004465 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00004466 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4467 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00004468
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00004469 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00004470 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4471 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00004472 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4473
Douglas Gregorac1fb652009-03-24 19:52:54 +00004474 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00004475 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4476 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00004477 // incomplete types are not object types.
4478 if (ResultType->isFunctionType()) {
4479 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4480 << ResultType << BaseExpr->getSourceRange();
4481 return ExprError();
4482 }
Mike Stump11289f42009-09-09 15:08:12 +00004483
David Blaikiebbafb8a2012-03-11 07:00:24 +00004484 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00004485 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00004486 Diag(LLoc, diag::ext_gnu_subscript_void_type)
4487 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00004488
4489 // C forbids expressions of unqualified void type from being l-values.
4490 // See IsCForbiddenLValueType.
4491 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00004492 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00004493 RequireCompleteType(LLoc, ResultType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004494 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregorac1fb652009-03-24 19:52:54 +00004495 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004496
John McCall4bc41ae2010-11-18 19:01:18 +00004497 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00004498 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00004499
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004500 return new (Context)
4501 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
Chris Lattnere168f762006-11-10 05:29:30 +00004502}
4503
John McCalldadc5752010-08-24 06:29:42 +00004504ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00004505 FunctionDecl *FD,
4506 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00004507 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004508 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00004509 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00004510 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004511 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00004512 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004513 return ExprError();
4514 }
4515
4516 if (Param->hasUninstantiatedDefaultArg()) {
4517 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00004518
Richard Smith505df232012-07-22 23:45:10 +00004519 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4520 Param);
4521
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004522 // Instantiate the expression.
Richard Smith47752e42013-05-03 23:46:09 +00004523 MultiLevelTemplateArgumentList MutiLevelArgList
Craig Topperc3ec1492014-05-26 06:22:03 +00004524 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00004525
Richard Smith80934652012-07-16 01:09:10 +00004526 InstantiatingTemplate Inst(*this, CallLoc, Param,
Richard Smith47752e42013-05-03 23:46:09 +00004527 MutiLevelArgList.getInnermost());
Alp Tokerd4a72d52013-10-08 08:09:04 +00004528 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00004529 return ExprError();
Anders Carlsson355933d2009-08-25 03:49:14 +00004530
Nico Weber44887f62010-11-29 18:19:25 +00004531 ExprResult Result;
4532 {
4533 // C++ [dcl.fct.default]p5:
4534 // The names in the [default argument] expression are bound, and
4535 // the semantic constraints are checked, at the point where the
4536 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00004537 ContextRAII SavedContext(*this, FD);
Douglas Gregora86bc002012-02-16 21:36:18 +00004538 LocalInstantiationScope Local(*this);
Richard Smith47752e42013-05-03 23:46:09 +00004539 Result = SubstExpr(UninstExpr, MutiLevelArgList);
Nico Weber44887f62010-11-29 18:19:25 +00004540 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004541 if (Result.isInvalid())
4542 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004543
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004544 // Check the expression as an initializer for the parameter.
4545 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004546 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004547 InitializationKind Kind
4548 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004549 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004550 Expr *ResultE = Result.getAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00004551
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004552 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004553 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004554 if (Result.isInvalid())
4555 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004556
John McCall8a43a0d2016-01-06 23:34:20 +00004557 Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4558 Param->getOuterLocStart());
4559 if (Result.isInvalid())
4560 return ExprError();
John McCall32791cc2016-01-06 22:34:54 +00004561
4562 // Remember the instantiated default argument.
John McCall8a43a0d2016-01-06 23:34:20 +00004563 Param->setDefaultArg(Result.getAs<Expr>());
John McCall32791cc2016-01-06 22:34:54 +00004564 if (ASTMutationListener *L = getASTMutationListener()) {
4565 L->DefaultArgumentInstantiated(Param);
4566 }
Anders Carlsson355933d2009-08-25 03:49:14 +00004567 }
4568
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004569 // If the default expression creates temporaries, we need to
4570 // push them to the current stack of expression temporaries so they'll
4571 // be properly destroyed.
4572 // FIXME: We should really be rebuilding the default argument with new
4573 // bound temporaries; see the comment in PR5810.
John McCall28fc7092011-11-10 05:35:25 +00004574 // We don't need to do that with block decls, though, because
4575 // blocks in default argument expression can never capture anything.
4576 if (isa<ExprWithCleanups>(Param->getInit())) {
4577 // Set the "needs cleanups" bit regardless of whether there are
4578 // any explicit objects.
John McCall31168b02011-06-15 23:02:42 +00004579 ExprNeedsCleanups = true;
John McCall28fc7092011-11-10 05:35:25 +00004580
4581 // Append all the objects to the cleanup list. Right now, this
4582 // should always be a no-op, because blocks in default argument
4583 // expressions should never be able to capture anything.
4584 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
4585 "default argument expression has capturing blocks?");
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00004586 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004587
4588 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00004589 // Just mark all of the declarations in this potentially-evaluated expression
4590 // as being "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +00004591 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4592 /*SkipLocalVariables=*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004593 return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004594}
4595
Richard Smith55ce3522012-06-25 20:30:08 +00004596
4597Sema::VariadicCallType
4598Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4599 Expr *Fn) {
4600 if (Proto && Proto->isVariadic()) {
4601 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4602 return VariadicConstructor;
4603 else if (Fn && Fn->getType()->isBlockPointerType())
4604 return VariadicBlock;
4605 else if (FDecl) {
4606 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4607 if (Method->isInstance())
4608 return VariadicMethod;
Richard Trieu9be9c682013-06-22 02:30:38 +00004609 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4610 return VariadicMethod;
Richard Smith55ce3522012-06-25 20:30:08 +00004611 return VariadicFunction;
4612 }
4613 return VariadicDoesNotApply;
4614}
4615
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004616namespace {
4617class FunctionCallCCC : public FunctionCallFilterCCC {
4618public:
4619 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004620 unsigned NumArgs, MemberExpr *ME)
4621 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004622 FunctionName(FuncName) {}
4623
Craig Toppere14c0f82014-03-12 04:55:44 +00004624 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004625 if (!candidate.getCorrectionSpecifier() ||
4626 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4627 return false;
4628 }
4629
4630 return FunctionCallFilterCCC::ValidateCandidate(candidate);
4631 }
4632
4633private:
4634 const IdentifierInfo *const FunctionName;
4635};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004636}
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004637
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004638static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4639 FunctionDecl *FDecl,
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004640 ArrayRef<Expr *> Args) {
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004641 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4642 DeclarationName FuncName = FDecl->getDeclName();
4643 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004644
4645 if (TypoCorrection Corrected = S.CorrectTypo(
4646 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004647 S.getScopeForContext(S.CurContext), nullptr,
4648 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4649 Args.size(), ME),
John Thompson2255f2c2014-04-23 12:57:01 +00004650 Sema::CTK_ErrorRecovery)) {
Richard Smithde6d6c42015-12-29 19:43:10 +00004651 if (NamedDecl *ND = Corrected.getFoundDecl()) {
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004652 if (Corrected.isOverloaded()) {
Richard Smith100b24a2014-04-17 01:52:14 +00004653 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004654 OverloadCandidateSet::iterator Best;
Craig Topperdfe29ae2015-12-21 06:35:56 +00004655 for (NamedDecl *CD : Corrected) {
4656 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004657 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4658 OCS);
4659 }
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004660 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004661 case OR_Success:
Richard Smithde6d6c42015-12-29 19:43:10 +00004662 ND = Best->FoundDecl;
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004663 Corrected.setCorrectionDecl(ND);
4664 break;
4665 default:
4666 break;
4667 }
4668 }
Richard Smithde6d6c42015-12-29 19:43:10 +00004669 ND = ND->getUnderlyingDecl();
4670 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004671 return Corrected;
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004672 }
4673 }
4674 return TypoCorrection();
4675}
4676
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004677/// ConvertArgumentsForCall - Converts the arguments specified in
4678/// Args/NumArgs to the parameter types of the function FDecl with
4679/// function prototype Proto. Call is the call expression itself, and
4680/// Fn is the function expression. For a C++ member function, this
4681/// routine does not attempt to convert the object argument. Returns
4682/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004683bool
4684Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004685 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004686 const FunctionProtoType *Proto,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004687 ArrayRef<Expr *> Args,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00004688 SourceLocation RParenLoc,
4689 bool IsExecConfig) {
John McCallbebede42011-02-26 05:39:39 +00004690 // Bail out early if calling a builtin with custom typechecking.
John McCallbebede42011-02-26 05:39:39 +00004691 if (FDecl)
4692 if (unsigned ID = FDecl->getBuiltinID())
4693 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4694 return false;
4695
Mike Stump4e1f26a2009-02-19 03:04:26 +00004696 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004697 // assignment, to the types of the corresponding parameter, ...
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004698 unsigned NumParams = Proto->getNumParams();
Douglas Gregorb6b99612009-01-23 21:30:56 +00004699 bool Invalid = false;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004700 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
Peter Collingbourne619a8c72011-10-02 23:49:29 +00004701 unsigned FnKind = Fn->getType()->isBlockPointerType()
4702 ? 1 /* block */
4703 : (IsExecConfig ? 3 /* kernel function (exec config) */
4704 : 0 /* function */);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004705
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004706 // If too few arguments are available (and we don't have default
4707 // arguments for the remaining parameters), don't make the call.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004708 if (Args.size() < NumParams) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004709 if (Args.size() < MinArgs) {
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004710 TypoCorrection TC;
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004711 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004712 unsigned diag_id =
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004713 MinArgs == NumParams && !Proto->isVariadic()
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004714 ? diag::err_typecheck_call_too_few_args_suggest
4715 : diag::err_typecheck_call_too_few_args_at_least_suggest;
Richard Smithf9b15102013-08-17 00:46:16 +00004716 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4717 << static_cast<unsigned>(Args.size())
Kaelyn Uhrain59baee82014-01-28 00:46:47 +00004718 << TC.getCorrectionRange());
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004719 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004720 Diag(RParenLoc,
4721 MinArgs == NumParams && !Proto->isVariadic()
4722 ? diag::err_typecheck_call_too_few_args_one
4723 : diag::err_typecheck_call_too_few_args_at_least_one)
4724 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
Richard Smith10ff50d2012-05-11 05:16:41 +00004725 else
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004726 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4727 ? diag::err_typecheck_call_too_few_args
4728 : diag::err_typecheck_call_too_few_args_at_least)
4729 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4730 << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00004731
4732 // Emit the location of the prototype.
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004733 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00004734 Diag(FDecl->getLocStart(), diag::note_callee_decl)
4735 << FDecl;
4736
4737 return true;
4738 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004739 Call->setNumArgs(Context, NumParams);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004740 }
4741
4742 // If too many are passed and not variadic, error on the extras and drop
4743 // them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004744 if (Args.size() > NumParams) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004745 if (!Proto->isVariadic()) {
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004746 TypoCorrection TC;
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004747 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004748 unsigned diag_id =
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004749 MinArgs == NumParams && !Proto->isVariadic()
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004750 ? diag::err_typecheck_call_too_many_args_suggest
4751 : diag::err_typecheck_call_too_many_args_at_most_suggest;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004752 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
Richard Smithf9b15102013-08-17 00:46:16 +00004753 << static_cast<unsigned>(Args.size())
Kaelyn Uhrain59baee82014-01-28 00:46:47 +00004754 << TC.getCorrectionRange());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004755 } else if (NumParams == 1 && FDecl &&
Richard Smithf9b15102013-08-17 00:46:16 +00004756 FDecl->getParamDecl(0)->getDeclName())
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004757 Diag(Args[NumParams]->getLocStart(),
4758 MinArgs == NumParams
4759 ? diag::err_typecheck_call_too_many_args_one
4760 : diag::err_typecheck_call_too_many_args_at_most_one)
4761 << FnKind << FDecl->getParamDecl(0)
4762 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4763 << SourceRange(Args[NumParams]->getLocStart(),
4764 Args.back()->getLocEnd());
Richard Smithd72da152012-05-15 06:21:54 +00004765 else
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004766 Diag(Args[NumParams]->getLocStart(),
4767 MinArgs == NumParams
4768 ? diag::err_typecheck_call_too_many_args
4769 : diag::err_typecheck_call_too_many_args_at_most)
4770 << FnKind << NumParams << static_cast<unsigned>(Args.size())
4771 << Fn->getSourceRange()
4772 << SourceRange(Args[NumParams]->getLocStart(),
4773 Args.back()->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00004774
4775 // Emit the location of the prototype.
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004776 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00004777 Diag(FDecl->getLocStart(), diag::note_callee_decl)
4778 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00004779
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004780 // This deletes the extra arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004781 Call->setNumArgs(Context, NumParams);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004782 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004783 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004784 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004785 SmallVector<Expr *, 8> AllArgs;
Richard Smith55ce3522012-06-25 20:30:08 +00004786 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4787
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004788 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004789 Proto, 0, Args, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004790 if (Invalid)
4791 return true;
4792 unsigned TotalNumArgs = AllArgs.size();
4793 for (unsigned i = 0; i < TotalNumArgs; ++i)
4794 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004795
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004796 return false;
4797}
Mike Stump4e1f26a2009-02-19 03:04:26 +00004798
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004799bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004800 const FunctionProtoType *Proto,
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004801 unsigned FirstParam, ArrayRef<Expr *> Args,
Craig Topper5603df42013-07-05 19:34:19 +00004802 SmallVectorImpl<Expr *> &AllArgs,
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004803 VariadicCallType CallType, bool AllowExplicit,
Richard Smith6b216962013-02-05 05:52:24 +00004804 bool IsListInitialization) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004805 unsigned NumParams = Proto->getNumParams();
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004806 bool Invalid = false;
Craig Topperdfe29ae2015-12-21 06:35:56 +00004807 size_t ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004808 // Continue to check argument types (even if we have too few/many args).
Richard Smithd6f9e732014-05-13 19:56:21 +00004809 for (unsigned i = FirstParam; i < NumParams; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004810 QualType ProtoArgType = Proto->getParamType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004811
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004812 Expr *Arg;
Richard Smithd6f9e732014-05-13 19:56:21 +00004813 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004814 if (ArgIx < Args.size()) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004815 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004816
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004817 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedman3164fb12009-03-22 22:00:50 +00004818 ProtoArgType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004819 diag::err_call_incomplete_argument, Arg))
Eli Friedman3164fb12009-03-22 22:00:50 +00004820 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004821
John McCall4124c492011-10-17 18:40:02 +00004822 // Strip the unbridged-cast placeholder expression off, if applicable.
Fariborz Jahanian48d94c82013-07-31 18:39:08 +00004823 bool CFAudited = false;
John McCall4124c492011-10-17 18:40:02 +00004824 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4825 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4826 (!Param || !Param->hasAttr<CFConsumedAttr>()))
4827 Arg = stripARCUnbridgedCast(Arg);
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004828 else if (getLangOpts().ObjCAutoRefCount &&
4829 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
Fariborz Jahanian48d94c82013-07-31 18:39:08 +00004830 (!Param || !Param->hasAttr<CFConsumedAttr>()))
4831 CFAudited = true;
John McCall4124c492011-10-17 18:40:02 +00004832
Alp Toker9cacbab2014-01-20 20:26:09 +00004833 InitializedEntity Entity =
4834 Param ? InitializedEntity::InitializeParameter(Context, Param,
4835 ProtoArgType)
4836 : InitializedEntity::InitializeParameter(
4837 Context, ProtoArgType, Proto->isParamConsumed(i));
4838
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004839 // Remember that parameter belongs to a CF audited API.
Fariborz Jahanian48d94c82013-07-31 18:39:08 +00004840 if (CFAudited)
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004841 Entity.setParameterCFAudited();
Richard Smithd6f9e732014-05-13 19:56:21 +00004842
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004843 ExprResult ArgE = PerformCopyInitialization(
4844 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004845 if (ArgE.isInvalid())
4846 return true;
4847
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004848 Arg = ArgE.getAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004849 } else {
Richard Smithd6f9e732014-05-13 19:56:21 +00004850 assert(Param && "can't use default arguments without a known callee");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004851
John McCalldadc5752010-08-24 06:29:42 +00004852 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004853 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004854 if (ArgExpr.isInvalid())
4855 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004856
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004857 Arg = ArgExpr.getAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004858 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004859
4860 // Check for array bounds violations for each argument to the call. This
4861 // check only triggers warnings when the argument isn't a more complex Expr
4862 // with its own checking, such as a BinaryOperator.
4863 CheckArrayAccess(Arg);
4864
Peter Collingbournea48f33f2011-10-19 00:16:45 +00004865 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4866 CheckStaticArrayArgument(CallLoc, Param, Arg);
4867
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004868 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004869 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004870
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004871 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004872 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00004873 // Assume that extern "C" functions with variadic arguments that
4874 // return __unknown_anytype aren't *really* variadic.
Alp Toker314cc812014-01-25 16:55:45 +00004875 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4876 FDecl->isExternC()) {
Craig Topperdfe29ae2015-12-21 06:35:56 +00004877 for (Expr *A : Args.slice(ArgIx)) {
John McCallcc5788c2013-03-04 07:34:02 +00004878 QualType paramType; // ignored
Craig Topperdfe29ae2015-12-21 06:35:56 +00004879 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
John McCall2979fe02011-04-12 00:42:48 +00004880 Invalid |= arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004881 AllArgs.push_back(arg.get());
John McCall2979fe02011-04-12 00:42:48 +00004882 }
4883
4884 // Otherwise do argument promotion, (C99 6.5.2.2p7).
4885 } else {
Craig Topperdfe29ae2015-12-21 06:35:56 +00004886 for (Expr *A : Args.slice(ArgIx)) {
4887 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
John McCall2979fe02011-04-12 00:42:48 +00004888 Invalid |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004889 AllArgs.push_back(Arg.get());
John McCall2979fe02011-04-12 00:42:48 +00004890 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004891 }
Ted Kremenekd41f3462011-09-26 23:36:13 +00004892
4893 // Check for array bounds violations.
Craig Topperdfe29ae2015-12-21 06:35:56 +00004894 for (Expr *A : Args.slice(ArgIx))
4895 CheckArrayAccess(A);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004896 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00004897 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004898}
4899
Peter Collingbournea48f33f2011-10-19 00:16:45 +00004900static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4901 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
Reid Kleckner8a365022013-06-24 17:51:48 +00004902 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4903 TL = DTL.getOriginalLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00004904 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
Peter Collingbournea48f33f2011-10-19 00:16:45 +00004905 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
David Blaikie6adc78e2013-02-18 22:06:02 +00004906 << ATL.getLocalSourceRange();
Peter Collingbournea48f33f2011-10-19 00:16:45 +00004907}
4908
4909/// CheckStaticArrayArgument - If the given argument corresponds to a static
4910/// array parameter, check that it is non-null, and that if it is formed by
4911/// array-to-pointer decay, the underlying array is sufficiently large.
4912///
4913/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4914/// array type derivation, then for each call to the function, the value of the
4915/// corresponding actual argument shall provide access to the first element of
4916/// an array with at least as many elements as specified by the size expression.
4917void
4918Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4919 ParmVarDecl *Param,
4920 const Expr *ArgExpr) {
4921 // Static array parameters are not supported in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004922 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbournea48f33f2011-10-19 00:16:45 +00004923 return;
4924
4925 QualType OrigTy = Param->getOriginalType();
4926
4927 const ArrayType *AT = Context.getAsArrayType(OrigTy);
4928 if (!AT || AT->getSizeModifier() != ArrayType::Static)
4929 return;
4930
4931 if (ArgExpr->isNullPointerConstant(Context,
4932 Expr::NPC_NeverValueDependent)) {
4933 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4934 DiagnoseCalleeStaticArrayParam(*this, Param);
4935 return;
4936 }
4937
4938 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4939 if (!CAT)
4940 return;
4941
4942 const ConstantArrayType *ArgCAT =
4943 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4944 if (!ArgCAT)
4945 return;
4946
4947 if (ArgCAT->getSize().ult(CAT->getSize())) {
4948 Diag(CallLoc, diag::warn_static_array_too_small)
4949 << ArgExpr->getSourceRange()
4950 << (unsigned) ArgCAT->getSize().getZExtValue()
4951 << (unsigned) CAT->getSize().getZExtValue();
4952 DiagnoseCalleeStaticArrayParam(*this, Param);
4953 }
4954}
4955
John McCall2979fe02011-04-12 00:42:48 +00004956/// Given a function expression of unknown-any type, try to rebuild it
4957/// to have a function type.
4958static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4959
John McCall5e77d762013-04-16 07:28:30 +00004960/// Is the given type a placeholder that we need to lower out
4961/// immediately during argument processing?
4962static bool isPlaceholderToRemoveAsArg(QualType type) {
4963 // Placeholders are never sugared.
4964 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4965 if (!placeholder) return false;
4966
4967 switch (placeholder->getKind()) {
4968 // Ignore all the non-placeholder types.
Alexey Bader954ba212016-04-08 13:40:33 +00004969#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
4970 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00004971#include "clang/Basic/OpenCLImageTypes.def"
John McCall5e77d762013-04-16 07:28:30 +00004972#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4973#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4974#include "clang/AST/BuiltinTypes.def"
4975 return false;
4976
4977 // We cannot lower out overload sets; they might validly be resolved
4978 // by the call machinery.
4979 case BuiltinType::Overload:
4980 return false;
4981
4982 // Unbridged casts in ARC can be handled in some call positions and
4983 // should be left in place.
4984 case BuiltinType::ARCUnbridgedCast:
4985 return false;
4986
4987 // Pseudo-objects should be converted as soon as possible.
4988 case BuiltinType::PseudoObject:
4989 return true;
4990
4991 // The debugger mode could theoretically but currently does not try
4992 // to resolve unknown-typed arguments based on known parameter types.
4993 case BuiltinType::UnknownAny:
4994 return true;
4995
4996 // These are always invalid as call arguments and should be reported.
4997 case BuiltinType::BoundMember:
4998 case BuiltinType::BuiltinFn:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004999 case BuiltinType::OMPArraySection:
John McCall5e77d762013-04-16 07:28:30 +00005000 return true;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005001
John McCall5e77d762013-04-16 07:28:30 +00005002 }
5003 llvm_unreachable("bad builtin type kind");
5004}
5005
5006/// Check an argument list for placeholders that we won't try to
5007/// handle later.
5008static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5009 // Apply this processing to all the arguments at once instead of
5010 // dying at the first failure.
5011 bool hasInvalid = false;
5012 for (size_t i = 0, e = args.size(); i != e; i++) {
5013 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5014 ExprResult result = S.CheckPlaceholderExpr(args[i]);
5015 if (result.isInvalid()) hasInvalid = true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005016 else args[i] = result.get();
Kaelyn Takata15867822014-11-21 18:48:04 +00005017 } else if (hasInvalid) {
5018 (void)S.CorrectDelayedTyposInExpr(args[i]);
John McCall5e77d762013-04-16 07:28:30 +00005019 }
5020 }
5021 return hasInvalid;
5022}
5023
Tom Stellardb919c7d2015-03-31 16:39:02 +00005024/// If a builtin function has a pointer argument with no explicit address
Sanjay Patel71fca732015-12-29 20:09:37 +00005025/// space, then it should be able to accept a pointer to any address
Tom Stellardb919c7d2015-03-31 16:39:02 +00005026/// space as input. In order to do this, we need to replace the
5027/// standard builtin declaration with one that uses the same address space
5028/// as the call.
5029///
5030/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5031/// it does not contain any pointer arguments without
5032/// an address space qualifer. Otherwise the rewritten
5033/// FunctionDecl is returned.
5034/// TODO: Handle pointer return types.
5035static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5036 const FunctionDecl *FDecl,
5037 MultiExprArg ArgExprs) {
5038
5039 QualType DeclType = FDecl->getType();
5040 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5041
5042 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5043 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5044 return nullptr;
5045
5046 bool NeedsNewDecl = false;
5047 unsigned i = 0;
5048 SmallVector<QualType, 8> OverloadParams;
5049
5050 for (QualType ParamType : FT->param_types()) {
5051
5052 // Convert array arguments to pointer to simplify type lookup.
5053 Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get();
5054 QualType ArgType = Arg->getType();
5055 if (!ParamType->isPointerType() ||
5056 ParamType.getQualifiers().hasAddressSpace() ||
5057 !ArgType->isPointerType() ||
5058 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5059 OverloadParams.push_back(ParamType);
5060 continue;
5061 }
5062
5063 NeedsNewDecl = true;
5064 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5065
5066 QualType PointeeType = ParamType->getPointeeType();
5067 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5068 OverloadParams.push_back(Context.getPointerType(PointeeType));
5069 }
5070
5071 if (!NeedsNewDecl)
5072 return nullptr;
5073
5074 FunctionProtoType::ExtProtoInfo EPI;
5075 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5076 OverloadParams, EPI);
5077 DeclContext *Parent = Context.getTranslationUnitDecl();
5078 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5079 FDecl->getLocation(),
5080 FDecl->getLocation(),
5081 FDecl->getIdentifier(),
5082 OverloadTy,
5083 /*TInfo=*/nullptr,
5084 SC_Extern, false,
5085 /*hasPrototype=*/true);
5086 SmallVector<ParmVarDecl*, 16> Params;
5087 FT = cast<FunctionProtoType>(OverloadTy);
5088 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5089 QualType ParamType = FT->getParamType(i);
5090 ParmVarDecl *Parm =
5091 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5092 SourceLocation(), nullptr, ParamType,
5093 /*TInfo=*/nullptr, SC_None, nullptr);
5094 Parm->setScopeInfo(0, i);
5095 Params.push_back(Parm);
5096 }
5097 OverloadDecl->setParams(Params);
5098 return OverloadDecl;
5099}
5100
George Burgess IV21d3bff2016-03-31 00:16:25 +00005101static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee,
5102 std::size_t NumArgs) {
5103 if (S.TooManyArguments(Callee->getNumParams(), NumArgs,
5104 /*PartialOverloading=*/false))
5105 return Callee->isVariadic();
5106 return Callee->getMinRequiredArguments() <= NumArgs;
5107}
5108
Steve Naroff83895f72007-09-16 03:34:24 +00005109/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00005110/// This provides the location of the left/right parens and a list of comma
5111/// locations.
John McCalldadc5752010-08-24 06:29:42 +00005112ExprResult
John McCallb268a282010-08-23 23:25:46 +00005113Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00005114 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00005115 Expr *ExecConfig, bool IsExecConfig) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005116 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00005117 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00005118 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005119 Fn = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00005120
John McCall5e77d762013-04-16 07:28:30 +00005121 if (checkArgsForPlaceholders(*this, ArgExprs))
5122 return ExprError();
5123
David Blaikiebbafb8a2012-03-11 07:00:24 +00005124 if (getLangOpts().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00005125 // If this is a pseudo-destructor expression, build the call immediately.
5126 if (isa<CXXPseudoDestructorExpr>(Fn)) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00005127 if (!ArgExprs.empty()) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00005128 // Pseudo-destructor calls should not have any arguments.
5129 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00005130 << FixItHint::CreateRemoval(
Craig Topperd8040cf2015-10-22 01:56:16 +00005131 SourceRange(ArgExprs.front()->getLocStart(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00005132 ArgExprs.back()->getLocEnd()));
Douglas Gregorad8a3362009-09-04 17:36:40 +00005133 }
Mike Stump11289f42009-09-09 15:08:12 +00005134
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005135 return new (Context)
5136 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
Douglas Gregorad8a3362009-09-04 17:36:40 +00005137 }
John McCall5e77d762013-04-16 07:28:30 +00005138 if (Fn->getType() == Context.PseudoObjectTy) {
5139 ExprResult result = CheckPlaceholderExpr(Fn);
5140 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005141 Fn = result.get();
John McCall5e77d762013-04-16 07:28:30 +00005142 }
Mike Stump11289f42009-09-09 15:08:12 +00005143
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005144 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00005145 // in which case we won't do any semantic analysis now.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005146 bool Dependent = false;
5147 if (Fn->isTypeDependent())
5148 Dependent = true;
Benjamin Kramerc215e762012-08-24 11:54:20 +00005149 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005150 Dependent = true;
5151
Peter Collingbourne41f85462011-02-09 21:07:24 +00005152 if (Dependent) {
5153 if (ExecConfig) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005154 return new (Context) CUDAKernelCallExpr(
Benjamin Kramerc215e762012-08-24 11:54:20 +00005155 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005156 Context.DependentTy, VK_RValue, RParenLoc);
Peter Collingbourne41f85462011-02-09 21:07:24 +00005157 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005158 return new (Context) CallExpr(
5159 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
Peter Collingbourne41f85462011-02-09 21:07:24 +00005160 }
5161 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005162
5163 // Determine whether this is a call to an object (C++ [over.call.object]).
5164 if (Fn->getType()->isRecordType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005165 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
5166 RParenLoc);
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005167
John McCall2979fe02011-04-12 00:42:48 +00005168 if (Fn->getType() == Context.UnknownAnyTy) {
5169 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5170 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005171 Fn = result.get();
John McCall2979fe02011-04-12 00:42:48 +00005172 }
5173
John McCall0009fcc2011-04-26 20:42:42 +00005174 if (Fn->getType() == Context.BoundMemberTy) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005175 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00005176 }
John McCall0009fcc2011-04-26 20:42:42 +00005177 }
John McCall10eae182009-11-30 22:42:35 +00005178
John McCall0009fcc2011-04-26 20:42:42 +00005179 // Check for overloaded calls. This can happen even in C due to extensions.
5180 if (Fn->getType() == Context.OverloadTy) {
5181 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5182
Douglas Gregorcda22702011-10-13 18:10:35 +00005183 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregorf4a06c22011-10-13 18:26:27 +00005184 if (!find.HasFormOfMemberPointer) {
John McCall0009fcc2011-04-26 20:42:42 +00005185 OverloadExpr *ovl = find.Expression;
Yaron Keren442dfb42015-12-23 20:38:13 +00005186 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005187 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
George Burgess IV7204ed92016-01-07 02:26:57 +00005188 RParenLoc, ExecConfig,
5189 /*AllowTypoCorrection=*/true,
5190 find.IsAddressOfOperand);
Yaron Keren442dfb42015-12-23 20:38:13 +00005191 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00005192 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005193 }
5194
Douglas Gregore254f902009-02-04 00:32:51 +00005195 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregord8fb1e32011-12-01 01:37:36 +00005196 if (Fn->getType() == Context.UnknownAnyTy) {
5197 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5198 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005199 Fn = result.get();
Douglas Gregord8fb1e32011-12-01 01:37:36 +00005200 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005201
Eli Friedmane14b1992009-12-26 03:35:45 +00005202 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00005203
George Burgess IV7204ed92016-01-07 02:26:57 +00005204 bool CallingNDeclIndirectly = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00005205 NamedDecl *NDecl = nullptr;
George Burgess IV7204ed92016-01-07 02:26:57 +00005206 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5207 if (UnOp->getOpcode() == UO_AddrOf) {
5208 CallingNDeclIndirectly = true;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00005209 NakedFn = UnOp->getSubExpr()->IgnoreParens();
George Burgess IV7204ed92016-01-07 02:26:57 +00005210 }
5211 }
Tom Stellardb919c7d2015-03-31 16:39:02 +00005212
5213 if (isa<DeclRefExpr>(NakedFn)) {
John McCall57500772009-12-16 12:17:52 +00005214 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
Tom Stellardb919c7d2015-03-31 16:39:02 +00005215
5216 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5217 if (FDecl && FDecl->getBuiltinID()) {
Sanjay Patel71fca732015-12-29 20:09:37 +00005218 // Rewrite the function decl for this builtin by replacing parameters
Tom Stellardb919c7d2015-03-31 16:39:02 +00005219 // with no explicit address space with the address space of the arguments
5220 // in ArgExprs.
5221 if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5222 NDecl = FDecl;
5223 Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(),
5224 SourceLocation(), FDecl, false,
5225 SourceLocation(), FDecl->getType(),
5226 Fn->getValueKind(), FDecl);
5227 }
5228 }
5229 } else if (isa<MemberExpr>(NakedFn))
John McCall0009fcc2011-04-26 20:42:42 +00005230 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00005231
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005232 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
George Burgess IV7204ed92016-01-07 02:26:57 +00005233 if (CallingNDeclIndirectly &&
5234 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5235 Fn->getLocStart()))
5236 return ExprError();
5237
George Burgess IV21d3bff2016-03-31 00:16:25 +00005238 // CheckEnableIf assumes that the we're passing in a sane number of args for
5239 // FD, but that doesn't always hold true here. This is because, in some
5240 // cases, we'll emit a diag about an ill-formed function call, but then
5241 // we'll continue on as if the function call wasn't ill-formed. So, if the
5242 // number of args looks incorrect, don't do enable_if checks; we should've
5243 // already emitted an error about the bad call.
5244 if (FD->hasAttr<EnableIfAttr>() &&
5245 isNumberOfArgsValidForCall(*this, FD, ArgExprs.size())) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005246 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
5247 Diag(Fn->getLocStart(),
5248 isa<CXXMethodDecl>(FD) ?
5249 diag::err_ovl_no_viable_member_function_in_call :
5250 diag::err_ovl_no_viable_function_in_call)
5251 << FD << FD->getSourceRange();
5252 Diag(FD->getLocation(),
5253 diag::note_ovl_candidate_disabled_by_enable_if_attr)
5254 << Attr->getCond()->getSourceRange() << Attr->getMessage();
5255 }
5256 }
5257 }
5258
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005259 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5260 ExecConfig, IsExecConfig);
Peter Collingbourne41f85462011-02-09 21:07:24 +00005261}
5262
Tanya Lattner55808c12011-06-04 00:47:47 +00005263/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5264///
5265/// __builtin_astype( value, dst type )
5266///
Richard Trieuba63ce62011-09-09 01:45:06 +00005267ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00005268 SourceLocation BuiltinLoc,
5269 SourceLocation RParenLoc) {
5270 ExprValueKind VK = VK_RValue;
5271 ExprObjectKind OK = OK_Ordinary;
Richard Trieuba63ce62011-09-09 01:45:06 +00005272 QualType DstTy = GetTypeFromParser(ParsedDestTy);
5273 QualType SrcTy = E->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00005274 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5275 return ExprError(Diag(BuiltinLoc,
5276 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00005277 << DstTy
5278 << SrcTy
Richard Trieuba63ce62011-09-09 01:45:06 +00005279 << E->getSourceRange());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005280 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Tanya Lattner55808c12011-06-04 00:47:47 +00005281}
5282
Hal Finkelc4d7c822013-09-18 03:29:45 +00005283/// ActOnConvertVectorExpr - create a new convert-vector expression from the
5284/// provided arguments.
5285///
5286/// __builtin_convertvector( value, dst type )
5287///
5288ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5289 SourceLocation BuiltinLoc,
5290 SourceLocation RParenLoc) {
5291 TypeSourceInfo *TInfo;
5292 GetTypeFromParser(ParsedDestTy, &TInfo);
5293 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5294}
5295
John McCall57500772009-12-16 12:17:52 +00005296/// BuildResolvedCallExpr - Build a call to a resolved expression,
5297/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00005298/// unary-convert to an expression of function-pointer or
5299/// block-pointer type.
5300///
5301/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00005302ExprResult
John McCall2d74de92009-12-01 22:10:20 +00005303Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5304 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005305 ArrayRef<Expr *> Args,
Peter Collingbourne41f85462011-02-09 21:07:24 +00005306 SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00005307 Expr *Config, bool IsExecConfig) {
John McCall2d74de92009-12-01 22:10:20 +00005308 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
Eli Friedman34866c72012-08-31 00:14:07 +00005309 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
John McCall2d74de92009-12-01 22:10:20 +00005310
Alexey Bataevd51e9932016-01-15 04:06:31 +00005311 // Functions with 'interrupt' attribute cannot be called directly.
5312 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5313 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5314 return ExprError();
5315 }
5316
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005317 // Promote the function operand.
Eli Friedman34866c72012-08-31 00:14:07 +00005318 // We special-case function promotion here because we only allow promoting
5319 // builtin functions to function pointers in the callee of a call.
5320 ExprResult Result;
5321 if (BuiltinID &&
5322 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5323 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005324 CK_BuiltinFnToFnPtr).get();
Eli Friedman34866c72012-08-31 00:14:07 +00005325 } else {
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +00005326 Result = CallExprUnaryConversions(Fn);
Eli Friedman34866c72012-08-31 00:14:07 +00005327 }
John Wiegley01296292011-04-08 18:41:53 +00005328 if (Result.isInvalid())
5329 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005330 Fn = Result.get();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005331
Chris Lattner08464942007-12-28 05:29:59 +00005332 // Make the call expr early, before semantic checks. This guarantees cleanup
5333 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00005334 CallExpr *TheCall;
Eric Christopher13586ab2012-05-30 01:14:28 +00005335 if (Config)
Peter Collingbourne41f85462011-02-09 21:07:24 +00005336 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005337 cast<CallExpr>(Config), Args,
5338 Context.BoolTy, VK_RValue,
Peter Collingbourne41f85462011-02-09 21:07:24 +00005339 RParenLoc);
Eric Christopher13586ab2012-05-30 01:14:28 +00005340 else
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005341 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5342 VK_RValue, RParenLoc);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005343
Kaelyn Takata72d16a52015-06-23 19:13:17 +00005344 if (!getLangOpts().CPlusPlus) {
5345 // C cannot always handle TypoExpr nodes in builtin calls and direct
5346 // function calls as their argument checking don't necessarily handle
5347 // dependent types properly, so make sure any TypoExprs have been
5348 // dealt with.
5349 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5350 if (!Result.isUsable()) return ExprError();
5351 TheCall = dyn_cast<CallExpr>(Result.get());
5352 if (!TheCall) return Result;
Craig Topper882bc8d2015-11-07 06:16:16 +00005353 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
Kaelyn Takatae53f0f92015-06-23 18:42:21 +00005354 }
John McCallbebede42011-02-26 05:39:39 +00005355
Kaelyn Takata72d16a52015-06-23 19:13:17 +00005356 // Bail out early if calling a builtin with custom typechecking.
5357 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5358 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5359
John McCall31996342011-04-07 08:22:57 +00005360 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005361 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00005362 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005363 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5364 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00005365 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Craig Topperc3ec1492014-05-26 06:22:03 +00005366 if (!FuncT)
John McCallbebede42011-02-26 05:39:39 +00005367 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5368 << Fn->getType() << Fn->getSourceRange());
5369 } else if (const BlockPointerType *BPT =
5370 Fn->getType()->getAs<BlockPointerType>()) {
5371 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5372 } else {
John McCall31996342011-04-07 08:22:57 +00005373 // Handle calls to expressions of unknown-any type.
5374 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00005375 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00005376 if (rewrite.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005377 Fn = rewrite.get();
John McCall39439732011-04-09 22:50:59 +00005378 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00005379 goto retry;
5380 }
5381
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005382 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5383 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00005384 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005385
David Blaikiebbafb8a2012-03-11 07:00:24 +00005386 if (getLangOpts().CUDA) {
Peter Collingbourne4b66c472011-02-23 01:53:29 +00005387 if (Config) {
5388 // CUDA: Kernel calls must be to global functions
5389 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5390 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5391 << FDecl->getName() << Fn->getSourceRange());
5392
5393 // CUDA: Kernel function must have 'void' return type
Alp Toker314cc812014-01-25 16:55:45 +00005394 if (!FuncT->getReturnType()->isVoidType())
Peter Collingbourne4b66c472011-02-23 01:53:29 +00005395 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5396 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne34a20b02011-10-02 23:49:15 +00005397 } else {
5398 // CUDA: Calls to global functions must be configured
5399 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5400 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5401 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne4b66c472011-02-23 01:53:29 +00005402 }
5403 }
5404
Eli Friedman3164fb12009-03-22 22:00:50 +00005405 // Check for a valid return type
Alp Toker314cc812014-01-25 16:55:45 +00005406 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00005407 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00005408 return ExprError();
5409
Chris Lattner08464942007-12-28 05:29:59 +00005410 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00005411 TheCall->setType(FuncT->getCallResultType(Context));
Alp Toker314cc812014-01-25 16:55:45 +00005412 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005413
Richard Smith55ce3522012-06-25 20:30:08 +00005414 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5415 if (Proto) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005416 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5417 IsExecConfig))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005418 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00005419 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005420 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005421
Douglas Gregord8e97de2009-04-02 15:37:10 +00005422 if (FDecl) {
5423 // Check if we have too few/too many template arguments, based
5424 // on our knowledge of the function definition.
Craig Topperc3ec1492014-05-26 06:22:03 +00005425 const FunctionDecl *Def = nullptr;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005426 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
Richard Smith55ce3522012-06-25 20:30:08 +00005427 Proto = Def->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005428 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00005429 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005430 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00005431 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00005432
5433 // If the function we're calling isn't a function prototype, but we have
5434 // a function prototype from a prior declaratiom, use that prototype.
5435 if (!FDecl->hasPrototype())
5436 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00005437 }
5438
Steve Naroff0b661582007-08-28 23:30:39 +00005439 // Promote the arguments (C99 6.5.2.2p6).
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005440 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Chris Lattner08464942007-12-28 05:29:59 +00005441 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00005442
Alp Toker9cacbab2014-01-20 20:26:09 +00005443 if (Proto && i < Proto->getNumParams()) {
5444 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5445 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005446 ExprResult ArgE =
5447 PerformCopyInitialization(Entity, SourceLocation(), Arg);
Douglas Gregor8e09a722010-10-25 20:39:23 +00005448 if (ArgE.isInvalid())
5449 return true;
5450
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005451 Arg = ArgE.getAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00005452
5453 } else {
John Wiegley01296292011-04-08 18:41:53 +00005454 ExprResult ArgE = DefaultArgumentPromotion(Arg);
5455
5456 if (ArgE.isInvalid())
5457 return true;
5458
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005459 Arg = ArgE.getAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00005460 }
5461
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005462 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor83025412010-10-26 05:45:40 +00005463 Arg->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005464 diag::err_call_incomplete_argument, Arg))
Douglas Gregor83025412010-10-26 05:45:40 +00005465 return ExprError();
5466
Chris Lattner08464942007-12-28 05:29:59 +00005467 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00005468 }
Steve Naroffae4143e2007-04-26 20:39:23 +00005469 }
Chris Lattner08464942007-12-28 05:29:59 +00005470
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005471 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5472 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005473 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5474 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005475
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00005476 // Check for sentinels
5477 if (NDecl)
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005478 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
Mike Stump11289f42009-09-09 15:08:12 +00005479
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005480 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005481 if (FDecl) {
Richard Smith55ce3522012-06-25 20:30:08 +00005482 if (CheckFunctionCall(FDecl, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005483 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00005484
John McCallbebede42011-02-26 05:39:39 +00005485 if (BuiltinID)
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00005486 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005487 } else if (NDecl) {
Richard Trieu664c4c62013-06-20 21:03:13 +00005488 if (CheckPointerCall(NDecl, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005489 return ExprError();
Richard Trieu41bc0992013-06-22 00:20:41 +00005490 } else {
5491 if (CheckOtherCall(TheCall, Proto))
5492 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005493 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005494
John McCallb268a282010-08-23 23:25:46 +00005495 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00005496}
5497
John McCalldadc5752010-08-24 06:29:42 +00005498ExprResult
John McCallba7bf592010-08-24 05:47:05 +00005499Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00005500 SourceLocation RParenLoc, Expr *InitExpr) {
David Blaikie7d170102013-05-15 07:37:26 +00005501 assert(Ty && "ActOnCompoundLiteral(): missing type");
Davide Italiano99219622015-08-19 02:21:12 +00005502 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00005503
5504 TypeSourceInfo *TInfo;
5505 QualType literalType = GetTypeFromParser(Ty, &TInfo);
5506 if (!TInfo)
5507 TInfo = Context.getTrivialTypeSourceInfo(literalType);
5508
John McCallb268a282010-08-23 23:25:46 +00005509 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00005510}
5511
John McCalldadc5752010-08-24 06:29:42 +00005512ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00005513Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00005514 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00005515 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00005516
Eli Friedman37a186d2008-05-20 05:22:08 +00005517 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00005518 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005519 diag::err_illegal_decl_array_incomplete_type,
5520 SourceRange(LParenLoc,
5521 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00005522 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00005523 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005524 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuba63ce62011-09-09 01:45:06 +00005525 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00005526 } else if (!literalType->isDependentType() &&
5527 RequireCompleteType(LParenLoc, literalType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005528 diag::err_typecheck_decl_incomplete_type,
5529 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00005530 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00005531
Douglas Gregor85dabae2009-12-16 01:38:02 +00005532 InitializedEntity Entity
Jordan Rose6c0505e2013-05-06 16:48:12 +00005533 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005534 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00005535 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl0501c632012-02-12 16:37:36 +00005536 SourceRange(LParenLoc, RParenLoc),
5537 /*InitList=*/true);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005538 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005539 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5540 &literalType);
Eli Friedmana553d4a2009-12-22 02:35:53 +00005541 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005542 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00005543 LiteralExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00005544
Craig Topperc3ec1492014-05-26 06:22:03 +00005545 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
Eli Friedman4a962f02013-10-01 00:28:29 +00005546 if (isFileScope &&
5547 !LiteralExpr->isTypeDependent() &&
5548 !LiteralExpr->isValueDependent() &&
5549 !literalType->isDependentType()) { // 6.5.2.5p3
Richard Trieuba63ce62011-09-09 01:45:06 +00005550 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00005551 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00005552 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00005553
John McCall7decc9e2010-11-18 06:31:45 +00005554 // In C, compound literals are l-values for some reason.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005555 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00005556
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00005557 return MaybeBindToTemporary(
5558 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuba63ce62011-09-09 01:45:06 +00005559 VK, LiteralExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00005560}
5561
John McCalldadc5752010-08-24 06:29:42 +00005562ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00005563Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb5d49352009-01-19 22:31:54 +00005564 SourceLocation RBraceLoc) {
John McCall526ab472011-10-25 17:37:35 +00005565 // Immediately handle non-overload placeholders. Overloads can be
5566 // resolved contextually, but everything else here can't.
Benjamin Kramerc215e762012-08-24 11:54:20 +00005567 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5568 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5569 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
John McCall526ab472011-10-25 17:37:35 +00005570
5571 // Ignore failures; dropping the entire initializer list because
5572 // of one failure would be terrible for indexing/etc.
5573 if (result.isInvalid()) continue;
5574
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005575 InitArgList[I] = result.get();
John McCall526ab472011-10-25 17:37:35 +00005576 }
5577 }
5578
Steve Naroff30d242c2007-09-15 18:49:24 +00005579 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00005580 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005581
Benjamin Kramerc215e762012-08-24 11:54:20 +00005582 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5583 RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005584 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005585 return E;
Steve Narofffbd09832007-07-19 01:06:55 +00005586}
5587
John McCallcd78e802011-09-10 01:16:55 +00005588/// Do an explicit extend of the given block pointer if we're in ARC.
Douglas Gregore83b9562015-07-07 03:57:53 +00005589void Sema::maybeExtendBlockObject(ExprResult &E) {
John McCallcd78e802011-09-10 01:16:55 +00005590 assert(E.get()->getType()->isBlockPointerType());
5591 assert(E.get()->isRValue());
5592
5593 // Only do this in an r-value context.
Douglas Gregore83b9562015-07-07 03:57:53 +00005594 if (!getLangOpts().ObjCAutoRefCount) return;
John McCallcd78e802011-09-10 01:16:55 +00005595
Douglas Gregore83b9562015-07-07 03:57:53 +00005596 E = ImplicitCastExpr::Create(Context, E.get()->getType(),
John McCall2d637d22011-09-10 06:18:15 +00005597 CK_ARCExtendBlockObject, E.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005598 /*base path*/ nullptr, VK_RValue);
Douglas Gregore83b9562015-07-07 03:57:53 +00005599 ExprNeedsCleanups = true;
John McCallcd78e802011-09-10 01:16:55 +00005600}
5601
5602/// Prepare a conversion of the given expression to an ObjC object
5603/// pointer type.
5604CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5605 QualType type = E.get()->getType();
5606 if (type->isObjCObjectPointerType()) {
5607 return CK_BitCast;
5608 } else if (type->isBlockPointerType()) {
Douglas Gregore83b9562015-07-07 03:57:53 +00005609 maybeExtendBlockObject(E);
John McCallcd78e802011-09-10 01:16:55 +00005610 return CK_BlockPointerToObjCPointerCast;
5611 } else {
5612 assert(type->isPointerType());
5613 return CK_CPointerToObjCPointerCast;
5614 }
5615}
5616
John McCalld7646252010-11-14 08:17:51 +00005617/// Prepares for a scalar cast, performing all the necessary stages
5618/// except the final cast and returning the kind required.
John McCall9776e432011-10-06 23:25:11 +00005619CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00005620 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5621 // Also, callers should have filtered out the invalid cases with
5622 // pointers. Everything else should be possible.
5623
John Wiegley01296292011-04-08 18:41:53 +00005624 QualType SrcTy = Src.get()->getType();
John McCall9776e432011-10-06 23:25:11 +00005625 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00005626 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00005627
John McCall9320b872011-09-09 05:25:32 +00005628 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00005629 case Type::STK_MemberPointer:
5630 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00005631
John McCall9320b872011-09-09 05:25:32 +00005632 case Type::STK_CPointer:
5633 case Type::STK_BlockPointer:
5634 case Type::STK_ObjCObjectPointer:
John McCall8cb679e2010-11-15 09:13:47 +00005635 switch (DestTy->getScalarTypeKind()) {
David Tweede1468322013-12-11 13:39:46 +00005636 case Type::STK_CPointer: {
5637 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5638 unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5639 if (SrcAS != DestAS)
5640 return CK_AddressSpaceConversion;
John McCall9320b872011-09-09 05:25:32 +00005641 return CK_BitCast;
David Tweede1468322013-12-11 13:39:46 +00005642 }
John McCall9320b872011-09-09 05:25:32 +00005643 case Type::STK_BlockPointer:
5644 return (SrcKind == Type::STK_BlockPointer
5645 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5646 case Type::STK_ObjCObjectPointer:
5647 if (SrcKind == Type::STK_ObjCObjectPointer)
5648 return CK_BitCast;
David Blaikie8a40f702012-01-17 06:56:22 +00005649 if (SrcKind == Type::STK_CPointer)
John McCall9320b872011-09-09 05:25:32 +00005650 return CK_CPointerToObjCPointerCast;
Douglas Gregore83b9562015-07-07 03:57:53 +00005651 maybeExtendBlockObject(Src);
David Blaikie8a40f702012-01-17 06:56:22 +00005652 return CK_BlockPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00005653 case Type::STK_Bool:
5654 return CK_PointerToBoolean;
5655 case Type::STK_Integral:
5656 return CK_PointerToIntegral;
5657 case Type::STK_Floating:
5658 case Type::STK_FloatingComplex:
5659 case Type::STK_IntegralComplex:
5660 case Type::STK_MemberPointer:
5661 llvm_unreachable("illegal cast from pointer");
5662 }
David Blaikie8a40f702012-01-17 06:56:22 +00005663 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005664
John McCall8cb679e2010-11-15 09:13:47 +00005665 case Type::STK_Bool: // casting from bool is like casting from an integer
5666 case Type::STK_Integral:
5667 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00005668 case Type::STK_CPointer:
5669 case Type::STK_ObjCObjectPointer:
5670 case Type::STK_BlockPointer:
John McCall9776e432011-10-06 23:25:11 +00005671 if (Src.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005672 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00005673 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00005674 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005675 case Type::STK_Bool:
5676 return CK_IntegralToBoolean;
5677 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00005678 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00005679 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00005680 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00005681 case Type::STK_IntegralComplex:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005682 Src = ImpCastExprToType(Src.get(),
George Burgess IV45461812015-10-11 20:13:20 +00005683 DestTy->castAs<ComplexType>()->getElementType(),
5684 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00005685 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005686 case Type::STK_FloatingComplex:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005687 Src = ImpCastExprToType(Src.get(),
George Burgess IV45461812015-10-11 20:13:20 +00005688 DestTy->castAs<ComplexType>()->getElementType(),
5689 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00005690 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005691 case Type::STK_MemberPointer:
5692 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005693 }
David Blaikie8a40f702012-01-17 06:56:22 +00005694 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005695
John McCall8cb679e2010-11-15 09:13:47 +00005696 case Type::STK_Floating:
5697 switch (DestTy->getScalarTypeKind()) {
5698 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00005699 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00005700 case Type::STK_Bool:
5701 return CK_FloatingToBoolean;
5702 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00005703 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00005704 case Type::STK_FloatingComplex:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005705 Src = ImpCastExprToType(Src.get(),
John McCall9776e432011-10-06 23:25:11 +00005706 DestTy->castAs<ComplexType>()->getElementType(),
5707 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00005708 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005709 case Type::STK_IntegralComplex:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005710 Src = ImpCastExprToType(Src.get(),
John McCall9776e432011-10-06 23:25:11 +00005711 DestTy->castAs<ComplexType>()->getElementType(),
5712 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00005713 return CK_IntegralRealToComplex;
John McCall9320b872011-09-09 05:25:32 +00005714 case Type::STK_CPointer:
5715 case Type::STK_ObjCObjectPointer:
5716 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00005717 llvm_unreachable("valid float->pointer cast?");
5718 case Type::STK_MemberPointer:
5719 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005720 }
David Blaikie8a40f702012-01-17 06:56:22 +00005721 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00005722
John McCall8cb679e2010-11-15 09:13:47 +00005723 case Type::STK_FloatingComplex:
5724 switch (DestTy->getScalarTypeKind()) {
5725 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00005726 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00005727 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00005728 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00005729 case Type::STK_Floating: {
John McCall9776e432011-10-06 23:25:11 +00005730 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5731 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00005732 return CK_FloatingComplexToReal;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005733 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00005734 return CK_FloatingCast;
5735 }
John McCall8cb679e2010-11-15 09:13:47 +00005736 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00005737 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00005738 case Type::STK_Integral:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005739 Src = ImpCastExprToType(Src.get(),
John McCall9776e432011-10-06 23:25:11 +00005740 SrcTy->castAs<ComplexType>()->getElementType(),
5741 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00005742 return CK_FloatingToIntegral;
John McCall9320b872011-09-09 05:25:32 +00005743 case Type::STK_CPointer:
5744 case Type::STK_ObjCObjectPointer:
5745 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00005746 llvm_unreachable("valid complex float->pointer cast?");
5747 case Type::STK_MemberPointer:
5748 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005749 }
David Blaikie8a40f702012-01-17 06:56:22 +00005750 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00005751
John McCall8cb679e2010-11-15 09:13:47 +00005752 case Type::STK_IntegralComplex:
5753 switch (DestTy->getScalarTypeKind()) {
5754 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00005755 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005756 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00005757 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00005758 case Type::STK_Integral: {
John McCall9776e432011-10-06 23:25:11 +00005759 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5760 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00005761 return CK_IntegralComplexToReal;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005762 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00005763 return CK_IntegralCast;
5764 }
John McCall8cb679e2010-11-15 09:13:47 +00005765 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00005766 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00005767 case Type::STK_Floating:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005768 Src = ImpCastExprToType(Src.get(),
John McCall9776e432011-10-06 23:25:11 +00005769 SrcTy->castAs<ComplexType>()->getElementType(),
5770 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00005771 return CK_IntegralToFloating;
John McCall9320b872011-09-09 05:25:32 +00005772 case Type::STK_CPointer:
5773 case Type::STK_ObjCObjectPointer:
5774 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00005775 llvm_unreachable("valid complex int->pointer cast?");
5776 case Type::STK_MemberPointer:
5777 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005778 }
David Blaikie8a40f702012-01-17 06:56:22 +00005779 llvm_unreachable("Should have returned before this");
Anders Carlsson094c4592009-10-18 18:12:03 +00005780 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005781
John McCalld7646252010-11-14 08:17:51 +00005782 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson094c4592009-10-18 18:12:03 +00005783}
5784
Fariborz Jahanian328a7c42014-03-06 22:47:09 +00005785static bool breakDownVectorType(QualType type, uint64_t &len,
5786 QualType &eltType) {
5787 // Vectors are simple.
5788 if (const VectorType *vecType = type->getAs<VectorType>()) {
5789 len = vecType->getNumElements();
5790 eltType = vecType->getElementType();
5791 assert(eltType->isScalarType());
5792 return true;
5793 }
5794
5795 // We allow lax conversion to and from non-vector types, but only if
5796 // they're real types (i.e. non-complex, non-pointer scalar types).
5797 if (!type->isRealType()) return false;
5798
5799 len = 1;
5800 eltType = type;
5801 return true;
5802}
5803
John McCall1c78f082015-07-23 23:54:07 +00005804/// Are the two types lax-compatible vector types? That is, given
5805/// that one of them is a vector, do they have equal storage sizes,
5806/// where the storage size is the number of elements times the element
5807/// size?
5808///
5809/// This will also return false if either of the types is neither a
5810/// vector nor a real type.
5811bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5812 assert(destTy->isVectorType() || srcTy->isVectorType());
Stephen Canonca8eefd2015-09-15 00:21:56 +00005813
5814 // Disallow lax conversions between scalars and ExtVectors (these
5815 // conversions are allowed for other vector types because common headers
5816 // depend on them). Most scalar OP ExtVector cases are handled by the
5817 // splat path anyway, which does what we want (convert, not bitcast).
5818 // What this rules out for ExtVectors is crazy things like char4*float.
5819 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5820 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
John McCall1c78f082015-07-23 23:54:07 +00005821
Fariborz Jahanian328a7c42014-03-06 22:47:09 +00005822 uint64_t srcLen, destLen;
Vedant Kumar55c21442015-10-09 01:47:26 +00005823 QualType srcEltTy, destEltTy;
5824 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5825 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
Fariborz Jahanian328a7c42014-03-06 22:47:09 +00005826
5827 // ASTContext::getTypeSize will return the size rounded up to a
5828 // power of 2, so instead of using that, we need to use the raw
5829 // element size multiplied by the element count.
Vedant Kumar55c21442015-10-09 01:47:26 +00005830 uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5831 uint64_t destEltSize = Context.getTypeSize(destEltTy);
Fariborz Jahanian328a7c42014-03-06 22:47:09 +00005832
5833 return (srcLen * srcEltSize == destLen * destEltSize);
5834}
5835
John McCall1c78f082015-07-23 23:54:07 +00005836/// Is this a legal conversion between two types, one of which is
5837/// known to be a vector type?
Fariborz Jahanian328a7c42014-03-06 22:47:09 +00005838bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5839 assert(destTy->isVectorType() || srcTy->isVectorType());
5840
5841 if (!Context.getLangOpts().LaxVectorConversions)
5842 return false;
John McCall1c78f082015-07-23 23:54:07 +00005843 return areLaxCompatibleVectorTypes(srcTy, destTy);
Fariborz Jahanian328a7c42014-03-06 22:47:09 +00005844}
5845
Anders Carlsson525b76b2009-10-16 02:48:28 +00005846bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00005847 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00005848 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005849
John McCall1c78f082015-07-23 23:54:07 +00005850 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5851 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
Anders Carlssonde71adf2007-11-27 05:51:55 +00005852 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00005853 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00005854 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00005855 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005856 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005857 } else
5858 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00005859 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005860 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005861
John McCalle3027922010-08-25 11:45:40 +00005862 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005863 return false;
5864}
5865
George Burgess IVdf1ed002016-01-13 01:52:39 +00005866ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5867 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5868
5869 if (DestElemTy == SplattedExpr->getType())
5870 return SplattedExpr;
5871
5872 assert(DestElemTy->isFloatingType() ||
5873 DestElemTy->isIntegralOrEnumerationType());
5874
5875 CastKind CK;
5876 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5877 // OpenCL requires that we convert `true` boolean expressions to -1, but
5878 // only when splatting vectors.
5879 if (DestElemTy->isFloatingType()) {
5880 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5881 // in two steps: boolean to signed integral, then to floating.
5882 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5883 CK_BooleanToSignedIntegral);
5884 SplattedExpr = CastExprRes.get();
5885 CK = CK_IntegralToFloating;
5886 } else {
5887 CK = CK_BooleanToSignedIntegral;
5888 }
5889 } else {
5890 ExprResult CastExprRes = SplattedExpr;
5891 CK = PrepareScalarCast(CastExprRes, DestElemTy);
5892 if (CastExprRes.isInvalid())
5893 return ExprError();
5894 SplattedExpr = CastExprRes.get();
5895 }
5896 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
5897}
5898
John Wiegley01296292011-04-08 18:41:53 +00005899ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5900 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00005901 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005902
Anders Carlsson43d70f82009-10-16 05:23:41 +00005903 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005904
Nate Begemanc8961a42009-06-27 22:05:55 +00005905 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5906 // an ExtVectorType.
Tobias Grosser766bcc22011-09-22 13:03:14 +00005907 // In OpenCL, casts between vectors of different types are not allowed.
5908 // (See OpenCL 6.2).
Nate Begemanc69b7402009-06-26 00:50:28 +00005909 if (SrcTy->isVectorType()) {
John McCall1c78f082015-07-23 23:54:07 +00005910 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
David Blaikiebbafb8a2012-03-11 07:00:24 +00005911 || (getLangOpts().OpenCL &&
Tobias Grosser766bcc22011-09-22 13:03:14 +00005912 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005913 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00005914 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00005915 return ExprError();
5916 }
John McCalle3027922010-08-25 11:45:40 +00005917 Kind = CK_BitCast;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005918 return CastExpr;
Nate Begemanc69b7402009-06-26 00:50:28 +00005919 }
5920
Nate Begemanbd956c42009-06-28 02:36:38 +00005921 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00005922 // conversion will take place first from scalar to elt type, and then
5923 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00005924 if (SrcTy->isPointerType())
5925 return Diag(R.getBegin(),
5926 diag::err_invalid_conversion_between_vector_and_scalar)
5927 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00005928
John McCalle3027922010-08-25 11:45:40 +00005929 Kind = CK_VectorSplat;
George Burgess IVdf1ed002016-01-13 01:52:39 +00005930 return prepareVectorSplat(DestTy, CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00005931}
5932
John McCalldadc5752010-08-24 06:29:42 +00005933ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00005934Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5935 Declarator &D, ParsedType &Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00005936 SourceLocation RParenLoc, Expr *CastExpr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005937 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00005938 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00005939
Richard Trieuba63ce62011-09-09 01:45:06 +00005940 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00005941 if (D.isInvalidType())
5942 return ExprError();
5943
David Blaikiebbafb8a2012-03-11 07:00:24 +00005944 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00005945 // Check that there are no default arguments (C++ only).
5946 CheckExtraCXXDefaultArguments(D);
Kaelyn Takata13da33f2014-11-24 21:46:59 +00005947 } else {
5948 // Make sure any TypoExprs have been dealt with.
5949 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
5950 if (!Res.isUsable())
5951 return ExprError();
5952 CastExpr = Res.get();
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00005953 }
5954
John McCall42856de2011-10-01 05:17:03 +00005955 checkUnusedDeclAttributes(D);
5956
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00005957 QualType castType = castTInfo->getType();
5958 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00005959
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005960 bool isVectorLiteral = false;
5961
5962 // Check for an altivec or OpenCL literal,
5963 // i.e. all the elements are integer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00005964 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5965 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00005966 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
Tobias Grosser0a3a22f2011-09-21 18:28:29 +00005967 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005968 if (PLE && PLE->getNumExprs() == 0) {
5969 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5970 return ExprError();
5971 }
5972 if (PE || PLE->getNumExprs() == 1) {
5973 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5974 if (!E->getType()->isVectorType())
5975 isVectorLiteral = true;
5976 }
5977 else
5978 isVectorLiteral = true;
5979 }
5980
5981 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5982 // then handle it as such.
5983 if (isVectorLiteral)
Richard Trieuba63ce62011-09-09 01:45:06 +00005984 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005985
Nate Begeman5ec4b312009-08-10 23:49:36 +00005986 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005987 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5988 // sequence of BinOp comma operators.
Richard Trieuba63ce62011-09-09 01:45:06 +00005989 if (isa<ParenListExpr>(CastExpr)) {
5990 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005991 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005992 CastExpr = Result.get();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00005993 }
John McCallebe54742010-01-15 18:56:44 +00005994
Alp Toker15ab3732013-12-12 12:47:48 +00005995 if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
5996 !getSourceManager().isInSystemMacro(LParenLoc))
5997 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00005998
5999 CheckTollFreeBridgeCast(castType, CastExpr);
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00006000
6001 CheckObjCBridgeRelatedCast(castType, CastExpr);
6002
Richard Trieuba63ce62011-09-09 01:45:06 +00006003 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallebe54742010-01-15 18:56:44 +00006004}
6005
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00006006ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6007 SourceLocation RParenLoc, Expr *E,
6008 TypeSourceInfo *TInfo) {
6009 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6010 "Expected paren or paren list expression");
6011
6012 Expr **exprs;
6013 unsigned numExprs;
6014 Expr *subExpr;
Richard Smith9ca91012013-02-05 05:55:57 +00006015 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00006016 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
Richard Smith9ca91012013-02-05 05:55:57 +00006017 LiteralLParenLoc = PE->getLParenLoc();
6018 LiteralRParenLoc = PE->getRParenLoc();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00006019 exprs = PE->getExprs();
6020 numExprs = PE->getNumExprs();
Richard Smith9ca91012013-02-05 05:55:57 +00006021 } else { // isa<ParenExpr> by assertion at function entrance
6022 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6023 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00006024 subExpr = cast<ParenExpr>(E)->getSubExpr();
6025 exprs = &subExpr;
6026 numExprs = 1;
6027 }
6028
6029 QualType Ty = TInfo->getType();
6030 assert(Ty->isVectorType() && "Expected vector type");
6031
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006032 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00006033 const VectorType *VTy = Ty->getAs<VectorType>();
6034 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6035
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00006036 // '(...)' form of vector initialization in AltiVec: the number of
6037 // initializers must be one or must match the size of the vector.
6038 // If a single value is specified in the initializer then it will be
6039 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00006040 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00006041 // The number of initializers must be one or must match the size of the
6042 // vector. If a single value is specified in the initializer then it will
6043 // be replicated to all the components of the vector
6044 if (numExprs == 1) {
6045 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00006046 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6047 if (Literal.isInvalid())
6048 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006049 Literal = ImpCastExprToType(Literal.get(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00006050 PrepareScalarCast(Literal, ElemTy));
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006051 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00006052 }
6053 else if (numExprs < numElems) {
6054 Diag(E->getExprLoc(),
6055 diag::err_incorrect_number_of_vector_initializers);
6056 return ExprError();
6057 }
6058 else
Benjamin Kramer8001f742012-02-14 12:06:21 +00006059 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00006060 }
Tanya Lattner83559382011-07-15 23:07:01 +00006061 else {
6062 // For OpenCL, when the number of initializers is a single value,
6063 // it will be replicated to all components of the vector.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006064 if (getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +00006065 VTy->getVectorKind() == VectorType::GenericVector &&
6066 numExprs == 1) {
6067 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00006068 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6069 if (Literal.isInvalid())
6070 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006071 Literal = ImpCastExprToType(Literal.get(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00006072 PrepareScalarCast(Literal, ElemTy));
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006073 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
Tanya Lattner83559382011-07-15 23:07:01 +00006074 }
6075
Benjamin Kramer8001f742012-02-14 12:06:21 +00006076 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner83559382011-07-15 23:07:01 +00006077 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00006078 // FIXME: This means that pretty-printing the final AST will produce curly
6079 // braces instead of the original commas.
Richard Smith9ca91012013-02-05 05:55:57 +00006080 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6081 initExprs, LiteralRParenLoc);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00006082 initE->setType(Ty);
6083 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6084}
6085
Sebastian Redla9351792012-02-11 23:51:47 +00006086/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6087/// the ParenListExpr into a sequence of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00006088ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00006089Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6090 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00006091 if (!E)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006092 return OrigExpr;
Mike Stump11289f42009-09-09 15:08:12 +00006093
John McCalldadc5752010-08-24 06:29:42 +00006094 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00006095
Nate Begeman5ec4b312009-08-10 23:49:36 +00006096 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00006097 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6098 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00006099
John McCallb268a282010-08-23 23:25:46 +00006100 if (Result.isInvalid()) return ExprError();
6101
6102 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00006103}
6104
Sebastian Redla9351792012-02-11 23:51:47 +00006105ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6106 SourceLocation R,
6107 MultiExprArg Val) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00006108 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006109 return expr;
Nate Begeman5ec4b312009-08-10 23:49:36 +00006110}
6111
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00006112/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006113/// constant and the other is not a pointer. Returns true if a diagnostic is
6114/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00006115bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00006116 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00006117 Expr *NullExpr = LHSExpr;
6118 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00006119 Expr::NullPointerConstantKind NullKind =
6120 NullExpr->isNullPointerConstant(Context,
6121 Expr::NPC_ValueDependentIsNotNull);
6122
6123 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00006124 NullExpr = RHSExpr;
6125 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00006126 NullKind =
6127 NullExpr->isNullPointerConstant(Context,
6128 Expr::NPC_ValueDependentIsNotNull);
6129 }
6130
6131 if (NullKind == Expr::NPCK_NotNull)
6132 return false;
6133
David Blaikie1c7c8f72012-08-08 17:33:31 +00006134 if (NullKind == Expr::NPCK_ZeroExpression)
6135 return false;
6136
6137 if (NullKind == Expr::NPCK_ZeroLiteral) {
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00006138 // In this case, check to make sure that we got here from a "NULL"
6139 // string in the source code.
6140 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00006141 SourceLocation loc = NullExpr->getExprLoc();
6142 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00006143 return false;
6144 }
6145
Richard Smith89645bc2013-01-02 12:01:23 +00006146 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00006147 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6148 << NonPointerExpr->getType() << DiagType
6149 << NonPointerExpr->getSourceRange();
6150 return true;
6151}
6152
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006153/// \brief Return false if the condition expression is valid, true otherwise.
Sameer Sahasrabuddhee8d2aaf2015-02-04 06:38:18 +00006154static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006155 QualType CondTy = Cond->getType();
6156
Sameer Sahasrabuddhee8d2aaf2015-02-04 06:38:18 +00006157 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6158 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6159 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6160 << CondTy << Cond->getSourceRange();
6161 return true;
6162 }
6163
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006164 // C99 6.5.15p2
6165 if (CondTy->isScalarType()) return false;
6166
Sameer Sahasrabuddhee8d2aaf2015-02-04 06:38:18 +00006167 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6168 << CondTy << Cond->getSourceRange();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006169 return true;
6170}
6171
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006172/// \brief Handle when one or both operands are void type.
6173static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6174 ExprResult &RHS) {
6175 Expr *LHSExpr = LHS.get();
6176 Expr *RHSExpr = RHS.get();
6177
6178 if (!LHSExpr->getType()->isVoidType())
6179 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6180 << RHSExpr->getSourceRange();
6181 if (!RHSExpr->getType()->isVoidType())
6182 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6183 << LHSExpr->getSourceRange();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006184 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6185 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006186 return S.Context.VoidTy;
6187}
6188
6189/// \brief Return false if the NullExpr can be promoted to PointerTy,
6190/// true otherwise.
6191static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6192 QualType PointerTy) {
6193 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6194 !NullExpr.get()->isNullPointerConstant(S.Context,
6195 Expr::NPC_ValueDependentIsNull))
6196 return true;
6197
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006198 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006199 return false;
6200}
6201
6202/// \brief Checks compatibility between two pointers and return the resulting
6203/// type.
6204static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6205 ExprResult &RHS,
6206 SourceLocation Loc) {
6207 QualType LHSTy = LHS.get()->getType();
6208 QualType RHSTy = RHS.get()->getType();
6209
6210 if (S.Context.hasSameType(LHSTy, RHSTy)) {
6211 // Two identical pointers types are always compatible.
6212 return LHSTy;
6213 }
6214
6215 QualType lhptee, rhptee;
6216
6217 // Get the pointee types.
Fariborz Jahanian1edacec2013-06-07 16:07:38 +00006218 bool IsBlockPointer = false;
John McCall9320b872011-09-09 05:25:32 +00006219 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6220 lhptee = LHSBTy->getPointeeType();
6221 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanian1edacec2013-06-07 16:07:38 +00006222 IsBlockPointer = true;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006223 } else {
John McCall9320b872011-09-09 05:25:32 +00006224 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6225 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006226 }
6227
Eli Friedman57a75392012-04-05 22:30:04 +00006228 // C99 6.5.15p6: If both operands are pointers to compatible types or to
6229 // differently qualified versions of compatible types, the result type is
6230 // a pointer to an appropriately qualified version of the composite
6231 // type.
6232
6233 // Only CVR-qualifiers exist in the standard, and the differently-qualified
6234 // clause doesn't make sense for our extensions. E.g. address space 2 should
6235 // be incompatible with address space 3: they may live on different devices or
6236 // anything.
6237 Qualifiers lhQual = lhptee.getQualifiers();
6238 Qualifiers rhQual = rhptee.getQualifiers();
6239
6240 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6241 lhQual.removeCVRQualifiers();
6242 rhQual.removeCVRQualifiers();
6243
6244 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6245 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6246
Yaxun Liua1a87ad2016-04-12 19:43:36 +00006247 // For OpenCL:
6248 // 1. If LHS and RHS types match exactly and:
6249 // (a) AS match => use standard C rules, no bitcast or addrspacecast
6250 // (b) AS overlap => generate addrspacecast
6251 // (c) AS don't overlap => give an error
6252 // 2. if LHS and RHS types don't match:
6253 // (a) AS match => use standard C rules, generate bitcast
6254 // (b) AS overlap => generate addrspacecast instead of bitcast
6255 // (c) AS don't overlap => give an error
6256
6257 // For OpenCL, non-null composite type is returned only for cases 1a and 1b.
Eli Friedman57a75392012-04-05 22:30:04 +00006258 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6259
Yaxun Liua1a87ad2016-04-12 19:43:36 +00006260 // OpenCL cases 1c, 2a, 2b, and 2c.
Eli Friedman57a75392012-04-05 22:30:04 +00006261 if (CompositeTy.isNull()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006262 // In this situation, we assume void* type. No especially good
6263 // reason, but this is what gcc does, and we do have to pick
6264 // to get a consistent AST.
Yaxun Liua1a87ad2016-04-12 19:43:36 +00006265 QualType incompatTy;
6266 if (S.getLangOpts().OpenCL) {
6267 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6268 // spaces is disallowed.
6269 unsigned ResultAddrSpace;
6270 if (lhQual.isAddressSpaceSupersetOf(rhQual)) {
6271 // Cases 2a and 2b.
6272 ResultAddrSpace = lhQual.getAddressSpace();
6273 } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) {
6274 // Cases 2a and 2b.
6275 ResultAddrSpace = rhQual.getAddressSpace();
6276 } else {
6277 // Cases 1c and 2c.
6278 S.Diag(Loc,
6279 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6280 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6281 << RHS.get()->getSourceRange();
6282 return QualType();
6283 }
6284
6285 // Continue handling cases 2a and 2b.
6286 incompatTy = S.Context.getPointerType(
6287 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6288 LHS = S.ImpCastExprToType(LHS.get(), incompatTy,
6289 (lhQual.getAddressSpace() != ResultAddrSpace)
6290 ? CK_AddressSpaceConversion /* 2b */
6291 : CK_BitCast /* 2a */);
6292 RHS = S.ImpCastExprToType(RHS.get(), incompatTy,
6293 (rhQual.getAddressSpace() != ResultAddrSpace)
6294 ? CK_AddressSpaceConversion /* 2b */
6295 : CK_BitCast /* 2a */);
6296 } else {
6297 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6298 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6299 << RHS.get()->getSourceRange();
6300 incompatTy = S.Context.getPointerType(S.Context.VoidTy);
6301 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6302 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6303 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006304 return incompatTy;
6305 }
6306
6307 // The pointer types are compatible.
Eli Friedman57a75392012-04-05 22:30:04 +00006308 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
Yaxun Liua1a87ad2016-04-12 19:43:36 +00006309 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
Fariborz Jahanian1edacec2013-06-07 16:07:38 +00006310 if (IsBlockPointer)
Fariborz Jahanian44d23b82013-06-07 00:48:14 +00006311 ResultTy = S.Context.getBlockPointerType(ResultTy);
Yaxun Liua1a87ad2016-04-12 19:43:36 +00006312 else {
6313 // Cases 1a and 1b for OpenCL.
6314 auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace();
6315 LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace
6316 ? CK_BitCast /* 1a */
6317 : CK_AddressSpaceConversion /* 1b */;
6318 RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace
6319 ? CK_BitCast /* 1a */
6320 : CK_AddressSpaceConversion /* 1b */;
Fariborz Jahanian44d23b82013-06-07 00:48:14 +00006321 ResultTy = S.Context.getPointerType(ResultTy);
Yaxun Liua1a87ad2016-04-12 19:43:36 +00006322 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006323
Yaxun Liua1a87ad2016-04-12 19:43:36 +00006324 // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast
6325 // if the target type does not change.
6326 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6327 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
Eli Friedman57a75392012-04-05 22:30:04 +00006328 return ResultTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006329}
6330
6331/// \brief Return the resulting type when the operands are both block pointers.
6332static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6333 ExprResult &LHS,
6334 ExprResult &RHS,
6335 SourceLocation Loc) {
6336 QualType LHSTy = LHS.get()->getType();
6337 QualType RHSTy = RHS.get()->getType();
6338
6339 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6340 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6341 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006342 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6343 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006344 return destType;
6345 }
6346 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6347 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6348 << RHS.get()->getSourceRange();
6349 return QualType();
6350 }
6351
6352 // We have 2 block pointer types.
6353 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6354}
6355
6356/// \brief Return the resulting type when the operands are both pointers.
6357static QualType
6358checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6359 ExprResult &RHS,
6360 SourceLocation Loc) {
6361 // get the pointer types
6362 QualType LHSTy = LHS.get()->getType();
6363 QualType RHSTy = RHS.get()->getType();
6364
6365 // get the "pointed to" types
6366 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6367 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6368
6369 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6370 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6371 // Figure out necessary qualifiers (C99 6.5.15p6)
6372 QualType destPointee
6373 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6374 QualType destType = S.Context.getPointerType(destPointee);
6375 // Add qualifiers if necessary.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006376 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006377 // Promote to void*.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006378 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006379 return destType;
6380 }
6381 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6382 QualType destPointee
6383 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6384 QualType destType = S.Context.getPointerType(destPointee);
6385 // Add qualifiers if necessary.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006386 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006387 // Promote to void*.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006388 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006389 return destType;
6390 }
6391
6392 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6393}
6394
6395/// \brief Return false if the first expression is not an integer and the second
6396/// expression is not a pointer, true otherwise.
6397static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6398 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006399 bool IsIntFirstExpr) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006400 if (!PointerExpr->getType()->isPointerType() ||
6401 !Int.get()->getType()->isIntegerType())
6402 return false;
6403
Richard Trieuba63ce62011-09-09 01:45:06 +00006404 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6405 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006406
Richard Smith1b98ccc2014-07-19 01:39:17 +00006407 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006408 << Expr1->getType() << Expr2->getType()
6409 << Expr1->getSourceRange() << Expr2->getSourceRange();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006410 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006411 CK_IntegralToPointer);
6412 return true;
6413}
6414
Sameer Sahasrabuddhee8d2aaf2015-02-04 06:38:18 +00006415/// \brief Simple conversion between integer and floating point types.
6416///
6417/// Used when handling the OpenCL conditional operator where the
6418/// condition is a vector while the other operands are scalar.
6419///
6420/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6421/// types are either integer or floating type. Between the two
6422/// operands, the type with the higher rank is defined as the "result
6423/// type". The other operand needs to be promoted to the same type. No
6424/// other type promotion is allowed. We cannot use
6425/// UsualArithmeticConversions() for this purpose, since it always
6426/// promotes promotable types.
6427static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6428 ExprResult &RHS,
6429 SourceLocation QuestionLoc) {
6430 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6431 if (LHS.isInvalid())
6432 return QualType();
6433 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6434 if (RHS.isInvalid())
6435 return QualType();
6436
6437 // For conversion purposes, we ignore any qualifiers.
6438 // For example, "const float" and "float" are equivalent.
6439 QualType LHSType =
6440 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6441 QualType RHSType =
6442 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6443
6444 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6445 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6446 << LHSType << LHS.get()->getSourceRange();
6447 return QualType();
6448 }
6449
6450 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6451 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6452 << RHSType << RHS.get()->getSourceRange();
6453 return QualType();
6454 }
6455
6456 // If both types are identical, no conversion is needed.
6457 if (LHSType == RHSType)
6458 return LHSType;
6459
6460 // Now handle "real" floating types (i.e. float, double, long double).
6461 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6462 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6463 /*IsCompAssign = */ false);
6464
6465 // Finally, we have two differing integer types.
6466 return handleIntegerConversion<doIntegralCast, doIntegralCast>
6467 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6468}
6469
6470/// \brief Convert scalar operands to a vector that matches the
6471/// condition in length.
6472///
6473/// Used when handling the OpenCL conditional operator where the
6474/// condition is a vector while the other operands are scalar.
6475///
6476/// We first compute the "result type" for the scalar operands
6477/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6478/// into a vector of that type where the length matches the condition
6479/// vector type. s6.11.6 requires that the element types of the result
6480/// and the condition must have the same number of bits.
6481static QualType
6482OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6483 QualType CondTy, SourceLocation QuestionLoc) {
6484 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6485 if (ResTy.isNull()) return QualType();
6486
6487 const VectorType *CV = CondTy->getAs<VectorType>();
6488 assert(CV);
6489
6490 // Determine the vector result type
6491 unsigned NumElements = CV->getNumElements();
6492 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6493
6494 // Ensure that all types have the same number of bits
6495 if (S.Context.getTypeSize(CV->getElementType())
6496 != S.Context.getTypeSize(ResTy)) {
6497 // Since VectorTy is created internally, it does not pretty print
6498 // with an OpenCL name. Instead, we just print a description.
6499 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6500 SmallString<64> Str;
6501 llvm::raw_svector_ostream OS(Str);
6502 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6503 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6504 << CondTy << OS.str();
6505 return QualType();
6506 }
6507
6508 // Convert operands to the vector result type
6509 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6510 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6511
6512 return VectorTy;
6513}
6514
6515/// \brief Return false if this is a valid OpenCL condition vector
6516static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6517 SourceLocation QuestionLoc) {
6518 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6519 // integral type.
6520 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6521 assert(CondTy);
6522 QualType EleTy = CondTy->getElementType();
6523 if (EleTy->isIntegerType()) return false;
6524
6525 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6526 << Cond->getType() << Cond->getSourceRange();
6527 return true;
6528}
6529
6530/// \brief Return false if the vector condition type and the vector
6531/// result type are compatible.
6532///
6533/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6534/// number of elements, and their element types have the same number
6535/// of bits.
6536static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6537 SourceLocation QuestionLoc) {
6538 const VectorType *CV = CondTy->getAs<VectorType>();
6539 const VectorType *RV = VecResTy->getAs<VectorType>();
6540 assert(CV && RV);
6541
6542 if (CV->getNumElements() != RV->getNumElements()) {
6543 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6544 << CondTy << VecResTy;
6545 return true;
6546 }
6547
6548 QualType CVE = CV->getElementType();
6549 QualType RVE = RV->getElementType();
6550
6551 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6552 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6553 << CondTy << VecResTy;
6554 return true;
6555 }
6556
6557 return false;
6558}
6559
6560/// \brief Return the resulting type for the conditional operator in
6561/// OpenCL (aka "ternary selection operator", OpenCL v1.1
6562/// s6.3.i) when the condition is a vector type.
6563static QualType
6564OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6565 ExprResult &LHS, ExprResult &RHS,
6566 SourceLocation QuestionLoc) {
6567 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6568 if (Cond.isInvalid())
6569 return QualType();
6570 QualType CondTy = Cond.get()->getType();
6571
6572 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6573 return QualType();
6574
6575 // If either operand is a vector then find the vector type of the
6576 // result as specified in OpenCL v1.1 s6.3.i.
6577 if (LHS.get()->getType()->isVectorType() ||
6578 RHS.get()->getType()->isVectorType()) {
6579 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00006580 /*isCompAssign*/false,
6581 /*AllowBothBool*/true,
6582 /*AllowBoolConversions*/false);
Sameer Sahasrabuddhee8d2aaf2015-02-04 06:38:18 +00006583 if (VecResTy.isNull()) return QualType();
6584 // The result type must match the condition type as specified in
6585 // OpenCL v1.1 s6.11.6.
6586 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6587 return QualType();
6588 return VecResTy;
6589 }
6590
6591 // Both operands are scalar.
6592 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6593}
6594
Xiuli Pan89307aa2016-02-24 04:29:36 +00006595/// \brief Return true if the Expr is block type
6596static bool checkBlockType(Sema &S, const Expr *E) {
6597 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6598 QualType Ty = CE->getCallee()->getType();
6599 if (Ty->isBlockPointerType()) {
6600 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6601 return true;
6602 }
6603 }
6604 return false;
6605}
6606
Richard Trieud33e46e2011-09-06 20:06:39 +00006607/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6608/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00006609/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00006610QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6611 ExprResult &RHS, ExprValueKind &VK,
6612 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00006613 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00006614
Richard Trieud33e46e2011-09-06 20:06:39 +00006615 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6616 if (!LHSResult.isUsable()) return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006617 LHS = LHSResult;
Douglas Gregor0124e9b2010-11-09 21:07:58 +00006618
Richard Trieud33e46e2011-09-06 20:06:39 +00006619 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6620 if (!RHSResult.isUsable()) return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006621 RHS = RHSResult;
Douglas Gregor0124e9b2010-11-09 21:07:58 +00006622
Sebastian Redl1a99f442009-04-16 17:51:27 +00006623 // C++ is sufficiently different to merit its own checker.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006624 if (getLangOpts().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00006625 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00006626
6627 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00006628 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006629
Sameer Sahasrabuddhee8d2aaf2015-02-04 06:38:18 +00006630 // The OpenCL operator with a vector condition is sufficiently
6631 // different to merit its own checker.
6632 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6633 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6634
Jin-Gu Kang09c22132013-09-02 20:32:37 +00006635 // First, check the condition.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006636 Cond = UsualUnaryConversions(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00006637 if (Cond.isInvalid())
6638 return QualType();
Sameer Sahasrabuddhee8d2aaf2015-02-04 06:38:18 +00006639 if (checkCondition(*this, Cond.get(), QuestionLoc))
Jin-Gu Kang09c22132013-09-02 20:32:37 +00006640 return QualType();
6641
6642 // Now check the two expressions.
6643 if (LHS.get()->getType()->isVectorType() ||
6644 RHS.get()->getType()->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00006645 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6646 /*AllowBothBool*/true,
6647 /*AllowBoolConversions*/false);
Jin-Gu Kang09c22132013-09-02 20:32:37 +00006648
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006649 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
Eli Friedmane6d33952013-07-08 20:20:06 +00006650 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006651 return QualType();
6652
John Wiegley01296292011-04-08 18:41:53 +00006653 QualType LHSTy = LHS.get()->getType();
6654 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00006655
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006656 // Diagnose attempts to convert between __float128 and long double where
6657 // such conversions currently can't be handled.
6658 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6659 Diag(QuestionLoc,
6660 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6661 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6662 return QualType();
6663 }
6664
Xiuli Pan89307aa2016-02-24 04:29:36 +00006665 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6666 // selection operator (?:).
6667 if (getLangOpts().OpenCL &&
6668 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6669 return QualType();
6670 }
6671
Chris Lattnere2949f42008-01-06 22:42:25 +00006672 // If both operands have arithmetic type, do the usual arithmetic conversions
6673 // to find a common type: C99 6.5.15p3,5.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006674 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6675 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6676 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6677
6678 return ResTy;
6679 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006680
Chris Lattnere2949f42008-01-06 22:42:25 +00006681 // If both operands are the same structure or union type, the result is that
6682 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006683 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
6684 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00006685 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00006686 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00006687 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00006688 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00006689 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00006690 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006691
Chris Lattnere2949f42008-01-06 22:42:25 +00006692 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00006693 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00006694 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006695 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00006696 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006697
Steve Naroff039ad3c2008-01-08 01:11:38 +00006698 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6699 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006700 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6701 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006702
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006703 // All objective-c pointer type analysis is done here.
6704 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6705 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00006706 if (LHS.isInvalid() || RHS.isInvalid())
6707 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006708 if (!compositeType.isNull())
6709 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006710
6711
Steve Naroff05efa972009-07-01 14:36:47 +00006712 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006713 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6714 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6715 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006716
Steve Naroff05efa972009-07-01 14:36:47 +00006717 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006718 if (LHSTy->isPointerType() && RHSTy->isPointerType())
6719 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6720 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006721
John McCalle84af4e2010-11-13 01:35:44 +00006722 // GCC compatibility: soften pointer/integer mismatch. Note that
6723 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006724 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6725 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00006726 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006727 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6728 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00006729 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00006730
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00006731 // Emit a better diagnostic if one of the expressions is a null pointer
6732 // constant and the other is not a pointer type. In this case, the user most
6733 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00006734 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00006735 return QualType();
6736
Chris Lattnere2949f42008-01-06 22:42:25 +00006737 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00006738 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00006739 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6740 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00006741 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00006742}
6743
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006744/// FindCompositeObjCPointerType - Helper method to find composite type of
6745/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00006746QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006747 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00006748 QualType LHSTy = LHS.get()->getType();
6749 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006750
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006751 // Handle things like Class and struct objc_class*. Here we case the result
6752 // to the pseudo-builtin, because that will be implicitly cast back to the
6753 // redefinition type if an attempt is made to access its fields.
6754 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00006755 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006756 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006757 return LHSTy;
6758 }
6759 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00006760 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006761 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006762 return RHSTy;
6763 }
6764 // And the same for struct objc_object* / id
6765 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00006766 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006767 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006768 return LHSTy;
6769 }
6770 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00006771 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006772 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006773 return RHSTy;
6774 }
6775 // And the same for struct objc_selector* / SEL
6776 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00006777 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006778 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006779 return LHSTy;
6780 }
6781 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00006782 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006783 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006784 return RHSTy;
6785 }
6786 // Check constraints for Objective-C object pointers types.
6787 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006788
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006789 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6790 // Two identical object pointer types are always compatible.
6791 return LHSTy;
6792 }
John McCall9320b872011-09-09 05:25:32 +00006793 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6794 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006795 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006796
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006797 // If both operands are interfaces and either operand can be
6798 // assigned to the other, use that type as the composite
6799 // type. This allows
6800 // xxx ? (A*) a : (B*) b
6801 // where B is a subclass of A.
6802 //
6803 // Additionally, as for assignment, if either type is 'id'
6804 // allow silent coercion. Finally, if the types are
6805 // incompatible then make sure to use 'id' as the composite
6806 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006807
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006808 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6809 // It could return the composite type.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006810 if (!(compositeType =
6811 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6812 // Nothing more to do.
6813 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006814 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6815 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6816 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6817 } else if ((LHSTy->isObjCQualifiedIdType() ||
6818 RHSTy->isObjCQualifiedIdType()) &&
6819 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6820 // Need to handle "id<xx>" explicitly.
6821 // GCC allows qualified id and any Objective-C type to devolve to
6822 // id. Currently localizing to here until clear this should be
6823 // part of ObjCQualifiedIdTypesAreCompatible.
6824 compositeType = Context.getObjCIdType();
6825 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6826 compositeType = Context.getObjCIdType();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006827 } else {
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006828 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6829 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00006830 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006831 QualType incompatTy = Context.getObjCIdType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006832 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6833 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006834 return incompatTy;
6835 }
6836 // The object pointer types are compatible.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006837 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6838 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006839 return compositeType;
6840 }
6841 // Check Objective-C object pointer types and 'void *'
6842 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006843 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00006844 // ARC forbids the implicit conversion of object pointers to 'void *',
6845 // so these types are not compatible.
6846 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6847 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6848 LHS = RHS = true;
6849 return QualType();
6850 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006851 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6852 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6853 QualType destPointee
6854 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6855 QualType destType = Context.getPointerType(destPointee);
6856 // Add qualifiers if necessary.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006857 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006858 // Promote to void*.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006859 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006860 return destType;
6861 }
6862 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006863 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00006864 // ARC forbids the implicit conversion of object pointers to 'void *',
6865 // so these types are not compatible.
6866 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6867 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6868 LHS = RHS = true;
6869 return QualType();
6870 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006871 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6872 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6873 QualType destPointee
6874 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6875 QualType destType = Context.getPointerType(destPointee);
6876 // Add qualifiers if necessary.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006877 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006878 // Promote to void*.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006879 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006880 return destType;
6881 }
6882 return QualType();
6883}
6884
Chandler Carruthb00e8c02011-06-16 01:05:14 +00006885/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006886/// ParenRange in parentheses.
6887static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00006888 const PartialDiagnostic &Note,
6889 SourceRange ParenRange) {
Craig Topper07fa1762015-11-15 02:31:46 +00006890 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
Chandler Carruthb00e8c02011-06-16 01:05:14 +00006891 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6892 EndLoc.isValid()) {
6893 Self.Diag(Loc, Note)
6894 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6895 << FixItHint::CreateInsertion(EndLoc, ")");
6896 } else {
6897 // We can't display the parentheses, so just show the bare note.
6898 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006899 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006900}
6901
6902static bool IsArithmeticOp(BinaryOperatorKind Opc) {
Craig Topperb0dfa7a2015-12-13 05:41:37 +00006903 return BinaryOperator::isAdditiveOp(Opc) ||
6904 BinaryOperator::isMultiplicativeOp(Opc) ||
6905 BinaryOperator::isShiftOp(Opc);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006906}
6907
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006908/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6909/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00006910/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6911/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006912static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00006913 Expr **RHSExprs) {
Hans Wennborgbe207b32011-09-12 12:07:30 +00006914 // Don't strip parenthesis: we should not warn if E is in parenthesis.
6915 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006916 E = E->IgnoreConversionOperator();
Hans Wennborgbe207b32011-09-12 12:07:30 +00006917 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006918
6919 // Built-in binary operator.
6920 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6921 if (IsArithmeticOp(OP->getOpcode())) {
6922 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00006923 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006924 return true;
6925 }
6926 }
6927
6928 // Overloaded operator.
6929 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6930 if (Call->getNumArgs() != 2)
6931 return false;
6932
6933 // Make sure this is really a binary operator that is safe to pass into
6934 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6935 OverloadedOperatorKind OO = Call->getOperator();
Benjamin Kramer0345f9f2013-03-30 11:56:00 +00006936 if (OO < OO_Plus || OO > OO_Arrow ||
6937 OO == OO_PlusPlus || OO == OO_MinusMinus)
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006938 return false;
6939
6940 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6941 if (IsArithmeticOp(OpKind)) {
6942 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00006943 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006944 return true;
6945 }
6946 }
6947
6948 return false;
6949}
6950
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006951/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6952/// or is a logical expression such as (x==y) which has int type, but is
6953/// commonly interpreted as boolean.
6954static bool ExprLooksBoolean(Expr *E) {
6955 E = E->IgnoreParenImpCasts();
6956
6957 if (E->getType()->isBooleanType())
6958 return true;
6959 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
Craig Topperb0dfa7a2015-12-13 05:41:37 +00006960 return OP->isComparisonOp() || OP->isLogicalOp();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006961 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6962 return OP->getOpcode() == UO_LNot;
Hans Wennborgb60dfbe2015-01-22 22:11:56 +00006963 if (E->getType()->isPointerType())
6964 return true;
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006965
6966 return false;
6967}
6968
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006969/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6970/// and binary operator are mixed in a way that suggests the programmer assumed
6971/// the conditional operator has higher precedence, for example:
6972/// "int x = a + someBinaryCondition ? 1 : 2".
6973static void DiagnoseConditionalPrecedence(Sema &Self,
6974 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00006975 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00006976 Expr *LHSExpr,
6977 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006978 BinaryOperatorKind CondOpcode;
6979 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006980
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00006981 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006982 return;
6983 if (!ExprLooksBoolean(CondRHS))
6984 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006985
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006986 // The condition is an arithmetic binary expression, with a right-
6987 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006988
Chandler Carruthb00e8c02011-06-16 01:05:14 +00006989 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00006990 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006991 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006992
Chandler Carruthb00e8c02011-06-16 01:05:14 +00006993 SuggestParentheses(Self, OpLoc,
David Blaikiedac86fd2012-10-08 01:19:49 +00006994 Self.PDiag(diag::note_precedence_silence)
Chandler Carruthb00e8c02011-06-16 01:05:14 +00006995 << BinaryOperator::getOpcodeStr(CondOpcode),
6996 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00006997
6998 SuggestParentheses(Self, OpLoc,
6999 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00007000 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00007001}
7002
Steve Naroff83895f72007-09-16 03:34:24 +00007003/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00007004/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00007005ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00007006 SourceLocation ColonLoc,
7007 Expr *CondExpr, Expr *LHSExpr,
7008 Expr *RHSExpr) {
Kaelyn Takata05f40502015-01-27 18:26:18 +00007009 if (!getLangOpts().CPlusPlus) {
7010 // C cannot handle TypoExpr nodes in the condition because it
7011 // doesn't handle dependent types properly, so make sure any TypoExprs have
7012 // been dealt with before checking the operands.
7013 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
David Majnemer2eb74e22016-02-17 17:19:00 +00007014 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7015 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7016
7017 if (!CondResult.isUsable())
7018 return ExprError();
7019
7020 if (LHSExpr) {
7021 if (!LHSResult.isUsable())
7022 return ExprError();
7023 }
7024
7025 if (!RHSResult.isUsable())
7026 return ExprError();
7027
Kaelyn Takata05f40502015-01-27 18:26:18 +00007028 CondExpr = CondResult.get();
David Majnemer2eb74e22016-02-17 17:19:00 +00007029 LHSExpr = LHSResult.get();
7030 RHSExpr = RHSResult.get();
Kaelyn Takata05f40502015-01-27 18:26:18 +00007031 }
7032
Chris Lattner2ab40a62007-11-26 01:40:58 +00007033 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7034 // was the condition.
Craig Topperc3ec1492014-05-26 06:22:03 +00007035 OpaqueValueExpr *opaqueValue = nullptr;
7036 Expr *commonExpr = nullptr;
7037 if (!LHSExpr) {
John McCallc07a0c72011-02-17 10:25:35 +00007038 commonExpr = CondExpr;
Fariborz Jahanian3caab6c2013-05-17 16:29:36 +00007039 // Lower out placeholder types first. This is important so that we don't
7040 // try to capture a placeholder. This happens in few cases in C++; such
7041 // as Objective-C++'s dictionary subscripting syntax.
7042 if (commonExpr->hasPlaceholderType()) {
7043 ExprResult result = CheckPlaceholderExpr(commonExpr);
7044 if (!result.isUsable()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007045 commonExpr = result.get();
Fariborz Jahanian3caab6c2013-05-17 16:29:36 +00007046 }
John McCallc07a0c72011-02-17 10:25:35 +00007047 // We usually want to apply unary conversions *before* saving, except
7048 // in the special case of a C++ l-value conditional.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007049 if (!(getLangOpts().CPlusPlus
John McCallc07a0c72011-02-17 10:25:35 +00007050 && !commonExpr->isTypeDependent()
7051 && commonExpr->getValueKind() == RHSExpr->getValueKind()
7052 && commonExpr->isGLValue()
7053 && commonExpr->isOrdinaryOrBitFieldObject()
7054 && RHSExpr->isOrdinaryOrBitFieldObject()
7055 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00007056 ExprResult commonRes = UsualUnaryConversions(commonExpr);
7057 if (commonRes.isInvalid())
7058 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007059 commonExpr = commonRes.get();
John McCallc07a0c72011-02-17 10:25:35 +00007060 }
7061
7062 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7063 commonExpr->getType(),
7064 commonExpr->getValueKind(),
Douglas Gregor2d5aea02012-02-23 22:17:26 +00007065 commonExpr->getObjectKind(),
7066 commonExpr);
John McCallc07a0c72011-02-17 10:25:35 +00007067 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00007068 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00007069
John McCall7decc9e2010-11-18 06:31:45 +00007070 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00007071 ExprObjectKind OK = OK_Ordinary;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007072 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
John Wiegley01296292011-04-08 18:41:53 +00007073 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00007074 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00007075 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7076 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007077 return ExprError();
7078
Hans Wennborgcf9bac42011-06-03 18:00:36 +00007079 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7080 RHS.get());
7081
Richard Trieucbab79a2015-05-20 23:29:18 +00007082 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7083
John McCallc07a0c72011-02-17 10:25:35 +00007084 if (!commonExpr)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007085 return new (Context)
7086 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7087 RHS.get(), result, VK, OK);
John McCallc07a0c72011-02-17 10:25:35 +00007088
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007089 return new (Context) BinaryConditionalOperator(
7090 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7091 ColonLoc, result, VK, OK);
Chris Lattnere168f762006-11-10 05:29:30 +00007092}
7093
John McCallaba90822011-01-31 23:13:11 +00007094// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00007095// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00007096// routine is it effectively iqnores the qualifiers on the top level pointee.
7097// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7098// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00007099static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00007100checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7101 assert(LHSType.isCanonical() && "LHS not canonicalized!");
7102 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00007103
Steve Naroff1f4d7272007-05-11 04:00:31 +00007104 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00007105 const Type *lhptee, *rhptee;
7106 Qualifiers lhq, rhq;
Benjamin Kramercef536e2014-03-02 13:18:22 +00007107 std::tie(lhptee, lhq) =
7108 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7109 std::tie(rhptee, rhq) =
7110 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007111
John McCallaba90822011-01-31 23:13:11 +00007112 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007113
7114 // C99 6.5.16.1p1: This following citation is common to constraints
7115 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7116 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00007117
John McCall31168b02011-06-15 23:02:42 +00007118 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7119 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7120 lhq.compatiblyIncludesObjCLifetime(rhq)) {
7121 // Ignore lifetime for further calculation.
7122 lhq.removeObjCLifetime();
7123 rhq.removeObjCLifetime();
7124 }
7125
John McCall4fff8f62011-02-01 00:10:29 +00007126 if (!lhq.compatiblyIncludes(rhq)) {
7127 // Treat address-space mismatches as fatal. TODO: address subspaces
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00007128 if (!lhq.isAddressSpaceSupersetOf(rhq))
John McCall4fff8f62011-02-01 00:10:29 +00007129 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7130
John McCall31168b02011-06-15 23:02:42 +00007131 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00007132 // and from void*.
John McCall18ce25e2012-02-08 00:46:36 +00007133 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCall31168b02011-06-15 23:02:42 +00007134 .compatiblyIncludes(
John McCall18ce25e2012-02-08 00:46:36 +00007135 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall78535952011-03-26 02:56:45 +00007136 && (lhptee->isVoidType() || rhptee->isVoidType()))
7137 ; // keep old
7138
John McCall31168b02011-06-15 23:02:42 +00007139 // Treat lifetime mismatches as fatal.
7140 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7141 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7142
Andrey Bokhanko45d41322016-05-11 18:38:21 +00007143 // For GCC/MS compatibility, other qualifier mismatches are treated
John McCall4fff8f62011-02-01 00:10:29 +00007144 // as still compatible in C.
7145 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7146 }
Steve Naroff3f597292007-05-11 22:18:03 +00007147
Mike Stump4e1f26a2009-02-19 03:04:26 +00007148 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7149 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00007150 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00007151 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00007152 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00007153 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007154
Chris Lattner0a788432008-01-03 22:56:36 +00007155 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00007156 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00007157 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00007158 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007159
Chris Lattner0a788432008-01-03 22:56:36 +00007160 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00007161 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00007162 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00007163
7164 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00007165 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00007166 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00007167 }
John McCall4fff8f62011-02-01 00:10:29 +00007168
Mike Stump4e1f26a2009-02-19 03:04:26 +00007169 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00007170 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00007171 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7172 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00007173 // Check if the pointee types are compatible ignoring the sign.
7174 // We explicitly check for char so that we catch "char" vs
7175 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00007176 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00007177 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007178 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00007179 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007180
Chris Lattnerec3a1562009-10-17 20:33:28 +00007181 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00007182 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007183 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00007184 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00007185
John McCall4fff8f62011-02-01 00:10:29 +00007186 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00007187 // Types are compatible ignoring the sign. Qualifier incompatibility
7188 // takes priority over sign incompatibility because the sign
7189 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00007190 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00007191 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00007192
John McCallaba90822011-01-31 23:13:11 +00007193 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00007194 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007195
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00007196 // If we are a multi-level pointer, it's possible that our issue is simply
7197 // one of qualification - e.g. char ** -> const char ** is not allowed. If
7198 // the eventual target type is the same and the pointers have the same
7199 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00007200 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00007201 do {
John McCall4fff8f62011-02-01 00:10:29 +00007202 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7203 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00007204 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007205
John McCall4fff8f62011-02-01 00:10:29 +00007206 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00007207 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00007208 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007209
Eli Friedman80160bd2009-03-22 23:59:44 +00007210 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00007211 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00007212 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00007213 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian48c69102011-10-05 00:05:34 +00007214 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
7215 return Sema::IncompatiblePointer;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007216 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00007217}
7218
John McCallaba90822011-01-31 23:13:11 +00007219/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00007220/// block pointer types are compatible or whether a block and normal pointer
7221/// are compatible. It is more restrict than comparing two function pointer
7222// types.
John McCallaba90822011-01-31 23:13:11 +00007223static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00007224checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7225 QualType RHSType) {
7226 assert(LHSType.isCanonical() && "LHS not canonicalized!");
7227 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00007228
Steve Naroff081c7422008-09-04 15:10:53 +00007229 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007230
Steve Naroff081c7422008-09-04 15:10:53 +00007231 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00007232 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7233 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007234
John McCallaba90822011-01-31 23:13:11 +00007235 // In C++, the types have to match exactly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007236 if (S.getLangOpts().CPlusPlus)
John McCallaba90822011-01-31 23:13:11 +00007237 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007238
John McCallaba90822011-01-31 23:13:11 +00007239 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007240
Steve Naroff081c7422008-09-04 15:10:53 +00007241 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00007242 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
7243 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007244
Richard Trieua871b972011-09-06 20:21:22 +00007245 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00007246 return Sema::IncompatibleBlockPointer;
7247
Steve Naroff081c7422008-09-04 15:10:53 +00007248 return ConvTy;
7249}
7250
John McCallaba90822011-01-31 23:13:11 +00007251/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00007252/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00007253static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00007254checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7255 QualType RHSType) {
7256 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7257 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00007258
Richard Trieua871b972011-09-06 20:21:22 +00007259 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00007260 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00007261 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7262 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00007263 return Sema::IncompatiblePointer;
7264 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00007265 }
Richard Trieua871b972011-09-06 20:21:22 +00007266 if (RHSType->isObjCBuiltinType()) {
Richard Trieua871b972011-09-06 20:21:22 +00007267 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7268 !LHSType->isObjCQualifiedClassType())
Fariborz Jahaniand923eb02011-09-15 20:40:18 +00007269 return Sema::IncompatiblePointer;
John McCallaba90822011-01-31 23:13:11 +00007270 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00007271 }
Richard Trieua871b972011-09-06 20:21:22 +00007272 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7273 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007274
Fariborz Jahaniane74d47e2012-01-12 22:12:08 +00007275 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7276 // make an exception for id<P>
7277 !LHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00007278 return Sema::CompatiblePointerDiscardsQualifiers;
7279
Richard Trieua871b972011-09-06 20:21:22 +00007280 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00007281 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00007282 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00007283 return Sema::IncompatibleObjCQualifiedId;
7284 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00007285}
7286
John McCall29600e12010-11-16 02:32:08 +00007287Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00007288Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00007289 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00007290 // Fake up an opaque expression. We don't actually care about what
7291 // cast operations are required, so if CheckAssignmentConstraints
7292 // adds casts to this they'll be wasted, but fortunately that doesn't
7293 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00007294 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7295 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00007296 CastKind K = CK_Invalid;
7297
George Burgess IV45461812015-10-11 20:13:20 +00007298 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
John McCall29600e12010-11-16 02:32:08 +00007299}
7300
Mike Stump4e1f26a2009-02-19 03:04:26 +00007301/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7302/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00007303/// pointers. Here are some objectionable examples that GCC considers warnings:
7304///
7305/// int a, *pint;
7306/// short *pshort;
7307/// struct foo *pfoo;
7308///
7309/// pint = pshort; // warning: assignment from incompatible pointer type
7310/// a = pint; // warning: assignment makes integer from pointer without a cast
7311/// pint = a; // warning: assignment makes pointer from integer without a cast
7312/// pint = pfoo; // warning: assignment from incompatible pointer type
7313///
7314/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00007315/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00007316///
John McCall8cb679e2010-11-15 09:13:47 +00007317/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00007318Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00007319Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
George Burgess IV45461812015-10-11 20:13:20 +00007320 CastKind &Kind, bool ConvertRHS) {
Richard Trieude4958f2011-09-06 20:30:53 +00007321 QualType RHSType = RHS.get()->getType();
7322 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00007323
Chris Lattnera52c2f22008-01-04 23:18:45 +00007324 // Get canonical types. We're not formatting these types, just comparing
7325 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00007326 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7327 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00007328
John McCalle5255932011-01-31 22:28:28 +00007329 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00007330 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00007331 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00007332 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00007333 }
7334
Eli Friedman93ee5ca2012-06-16 02:19:17 +00007335 // If we have an atomic type, try a non-atomic assignment, then just add an
7336 // atomic qualification step.
David Chisnallfa35df62012-01-16 17:27:18 +00007337 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman93ee5ca2012-06-16 02:19:17 +00007338 Sema::AssignConvertType result =
7339 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7340 if (result != Compatible)
7341 return result;
George Burgess IV45461812015-10-11 20:13:20 +00007342 if (Kind != CK_NoOp && ConvertRHS)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007343 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
Eli Friedman93ee5ca2012-06-16 02:19:17 +00007344 Kind = CK_NonAtomicToAtomic;
7345 return Compatible;
David Chisnallfa35df62012-01-16 17:27:18 +00007346 }
7347
Douglas Gregor6b754842008-10-28 00:22:11 +00007348 // If the left-hand side is a reference type, then we are in a
7349 // (rare!) case where we've allowed the use of references in C,
7350 // e.g., as a parameter type in a built-in function. In this case,
7351 // just make sure that the type referenced is compatible with the
7352 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00007353 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00007354 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00007355 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7356 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00007357 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00007358 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00007359 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00007360 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00007361 }
John McCalle5255932011-01-31 22:28:28 +00007362
Nate Begemanbd956c42009-06-28 02:36:38 +00007363 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7364 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00007365 if (LHSType->isExtVectorType()) {
7366 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00007367 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00007368 if (RHSType->isArithmeticType()) {
George Burgess IVdf1ed002016-01-13 01:52:39 +00007369 // CK_VectorSplat does T -> vector T, so first cast to the element type.
7370 if (ConvertRHS)
7371 RHS = prepareVectorSplat(LHSType, RHS.get());
John McCall29600e12010-11-16 02:32:08 +00007372 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00007373 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00007374 }
Nate Begemanbd956c42009-06-28 02:36:38 +00007375 }
Mike Stump11289f42009-09-09 15:08:12 +00007376
John McCalle5255932011-01-31 22:28:28 +00007377 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00007378 if (LHSType->isVectorType() || RHSType->isVectorType()) {
7379 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00007380 // Allow assignments of an AltiVec vector type to an equivalent GCC
7381 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00007382 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00007383 Kind = CK_BitCast;
7384 return Compatible;
7385 }
7386
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007387 // If we are allowing lax vector conversions, and LHS and RHS are both
7388 // vectors, the total size only needs to be the same. This is a bitcast;
7389 // no bits are changed but the result type is different.
John McCall9b595db2014-02-04 23:58:19 +00007390 if (isLaxVectorConversion(RHSType, LHSType)) {
John McCall3065d042010-11-15 10:08:00 +00007391 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00007392 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00007393 }
Chris Lattner881a2122008-01-04 23:32:24 +00007394 }
7395 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007396 }
Eli Friedman3360d892008-05-30 18:07:22 +00007397
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007398 // Diagnose attempts to convert between __float128 and long double where
7399 // such conversions currently can't be handled.
7400 if (unsupportedTypeConversion(*this, LHSType, RHSType))
7401 return Incompatible;
7402
John McCalle5255932011-01-31 22:28:28 +00007403 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00007404 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007405 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
George Burgess IV45461812015-10-11 20:13:20 +00007406 if (ConvertRHS)
7407 Kind = PrepareScalarCast(RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00007408 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00007409 }
Eli Friedman3360d892008-05-30 18:07:22 +00007410
John McCalle5255932011-01-31 22:28:28 +00007411 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00007412 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00007413 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00007414 if (isa<PointerType>(RHSType)) {
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00007415 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7416 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7417 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00007418 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00007419 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007420
John McCalle5255932011-01-31 22:28:28 +00007421 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00007422 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00007423 Kind = CK_IntegralToPointer; // FIXME: null?
7424 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007425 }
John McCalle5255932011-01-31 22:28:28 +00007426
7427 // C pointers are not compatible with ObjC object pointers,
7428 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00007429 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00007430 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00007431 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall9320b872011-09-09 05:25:32 +00007432 Kind = CK_BitCast;
John McCalle5255932011-01-31 22:28:28 +00007433 return Compatible;
7434 }
7435
7436 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00007437 if (RHSType->isObjCClassType() &&
7438 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00007439 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00007440 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00007441 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00007442 }
Douglas Gregor486b74e2011-09-27 16:10:05 +00007443
John McCalle5255932011-01-31 22:28:28 +00007444 Kind = CK_BitCast;
7445 return IncompatiblePointer;
7446 }
7447
7448 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00007449 if (RHSType->getAs<BlockPointerType>()) {
7450 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00007451 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00007452 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00007453 }
Steve Naroff32d072c2008-09-29 18:10:17 +00007454 }
John McCalle5255932011-01-31 22:28:28 +00007455
Steve Naroff081c7422008-09-04 15:10:53 +00007456 return Incompatible;
7457 }
7458
John McCalle5255932011-01-31 22:28:28 +00007459 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00007460 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00007461 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00007462 if (RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00007463 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00007464 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00007465 }
7466
7467 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00007468 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00007469 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00007470 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00007471 }
7472
John McCalle5255932011-01-31 22:28:28 +00007473 // id -> T^
David Blaikiebbafb8a2012-03-11 07:00:24 +00007474 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00007475 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00007476 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00007477 }
Steve Naroff32d072c2008-09-29 18:10:17 +00007478
John McCalle5255932011-01-31 22:28:28 +00007479 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00007480 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00007481 if (RHSPT->getPointeeType()->isVoidType()) {
7482 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00007483 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00007484 }
John McCall8cb679e2010-11-15 09:13:47 +00007485
Chris Lattnera52c2f22008-01-04 23:18:45 +00007486 return Incompatible;
7487 }
7488
John McCalle5255932011-01-31 22:28:28 +00007489 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00007490 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00007491 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00007492 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00007493 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00007494 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00007495 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikiebbafb8a2012-03-11 07:00:24 +00007496 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00007497 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00007498 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00007499 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00007500 return result;
John McCalle5255932011-01-31 22:28:28 +00007501 }
7502
7503 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00007504 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00007505 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00007506 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00007507 }
7508
John McCalle5255932011-01-31 22:28:28 +00007509 // In general, C pointers are not compatible with ObjC object pointers,
7510 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00007511 if (isa<PointerType>(RHSType)) {
John McCall9320b872011-09-09 05:25:32 +00007512 Kind = CK_CPointerToObjCPointerCast;
7513
John McCalle5255932011-01-31 22:28:28 +00007514 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00007515 if (RHSType->isVoidPointerType()) {
Steve Naroffaccc4882009-07-20 17:56:53 +00007516 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00007517 }
7518
7519 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00007520 if (LHSType->isObjCClassType() &&
7521 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00007522 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00007523 return Compatible;
7524 }
7525
Steve Naroffaccc4882009-07-20 17:56:53 +00007526 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007527 }
John McCalle5255932011-01-31 22:28:28 +00007528
Fariborz Jahanian7ea91b22014-06-09 21:42:01 +00007529 // Only under strict condition T^ is compatible with an Objective-C pointer.
Douglas Gregore9d95f12015-07-07 03:57:35 +00007530 if (RHSType->isBlockPointerType() &&
7531 LHSType->isBlockCompatibleObjCPointerType(Context)) {
George Burgess IV45461812015-10-11 20:13:20 +00007532 if (ConvertRHS)
7533 maybeExtendBlockObject(RHS);
John McCall9320b872011-09-09 05:25:32 +00007534 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007535 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00007536 }
7537
Steve Naroff7cae42b2009-07-10 23:34:53 +00007538 return Incompatible;
7539 }
John McCalle5255932011-01-31 22:28:28 +00007540
7541 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00007542 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00007543 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00007544 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00007545 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00007546 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00007547 }
Eli Friedman3360d892008-05-30 18:07:22 +00007548
John McCalle5255932011-01-31 22:28:28 +00007549 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00007550 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00007551 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00007552 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00007553 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007554
Chris Lattnera52c2f22008-01-04 23:18:45 +00007555 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00007556 }
John McCalle5255932011-01-31 22:28:28 +00007557
7558 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00007559 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00007560 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00007561 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00007562 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007563 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00007564 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007565
John McCalle5255932011-01-31 22:28:28 +00007566 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00007567 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00007568 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007569 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00007570 }
7571
Steve Naroff7cae42b2009-07-10 23:34:53 +00007572 return Incompatible;
7573 }
Eli Friedman3360d892008-05-30 18:07:22 +00007574
John McCalle5255932011-01-31 22:28:28 +00007575 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00007576 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7577 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00007578 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00007579 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00007580 }
Bill Wendling216423b2007-05-30 06:30:29 +00007581 }
John McCalle5255932011-01-31 22:28:28 +00007582
Steve Naroff98cf3e92007-06-06 18:38:38 +00007583 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00007584}
7585
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007586/// \brief Constructs a transparent union from an expression that is
7587/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00007588static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7589 ExprResult &EResult, QualType UnionType,
7590 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007591 // Build an initializer list that designates the appropriate member
7592 // of the transparent union.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007593 Expr *E = EResult.get();
Ted Kremenekac034612010-04-13 23:39:13 +00007594 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00007595 E, SourceLocation());
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007596 Initializer->setType(UnionType);
7597 Initializer->setInitializedFieldInUnion(Field);
7598
7599 // Build a compound literal constructing a value of the transparent
7600 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00007601 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007602 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7603 VK_RValue, Initializer, false);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007604}
7605
7606Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00007607Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00007608 ExprResult &RHS) {
7609 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007610
Mike Stump11289f42009-09-09 15:08:12 +00007611 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007612 // transparent_union GCC extension.
7613 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00007614 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007615 return Incompatible;
7616
7617 // The field to initialize within the transparent union.
7618 RecordDecl *UD = UT->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00007619 FieldDecl *InitField = nullptr;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007620 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007621 for (auto *it : UD->fields()) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007622 if (it->getType()->isPointerType()) {
7623 // If the transparent union contains a pointer type, we allow:
7624 // 1) void pointer
7625 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00007626 if (RHSType->isPointerType())
John McCall9320b872011-09-09 05:25:32 +00007627 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007628 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007629 InitField = it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007630 break;
7631 }
Mike Stump11289f42009-09-09 15:08:12 +00007632
Richard Trieueb299142011-09-06 20:40:12 +00007633 if (RHS.get()->isNullPointerConstant(Context,
7634 Expr::NPC_ValueDependentIsNull)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007635 RHS = ImpCastExprToType(RHS.get(), it->getType(),
Richard Trieueb299142011-09-06 20:40:12 +00007636 CK_NullToPointer);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007637 InitField = it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007638 break;
7639 }
7640 }
7641
John McCall8cb679e2010-11-15 09:13:47 +00007642 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00007643 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007644 == Compatible) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007645 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007646 InitField = it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007647 break;
7648 }
7649 }
7650
7651 if (!InitField)
7652 return Incompatible;
7653
Richard Trieueb299142011-09-06 20:40:12 +00007654 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007655 return Compatible;
7656}
7657
Chris Lattner9bad62c2008-01-04 18:04:52 +00007658Sema::AssignConvertType
George Burgess IV45461812015-10-11 20:13:20 +00007659Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
Fariborz Jahanian25eef192013-07-31 21:40:51 +00007660 bool Diagnose,
George Burgess IV45461812015-10-11 20:13:20 +00007661 bool DiagnoseCFAudited,
7662 bool ConvertRHS) {
7663 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7664 // we can't avoid *all* modifications at the moment, so we need some somewhere
7665 // to put the updated value.
7666 ExprResult LocalRHS = CallerRHS;
7667 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7668
David Blaikiebbafb8a2012-03-11 07:00:24 +00007669 if (getLangOpts().CPlusPlus) {
Eli Friedman0dfb8892011-10-06 23:00:33 +00007670 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00007671 // C++ 5.17p3: If the left operand is not of class type, the
7672 // expression is implicitly converted (C++ 4) to the
7673 // cv-unqualified type of the left operand.
Sebastian Redlcc152642011-10-16 18:19:06 +00007674 ExprResult Res;
7675 if (Diagnose) {
7676 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7677 AA_Assigning);
7678 } else {
7679 ImplicitConversionSequence ICS =
7680 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7681 /*SuppressUserConversions=*/false,
7682 /*AllowExplicit=*/false,
7683 /*InOverloadResolution=*/false,
7684 /*CStyle=*/false,
7685 /*AllowObjCWritebackConversion=*/false);
7686 if (ICS.isFailure())
7687 return Incompatible;
7688 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7689 ICS, AA_Assigning);
7690 }
John Wiegley01296292011-04-08 18:41:53 +00007691 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00007692 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00007693 Sema::AssignConvertType result = Compatible;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007694 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieueb299142011-09-06 20:40:12 +00007695 !CheckObjCARCUnavailableWeakConversion(LHSType,
7696 RHS.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00007697 result = IncompatibleObjCWeakRef;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007698 RHS = Res;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00007699 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00007700 }
7701
7702 // FIXME: Currently, we fall through and treat C++ classes like C
7703 // structures.
Eli Friedman0dfb8892011-10-06 23:00:33 +00007704 // FIXME: We also fall through for atomics; not sure what should
7705 // happen there, though.
George Burgess IV5f21c712015-10-12 19:57:04 +00007706 } else if (RHS.get()->getType() == Context.OverloadTy) {
7707 // As a set of extensions to C, we support overloading on functions. These
7708 // functions need to be resolved here.
7709 DeclAccessPair DAP;
7710 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7711 RHS.get(), LHSType, /*Complain=*/false, DAP))
7712 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7713 else
7714 return Incompatible;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007715 }
Douglas Gregor9a657932008-10-21 23:43:52 +00007716
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00007717 // C99 6.5.16.1p1: the left operand is a pointer and the right is
7718 // a null pointer constant.
Richard Smithe934d7c2013-11-21 01:53:02 +00007719 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7720 LHSType->isBlockPointerType()) &&
7721 RHS.get()->isNullPointerConstant(Context,
7722 Expr::NPC_ValueDependentIsNull)) {
George Burgess IV60bc9722016-01-13 23:36:34 +00007723 if (Diagnose || ConvertRHS) {
7724 CastKind Kind;
7725 CXXCastPath Path;
7726 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7727 /*IgnoreBaseAccess=*/false, Diagnose);
7728 if (ConvertRHS)
7729 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7730 }
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00007731 return Compatible;
7732 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007733
Chris Lattnere6dcd502007-10-16 02:55:40 +00007734 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007735 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00007736 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00007737 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00007738 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00007739 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00007740 if (!LHSType->isReferenceType()) {
George Burgess IV45461812015-10-11 20:13:20 +00007741 // FIXME: We potentially allocate here even if ConvertRHS is false.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007742 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
Richard Trieueb299142011-09-06 20:40:12 +00007743 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007744 return Incompatible;
7745 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00007746
Fariborz Jahaniana57d91c22014-07-25 19:45:01 +00007747 Expr *PRE = RHS.get()->IgnoreParenCasts();
George Burgess IV60bc9722016-01-13 23:36:34 +00007748 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7749 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
Fariborz Jahaniana57d91c22014-07-25 19:45:01 +00007750 if (PDecl && !PDecl->hasDefinition()) {
7751 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7752 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7753 }
7754 }
7755
John McCall8cb679e2010-11-15 09:13:47 +00007756 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007757 Sema::AssignConvertType result =
George Burgess IV45461812015-10-11 20:13:20 +00007758 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007759
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00007760 // C99 6.5.16.1p2: The value of the right operand is converted to the
7761 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00007762 // CheckAssignmentConstraints allows the left-hand side to be a reference,
7763 // so that we can use references in built-in functions even in C.
7764 // The getNonReferenceType() call makes sure that the resulting expression
7765 // does not have reference type.
Fariborz Jahanian374089e2013-07-31 17:12:26 +00007766 if (result != Incompatible && RHS.get()->getType() != LHSType) {
7767 QualType Ty = LHSType.getNonLValueExprType(Context);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007768 Expr *E = RHS.get();
Bob Wilsonf5c53b82016-02-13 01:41:41 +00007769
7770 // Check for various Objective-C errors. If we are not reporting
7771 // diagnostics and just checking for errors, e.g., during overload
7772 // resolution, return Incompatible to indicate the failure.
7773 if (getLangOpts().ObjCAutoRefCount &&
7774 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7775 Diagnose, DiagnoseCFAudited) != ACR_okay) {
7776 if (!Diagnose)
7777 return Incompatible;
7778 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00007779 if (getLangOpts().ObjC1 &&
George Burgess IV60bc9722016-01-13 23:36:34 +00007780 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7781 E->getType(), E, Diagnose) ||
7782 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
Bob Wilsonf5c53b82016-02-13 01:41:41 +00007783 if (!Diagnose)
7784 return Incompatible;
7785 // Replace the expression with a corrected version and continue so we
7786 // can find further errors.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007787 RHS = E;
Fariborz Jahanian381edf52013-12-16 22:54:37 +00007788 return Compatible;
7789 }
7790
George Burgess IV45461812015-10-11 20:13:20 +00007791 if (ConvertRHS)
7792 RHS = ImpCastExprToType(E, Ty, Kind);
Fariborz Jahanian374089e2013-07-31 17:12:26 +00007793 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00007794 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007795}
7796
Richard Trieueb299142011-09-06 20:40:12 +00007797QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7798 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007799 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00007800 << LHS.get()->getType() << RHS.get()->getType()
7801 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00007802 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00007803}
7804
Stephen Canon3ba640d2014-04-03 10:33:25 +00007805/// Try to convert a value of non-vector type to a vector type by converting
7806/// the type to the element type of the vector and then performing a splat.
7807/// If the language is OpenCL, we only use conversions that promote scalar
7808/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7809/// for float->int.
John McCall9b595db2014-02-04 23:58:19 +00007810///
7811/// \param scalar - if non-null, actually perform the conversions
7812/// \return true if the operation fails (but without diagnosing the failure)
Stephen Canon3ba640d2014-04-03 10:33:25 +00007813static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
John McCall9b595db2014-02-04 23:58:19 +00007814 QualType scalarTy,
7815 QualType vectorEltTy,
7816 QualType vectorTy) {
7817 // The conversion to apply to the scalar before splatting it,
7818 // if necessary.
7819 CastKind scalarCast = CK_Invalid;
Stephen Canon3ba640d2014-04-03 10:33:25 +00007820
John McCall9b595db2014-02-04 23:58:19 +00007821 if (vectorEltTy->isIntegralType(S.Context)) {
Stephen Canon3ba640d2014-04-03 10:33:25 +00007822 if (!scalarTy->isIntegralType(S.Context))
7823 return true;
7824 if (S.getLangOpts().OpenCL &&
7825 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
7826 return true;
7827 scalarCast = CK_IntegralCast;
John McCall9b595db2014-02-04 23:58:19 +00007828 } else if (vectorEltTy->isRealFloatingType()) {
7829 if (scalarTy->isRealFloatingType()) {
Stephen Canon3ba640d2014-04-03 10:33:25 +00007830 if (S.getLangOpts().OpenCL &&
7831 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
7832 return true;
7833 scalarCast = CK_FloatingCast;
John McCall9b595db2014-02-04 23:58:19 +00007834 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00007835 else if (scalarTy->isIntegralType(S.Context))
7836 scalarCast = CK_IntegralToFloating;
7837 else
7838 return true;
John McCall9b595db2014-02-04 23:58:19 +00007839 } else {
7840 return true;
7841 }
7842
7843 // Adjust scalar if desired.
7844 if (scalar) {
7845 if (scalarCast != CK_Invalid)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007846 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
7847 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
John McCall9b595db2014-02-04 23:58:19 +00007848 }
7849 return false;
7850}
7851
Richard Trieu859d23f2011-09-06 21:01:04 +00007852QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00007853 SourceLocation Loc, bool IsCompAssign,
7854 bool AllowBothBool,
7855 bool AllowBoolConversions) {
Richard Smith508ebf32011-10-28 03:31:48 +00007856 if (!IsCompAssign) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007857 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
Richard Smith508ebf32011-10-28 03:31:48 +00007858 if (LHS.isInvalid())
7859 return QualType();
7860 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007861 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
Richard Smith508ebf32011-10-28 03:31:48 +00007862 if (RHS.isInvalid())
7863 return QualType();
7864
Mike Stump4e1f26a2009-02-19 03:04:26 +00007865 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00007866 // For example, "const float" and "float" are equivalent.
John McCall9b595db2014-02-04 23:58:19 +00007867 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
7868 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007869
John McCall9b595db2014-02-04 23:58:19 +00007870 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
7871 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
7872 assert(LHSVecType || RHSVecType);
7873
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00007874 // AltiVec-style "vector bool op vector bool" combinations are allowed
7875 // for some operators but not others.
7876 if (!AllowBothBool &&
7877 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
7878 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
7879 return InvalidOperands(Loc, LHS, RHS);
7880
7881 // If the vector types are identical, return.
7882 if (Context.hasSameType(LHSType, RHSType))
7883 return LHSType;
7884
John McCall9b595db2014-02-04 23:58:19 +00007885 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
7886 if (LHSVecType && RHSVecType &&
Richard Trieu859d23f2011-09-06 21:01:04 +00007887 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
John McCall9b595db2014-02-04 23:58:19 +00007888 if (isa<ExtVectorType>(LHSVecType)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007889 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
Richard Trieu859d23f2011-09-06 21:01:04 +00007890 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00007891 }
7892
Richard Trieuba63ce62011-09-09 01:45:06 +00007893 if (!IsCompAssign)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007894 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
Richard Trieu859d23f2011-09-06 21:01:04 +00007895 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007896 }
7897
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00007898 // AllowBoolConversions says that bool and non-bool AltiVec vectors
7899 // can be mixed, with the result being the non-bool type. The non-bool
7900 // operand must have integer element type.
7901 if (AllowBoolConversions && LHSVecType && RHSVecType &&
7902 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
7903 (Context.getTypeSize(LHSVecType->getElementType()) ==
7904 Context.getTypeSize(RHSVecType->getElementType()))) {
7905 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
7906 LHSVecType->getElementType()->isIntegerType() &&
7907 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
7908 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
7909 return LHSType;
7910 }
7911 if (!IsCompAssign &&
7912 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
7913 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
7914 RHSVecType->getElementType()->isIntegerType()) {
7915 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
7916 return RHSType;
7917 }
7918 }
7919
Stephen Canon3ba640d2014-04-03 10:33:25 +00007920 // If there's an ext-vector type and a scalar, try to convert the scalar to
7921 // the vector element type and splat.
7922 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
7923 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
7924 LHSVecType->getElementType(), LHSType))
7925 return LHSType;
7926 }
7927 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007928 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
7929 LHSType, RHSVecType->getElementType(),
7930 RHSType))
Stephen Canon3ba640d2014-04-03 10:33:25 +00007931 return RHSType;
7932 }
7933
Reid Klecknere1a16462016-04-14 21:03:38 +00007934 // If we're allowing lax vector conversions, only the total (data) size needs
7935 // to be the same. If one of the types is scalar, the result is always the
7936 // vector type. Don't allow this if the scalar operand is an lvalue.
7937 QualType VecType = LHSVecType ? LHSType : RHSType;
7938 QualType ScalarType = LHSVecType ? RHSType : LHSType;
7939 ExprResult *ScalarExpr = LHSVecType ? &RHS : &LHS;
7940 if (isLaxVectorConversion(ScalarType, VecType) &&
7941 !ScalarExpr->get()->isLValue()) {
7942 *ScalarExpr = ImpCastExprToType(ScalarExpr->get(), VecType, CK_BitCast);
7943 return VecType;
Eli Friedman1408bc92011-06-23 18:10:35 +00007944 }
7945
John McCall9b595db2014-02-04 23:58:19 +00007946 // Okay, the expression is invalid.
7947
7948 // If there's a non-vector, non-real operand, diagnose that.
7949 if ((!RHSVecType && !RHSType->isRealType()) ||
7950 (!LHSVecType && !LHSType->isRealType())) {
Argyrios Kyrtzidisd07dcdb2014-01-07 07:59:31 +00007951 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
John McCall9b595db2014-02-04 23:58:19 +00007952 << LHSType << RHSType
7953 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Argyrios Kyrtzidisd07dcdb2014-01-07 07:59:31 +00007954 return QualType();
7955 }
7956
Alexey Baderf961e752015-08-30 18:06:39 +00007957 // OpenCL V1.1 6.2.6.p1:
7958 // If the operands are of more than one vector type, then an error shall
7959 // occur. Implicit conversions between vector types are not permitted, per
7960 // section 6.2.1.
7961 if (getLangOpts().OpenCL &&
7962 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
7963 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
7964 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
7965 << RHSType;
7966 return QualType();
7967 }
7968
John McCall9b595db2014-02-04 23:58:19 +00007969 // Otherwise, use the generic diagnostic.
Chris Lattner377d1f82008-11-18 22:52:51 +00007970 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John McCall9b595db2014-02-04 23:58:19 +00007971 << LHSType << RHSType
Richard Trieu859d23f2011-09-06 21:01:04 +00007972 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00007973 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00007974}
7975
Richard Trieuf8916e12011-09-16 00:53:10 +00007976// checkArithmeticNull - Detect when a NULL constant is used improperly in an
7977// expression. These are mainly cases where the null pointer is used as an
7978// integer instead of a pointer.
7979static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
7980 SourceLocation Loc, bool IsCompare) {
7981 // The canonical way to check for a GNU null is with isNullPointerConstant,
7982 // but we use a bit of a hack here for speed; this is a relatively
7983 // hot path, and isNullPointerConstant is slow.
7984 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
7985 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
7986
7987 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
7988
7989 // Avoid analyzing cases where the result will either be invalid (and
7990 // diagnosed as such) or entirely valid and not something to warn about.
7991 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
7992 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
7993 return;
7994
7995 // Comparison operations would not make sense with a null pointer no matter
7996 // what the other expression is.
7997 if (!IsCompare) {
7998 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
7999 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8000 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8001 return;
8002 }
8003
8004 // The rest of the operations only make sense with a null pointer
8005 // if the other expression is a pointer.
8006 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8007 NonNullType->canDecayToPointerType())
8008 return;
8009
8010 S.Diag(Loc, diag::warn_null_in_comparison_operation)
8011 << LHSNull /* LHS is NULL */ << NonNullType
8012 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8013}
8014
Davide Italianof76da1d2015-08-01 10:13:39 +00008015static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8016 ExprResult &RHS,
8017 SourceLocation Loc, bool IsDiv) {
8018 // Check for division/remainder by zero.
Davide Italianof76da1d2015-08-01 10:13:39 +00008019 llvm::APSInt RHSValue;
8020 if (!RHS.get()->isValueDependent() &&
8021 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8022 S.DiagRuntimeBehavior(Loc, RHS.get(),
Craig Topperda7b27f2015-11-17 05:40:09 +00008023 S.PDiag(diag::warn_remainder_division_by_zero)
8024 << IsDiv << RHS.get()->getSourceRange());
Davide Italianof76da1d2015-08-01 10:13:39 +00008025}
8026
Richard Trieu859d23f2011-09-06 21:01:04 +00008027QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00008028 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008029 bool IsCompAssign, bool IsDiv) {
Richard Trieuf8916e12011-09-16 00:53:10 +00008030 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8031
Richard Trieu859d23f2011-09-06 21:01:04 +00008032 if (LHS.get()->getType()->isVectorType() ||
8033 RHS.get()->getType()->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00008034 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8035 /*AllowBothBool*/getLangOpts().AltiVec,
8036 /*AllowBoolConversions*/false);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008037
Richard Trieuba63ce62011-09-09 01:45:06 +00008038 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00008039 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00008040 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00008041
David Chisnallfa35df62012-01-16 17:27:18 +00008042
Eli Friedman93ee5ca2012-06-16 02:19:17 +00008043 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu859d23f2011-09-06 21:01:04 +00008044 return InvalidOperands(Loc, LHS, RHS);
Davide Italianof76da1d2015-08-01 10:13:39 +00008045 if (IsDiv)
8046 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
Chris Lattnerfaa54172010-01-12 21:23:57 +00008047 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00008048}
8049
Chris Lattnerfaa54172010-01-12 21:23:57 +00008050QualType Sema::CheckRemainderOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00008051 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00008052 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8053
Richard Trieu859d23f2011-09-06 21:01:04 +00008054 if (LHS.get()->getType()->isVectorType() ||
8055 RHS.get()->getType()->isVectorType()) {
8056 if (LHS.get()->getType()->hasIntegerRepresentation() &&
8057 RHS.get()->getType()->hasIntegerRepresentation())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00008058 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8059 /*AllowBothBool*/getLangOpts().AltiVec,
8060 /*AllowBoolConversions*/false);
Richard Trieu859d23f2011-09-06 21:01:04 +00008061 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00008062 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00008063
Richard Trieuba63ce62011-09-09 01:45:06 +00008064 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00008065 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00008066 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00008067
Eli Friedman93ee5ca2012-06-16 02:19:17 +00008068 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu859d23f2011-09-06 21:01:04 +00008069 return InvalidOperands(Loc, LHS, RHS);
Davide Italianof76da1d2015-08-01 10:13:39 +00008070 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
Chris Lattnerfaa54172010-01-12 21:23:57 +00008071 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008072}
8073
Chandler Carruthc9332212011-06-27 08:02:19 +00008074/// \brief Diagnose invalid arithmetic on two void pointers.
8075static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00008076 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008077 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00008078 ? diag::err_typecheck_pointer_arith_void_type
8079 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00008080 << 1 /* two pointers */ << LHSExpr->getSourceRange()
8081 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00008082}
8083
8084/// \brief Diagnose invalid arithmetic on a void pointer.
8085static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8086 Expr *Pointer) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008087 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00008088 ? diag::err_typecheck_pointer_arith_void_type
8089 : diag::ext_gnu_void_ptr)
8090 << 0 /* one pointer */ << Pointer->getSourceRange();
8091}
8092
8093/// \brief Diagnose invalid arithmetic on two function pointers.
8094static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8095 Expr *LHS, Expr *RHS) {
8096 assert(LHS->getType()->isAnyPointerType());
8097 assert(RHS->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008098 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00008099 ? diag::err_typecheck_pointer_arith_function_type
8100 : diag::ext_gnu_ptr_func_arith)
8101 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8102 // We only show the second type if it differs from the first.
8103 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8104 RHS->getType())
8105 << RHS->getType()->getPointeeType()
8106 << LHS->getSourceRange() << RHS->getSourceRange();
8107}
8108
8109/// \brief Diagnose invalid arithmetic on a function pointer.
8110static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8111 Expr *Pointer) {
8112 assert(Pointer->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008113 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00008114 ? diag::err_typecheck_pointer_arith_function_type
8115 : diag::ext_gnu_ptr_func_arith)
8116 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8117 << 0 /* one pointer, so only one type */
8118 << Pointer->getSourceRange();
8119}
8120
Richard Trieu993f3ab2011-09-12 18:08:02 +00008121/// \brief Emit error if Operand is incomplete pointer type
Richard Trieuaba22802011-09-02 02:15:37 +00008122///
8123/// \returns True if pointer has incomplete type
8124static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8125 Expr *Operand) {
David Majnemercf7d1642015-02-12 21:07:34 +00008126 QualType ResType = Operand->getType();
8127 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8128 ResType = ResAtomicType->getValueType();
8129
8130 assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8131 QualType PointeeTy = ResType->getPointeeType();
John McCallf2538342012-07-31 05:14:30 +00008132 return S.RequireCompleteType(Loc, PointeeTy,
8133 diag::err_typecheck_arithmetic_incomplete_type,
8134 PointeeTy, Operand->getSourceRange());
Richard Trieuaba22802011-09-02 02:15:37 +00008135}
8136
Chandler Carruthc9332212011-06-27 08:02:19 +00008137/// \brief Check the validity of an arithmetic pointer operand.
8138///
8139/// If the operand has pointer type, this code will check for pointer types
8140/// which are invalid in arithmetic operations. These will be diagnosed
8141/// appropriately, including whether or not the use is supported as an
8142/// extension.
8143///
8144/// \returns True when the operand is valid to use (even if as an extension).
8145static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8146 Expr *Operand) {
David Majnemercf7d1642015-02-12 21:07:34 +00008147 QualType ResType = Operand->getType();
8148 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8149 ResType = ResAtomicType->getValueType();
Chandler Carruthc9332212011-06-27 08:02:19 +00008150
David Majnemercf7d1642015-02-12 21:07:34 +00008151 if (!ResType->isAnyPointerType()) return true;
8152
8153 QualType PointeeTy = ResType->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00008154 if (PointeeTy->isVoidType()) {
8155 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00008156 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00008157 }
8158 if (PointeeTy->isFunctionType()) {
8159 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00008160 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00008161 }
8162
Richard Trieuaba22802011-09-02 02:15:37 +00008163 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00008164
8165 return true;
8166}
8167
8168/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8169/// operands.
8170///
8171/// This routine will diagnose any invalid arithmetic on pointer operands much
8172/// like \see checkArithmeticOpPointerOperand. However, it has special logic
8173/// for emitting a single diagnostic even for operations where both LHS and RHS
8174/// are (potentially problematic) pointers.
8175///
8176/// \returns True when the operand is valid to use (even if as an extension).
8177static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00008178 Expr *LHSExpr, Expr *RHSExpr) {
8179 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8180 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00008181 if (!isLHSPointer && !isRHSPointer) return true;
8182
8183 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00008184 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8185 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00008186
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00008187 // if both are pointers check if operation is valid wrt address spaces
Anastasia Stulovae6e08232015-09-30 13:49:55 +00008188 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00008189 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8190 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8191 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8192 S.Diag(Loc,
8193 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8194 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8195 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8196 return false;
8197 }
8198 }
8199
Chandler Carruthc9332212011-06-27 08:02:19 +00008200 // Check for arithmetic on pointers to incomplete types.
8201 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8202 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8203 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00008204 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8205 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8206 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00008207
David Blaikiebbafb8a2012-03-11 07:00:24 +00008208 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00008209 }
8210
8211 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8212 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8213 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00008214 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8215 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8216 RHSExpr);
8217 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00008218
David Blaikiebbafb8a2012-03-11 07:00:24 +00008219 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00008220 }
8221
John McCallf2538342012-07-31 05:14:30 +00008222 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8223 return false;
8224 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8225 return false;
Richard Trieuaba22802011-09-02 02:15:37 +00008226
Chandler Carruthc9332212011-06-27 08:02:19 +00008227 return true;
8228}
8229
Nico Weberccec40d2012-03-02 22:01:22 +00008230/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8231/// literal.
8232static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8233 Expr *LHSExpr, Expr *RHSExpr) {
8234 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8235 Expr* IndexExpr = RHSExpr;
8236 if (!StrExpr) {
8237 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8238 IndexExpr = LHSExpr;
8239 }
8240
8241 bool IsStringPlusInt = StrExpr &&
8242 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
David Majnemer7e217452014-12-15 10:00:35 +00008243 if (!IsStringPlusInt || IndexExpr->isValueDependent())
Nico Weberccec40d2012-03-02 22:01:22 +00008244 return;
8245
8246 llvm::APSInt index;
8247 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8248 unsigned StrLenWithNull = StrExpr->getLength() + 1;
8249 if (index.isNonNegative() &&
8250 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8251 index.isUnsigned()))
8252 return;
8253 }
8254
8255 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8256 Self.Diag(OpLoc, diag::warn_string_plus_int)
8257 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8258
8259 // Only print a fixit for "str" + int, not for int + "str".
8260 if (IndexExpr == RHSExpr) {
Craig Topper07fa1762015-11-15 02:31:46 +00008261 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
Jordan Rose55659412013-10-25 16:52:00 +00008262 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
Nico Weberccec40d2012-03-02 22:01:22 +00008263 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8264 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8265 << FixItHint::CreateInsertion(EndLoc, "]");
8266 } else
Jordan Rose55659412013-10-25 16:52:00 +00008267 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8268}
8269
8270/// \brief Emit a warning when adding a char literal to a string.
8271static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8272 Expr *LHSExpr, Expr *RHSExpr) {
Daniel Marjamaki36859002014-12-15 20:22:33 +00008273 const Expr *StringRefExpr = LHSExpr;
Jordan Rose55659412013-10-25 16:52:00 +00008274 const CharacterLiteral *CharExpr =
8275 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
Daniel Marjamaki36859002014-12-15 20:22:33 +00008276
8277 if (!CharExpr) {
Jordan Rose55659412013-10-25 16:52:00 +00008278 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
Daniel Marjamaki36859002014-12-15 20:22:33 +00008279 StringRefExpr = RHSExpr;
Jordan Rose55659412013-10-25 16:52:00 +00008280 }
8281
8282 if (!CharExpr || !StringRefExpr)
8283 return;
8284
8285 const QualType StringType = StringRefExpr->getType();
8286
8287 // Return if not a PointerType.
8288 if (!StringType->isAnyPointerType())
8289 return;
8290
8291 // Return if not a CharacterType.
8292 if (!StringType->getPointeeType()->isAnyCharacterType())
8293 return;
8294
8295 ASTContext &Ctx = Self.getASTContext();
8296 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8297
8298 const QualType CharType = CharExpr->getType();
8299 if (!CharType->isAnyCharacterType() &&
8300 CharType->isIntegerType() &&
8301 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8302 Self.Diag(OpLoc, diag::warn_string_plus_char)
8303 << DiagRange << Ctx.CharTy;
8304 } else {
8305 Self.Diag(OpLoc, diag::warn_string_plus_char)
8306 << DiagRange << CharExpr->getType();
8307 }
8308
8309 // Only print a fixit for str + char, not for char + str.
8310 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
Craig Topper07fa1762015-11-15 02:31:46 +00008311 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
Jordan Rose55659412013-10-25 16:52:00 +00008312 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8313 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8314 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8315 << FixItHint::CreateInsertion(EndLoc, "]");
8316 } else {
8317 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8318 }
Nico Weberccec40d2012-03-02 22:01:22 +00008319}
8320
Richard Trieu993f3ab2011-09-12 18:08:02 +00008321/// \brief Emit error when two pointers are incompatible.
Richard Trieub10c6312011-09-01 22:53:23 +00008322static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00008323 Expr *LHSExpr, Expr *RHSExpr) {
8324 assert(LHSExpr->getType()->isAnyPointerType());
8325 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00008326 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00008327 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8328 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00008329}
8330
Craig Toppera92ffb02015-12-10 08:51:49 +00008331// C99 6.5.6
8332QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8333 SourceLocation Loc, BinaryOperatorKind Opc,
8334 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00008335 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8336
Richard Trieu4ae7e972011-09-06 21:13:51 +00008337 if (LHS.get()->getType()->isVectorType() ||
8338 RHS.get()->getType()->isVectorType()) {
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00008339 QualType compType = CheckVectorOperands(
8340 LHS, RHS, Loc, CompLHSTy,
8341 /*AllowBothBool*/getLangOpts().AltiVec,
8342 /*AllowBoolConversions*/getLangOpts().ZVector);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008343 if (CompLHSTy) *CompLHSTy = compType;
8344 return compType;
8345 }
Steve Naroff7a5af782007-07-13 16:58:59 +00008346
Richard Trieu4ae7e972011-09-06 21:13:51 +00008347 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8348 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00008349 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00008350
Jordan Rose55659412013-10-25 16:52:00 +00008351 // Diagnose "string literal" '+' int and string '+' "char literal".
8352 if (Opc == BO_Add) {
Nico Weberccec40d2012-03-02 22:01:22 +00008353 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
Jordan Rose55659412013-10-25 16:52:00 +00008354 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8355 }
Nico Weberccec40d2012-03-02 22:01:22 +00008356
Steve Naroffe4718892007-04-27 18:30:00 +00008357 // handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00008358 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008359 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00008360 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008361 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00008362
John McCallf2538342012-07-31 05:14:30 +00008363 // Type-checking. Ultimately the pointer's going to be in PExp;
8364 // note that we bias towards the LHS being the pointer.
8365 Expr *PExp = LHS.get(), *IExp = RHS.get();
Eli Friedman8e122982008-05-18 18:08:51 +00008366
John McCallf2538342012-07-31 05:14:30 +00008367 bool isObjCPointer;
8368 if (PExp->getType()->isPointerType()) {
8369 isObjCPointer = false;
8370 } else if (PExp->getType()->isObjCObjectPointerType()) {
8371 isObjCPointer = true;
8372 } else {
8373 std::swap(PExp, IExp);
8374 if (PExp->getType()->isPointerType()) {
8375 isObjCPointer = false;
8376 } else if (PExp->getType()->isObjCObjectPointerType()) {
8377 isObjCPointer = true;
8378 } else {
8379 return InvalidOperands(Loc, LHS, RHS);
8380 }
8381 }
8382 assert(PExp->getType()->isAnyPointerType());
Chandler Carruthc9332212011-06-27 08:02:19 +00008383
Richard Trieub420bca2011-09-12 18:37:54 +00008384 if (!IExp->getType()->isIntegerType())
8385 return InvalidOperands(Loc, LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00008386
Richard Trieub420bca2011-09-12 18:37:54 +00008387 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8388 return QualType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008389
John McCallf2538342012-07-31 05:14:30 +00008390 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
Richard Trieub420bca2011-09-12 18:37:54 +00008391 return QualType();
8392
8393 // Check array bounds for pointer arithemtic
8394 CheckArrayAccess(PExp, IExp);
8395
8396 if (CompLHSTy) {
8397 QualType LHSTy = Context.isPromotableBitField(LHS.get());
8398 if (LHSTy.isNull()) {
8399 LHSTy = LHS.get()->getType();
8400 if (LHSTy->isPromotableIntegerType())
8401 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00008402 }
Richard Trieub420bca2011-09-12 18:37:54 +00008403 *CompLHSTy = LHSTy;
Eli Friedman8e122982008-05-18 18:08:51 +00008404 }
8405
Richard Trieub420bca2011-09-12 18:37:54 +00008406 return PExp->getType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00008407}
8408
Chris Lattner2a3569b2008-04-07 05:30:13 +00008409// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00008410QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00008411 SourceLocation Loc,
8412 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00008413 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8414
Richard Trieu4ae7e972011-09-06 21:13:51 +00008415 if (LHS.get()->getType()->isVectorType() ||
8416 RHS.get()->getType()->isVectorType()) {
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00008417 QualType compType = CheckVectorOperands(
8418 LHS, RHS, Loc, CompLHSTy,
8419 /*AllowBothBool*/getLangOpts().AltiVec,
8420 /*AllowBoolConversions*/getLangOpts().ZVector);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008421 if (CompLHSTy) *CompLHSTy = compType;
8422 return compType;
8423 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008424
Richard Trieu4ae7e972011-09-06 21:13:51 +00008425 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8426 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00008427 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00008428
Chris Lattner4d62f422007-12-09 21:53:25 +00008429 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008430
Chris Lattner4d62f422007-12-09 21:53:25 +00008431 // Handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00008432 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008433 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00008434 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008435 }
Mike Stump11289f42009-09-09 15:08:12 +00008436
Chris Lattner4d62f422007-12-09 21:53:25 +00008437 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00008438 if (LHS.get()->getType()->isAnyPointerType()) {
8439 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00008440
Chris Lattner12bdebb2009-04-24 23:50:08 +00008441 // Diagnose bad cases where we step over interface counts.
John McCallf2538342012-07-31 05:14:30 +00008442 if (LHS.get()->getType()->isObjCObjectPointerType() &&
8443 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00008444 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00008445
Chris Lattner4d62f422007-12-09 21:53:25 +00008446 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00008447 if (RHS.get()->getType()->isIntegerType()) {
8448 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00008449 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00008450
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008451 // Check array bounds for pointer arithemtic
Craig Topperc3ec1492014-05-26 06:22:03 +00008452 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
Richard Smith13f67182011-12-16 19:31:14 +00008453 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008454
Richard Trieu4ae7e972011-09-06 21:13:51 +00008455 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8456 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00008457 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008458
Chris Lattner4d62f422007-12-09 21:53:25 +00008459 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00008460 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00008461 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00008462 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00008463
David Blaikiebbafb8a2012-03-11 07:00:24 +00008464 if (getLangOpts().CPlusPlus) {
Eli Friedman168fe152009-05-16 13:54:38 +00008465 // Pointee types must be the same: C++ [expr.add]
8466 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00008467 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00008468 }
8469 } else {
8470 // Pointee types must be compatible C99 6.5.6p3
8471 if (!Context.typesAreCompatible(
8472 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8473 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00008474 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00008475 return QualType();
8476 }
Chris Lattner4d62f422007-12-09 21:53:25 +00008477 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008478
Chandler Carruthc9332212011-06-27 08:02:19 +00008479 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00008480 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00008481 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008482
Richard Smith84c6b3d2013-09-10 21:34:14 +00008483 // The pointee type may have zero size. As an extension, a structure or
8484 // union may have zero size or an array may have zero length. In this
8485 // case subtraction does not make sense.
8486 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8487 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8488 if (ElementSize.isZero()) {
8489 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8490 << rpointee.getUnqualifiedType()
8491 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8492 }
8493 }
8494
Richard Trieu4ae7e972011-09-06 21:13:51 +00008495 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00008496 return Context.getPointerDiffType();
8497 }
8498 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008499
Richard Trieu4ae7e972011-09-06 21:13:51 +00008500 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008501}
8502
Douglas Gregor0bf31402010-10-08 23:50:27 +00008503static bool isScopedEnumerationType(QualType T) {
Richard Smith43d3f552015-01-14 00:33:10 +00008504 if (const EnumType *ET = T->getAs<EnumType>())
Douglas Gregor0bf31402010-10-08 23:50:27 +00008505 return ET->getDecl()->isScoped();
8506 return false;
8507}
8508
Richard Trieue4a19fb2011-09-06 21:21:28 +00008509static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Craig Toppera92ffb02015-12-10 08:51:49 +00008510 SourceLocation Loc, BinaryOperatorKind Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00008511 QualType LHSType) {
David Tweed042e0882013-01-07 16:43:27 +00008512 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8513 // so skip remaining warnings as we don't want to modify values within Sema.
8514 if (S.getLangOpts().OpenCL)
8515 return;
8516
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008517 llvm::APSInt Right;
8518 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00008519 if (RHS.get()->isValueDependent() ||
Davide Italiano346048a2015-03-26 21:37:49 +00008520 !RHS.get()->EvaluateAsInt(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008521 return;
8522
8523 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00008524 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00008525 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00008526 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008527 return;
8528 }
8529 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00008530 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008531 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00008532 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00008533 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00008534 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008535 return;
8536 }
8537 if (Opc != BO_Shl)
8538 return;
8539
8540 // When left shifting an ICE which is signed, we can check for overflow which
8541 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8542 // integers have defined behavior modulo one more than the maximum value
8543 // representable in the result type, so never warn for those.
8544 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00008545 if (LHS.get()->isValueDependent() ||
Davide Italianobf0f7752015-07-06 18:02:09 +00008546 LHSType->hasUnsignedIntegerRepresentation() ||
8547 !LHS.get()->EvaluateAsInt(Left, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008548 return;
Davide Italianobf0f7752015-07-06 18:02:09 +00008549
8550 // If LHS does not have a signed type and non-negative value
8551 // then, the behavior is undefined. Warn about it.
8552 if (Left.isNegative()) {
8553 S.DiagRuntimeBehavior(Loc, LHS.get(),
8554 S.PDiag(diag::warn_shift_lhs_negative)
8555 << LHS.get()->getSourceRange());
8556 return;
8557 }
8558
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008559 llvm::APInt ResultBits =
8560 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8561 if (LeftBits.uge(ResultBits))
8562 return;
8563 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8564 Result = Result.shl(Right);
8565
Ted Kremenek70f05fd2011-06-15 00:54:52 +00008566 // Print the bit representation of the signed integer as an unsigned
8567 // hexadecimal number.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008568 SmallString<40> HexResult;
Ted Kremenek70f05fd2011-06-15 00:54:52 +00008569 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8570
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008571 // If we are only missing a sign bit, this is less likely to result in actual
8572 // bugs -- if the result is cast back to an unsigned type, it will have the
8573 // expected value. Thus we place this behind a different warning that can be
8574 // turned off separately if needed.
8575 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00008576 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Yaron Keren92e1b622015-03-18 10:17:07 +00008577 << HexResult << LHSType
Richard Trieue4a19fb2011-09-06 21:21:28 +00008578 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008579 return;
8580 }
8581
8582 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00008583 << HexResult.str() << Result.getMinSignedBits() << LHSType
8584 << Left.getBitWidth() << LHS.get()->getSourceRange()
8585 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008586}
8587
Sameer Sahasrabuddhea75db662015-02-25 05:48:23 +00008588/// \brief Return the resulting type when an OpenCL vector is shifted
8589/// by a scalar or vector shift amount.
8590static QualType checkOpenCLVectorShift(Sema &S,
8591 ExprResult &LHS, ExprResult &RHS,
8592 SourceLocation Loc, bool IsCompAssign) {
8593 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8594 if (!LHS.get()->getType()->isVectorType()) {
8595 S.Diag(Loc, diag::err_shift_rhs_only_vector)
8596 << RHS.get()->getType() << LHS.get()->getType()
8597 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8598 return QualType();
8599 }
8600
8601 if (!IsCompAssign) {
8602 LHS = S.UsualUnaryConversions(LHS.get());
8603 if (LHS.isInvalid()) return QualType();
8604 }
8605
8606 RHS = S.UsualUnaryConversions(RHS.get());
8607 if (RHS.isInvalid()) return QualType();
8608
8609 QualType LHSType = LHS.get()->getType();
George Burgess IVdf1ed002016-01-13 01:52:39 +00008610 const VectorType *LHSVecTy = LHSType->castAs<VectorType>();
Sameer Sahasrabuddhea75db662015-02-25 05:48:23 +00008611 QualType LHSEleType = LHSVecTy->getElementType();
8612
8613 // Note that RHS might not be a vector.
8614 QualType RHSType = RHS.get()->getType();
8615 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8616 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8617
8618 // OpenCL v1.1 s6.3.j says that the operands need to be integers.
8619 if (!LHSEleType->isIntegerType()) {
8620 S.Diag(Loc, diag::err_typecheck_expect_int)
8621 << LHS.get()->getType() << LHS.get()->getSourceRange();
8622 return QualType();
8623 }
8624
8625 if (!RHSEleType->isIntegerType()) {
8626 S.Diag(Loc, diag::err_typecheck_expect_int)
8627 << RHS.get()->getType() << RHS.get()->getSourceRange();
8628 return QualType();
8629 }
8630
8631 if (RHSVecTy) {
8632 // OpenCL v1.1 s6.3.j says that for vector types, the operators
8633 // are applied component-wise. So if RHS is a vector, then ensure
8634 // that the number of elements is the same as LHS...
8635 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8636 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8637 << LHS.get()->getType() << RHS.get()->getType()
8638 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8639 return QualType();
8640 }
8641 } else {
8642 // ...else expand RHS to match the number of elements in LHS.
8643 QualType VecTy =
8644 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8645 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8646 }
8647
8648 return LHSType;
8649}
8650
Chris Lattner2a3569b2008-04-07 05:30:13 +00008651// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00008652QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Craig Toppera92ffb02015-12-10 08:51:49 +00008653 SourceLocation Loc, BinaryOperatorKind Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008654 bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00008655 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8656
Nate Begemane46ee9a2009-10-25 02:26:48 +00008657 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00008658 if (LHS.get()->getType()->isVectorType() ||
Sameer Sahasrabuddhea75db662015-02-25 05:48:23 +00008659 RHS.get()->getType()->isVectorType()) {
8660 if (LangOpts.OpenCL)
8661 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00008662 if (LangOpts.ZVector) {
8663 // The shift operators for the z vector extensions work basically
8664 // like OpenCL shifts, except that neither the LHS nor the RHS is
8665 // allowed to be a "vector bool".
8666 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8667 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8668 return InvalidOperands(Loc, LHS, RHS);
8669 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8670 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8671 return InvalidOperands(Loc, LHS, RHS);
8672 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8673 }
8674 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8675 /*AllowBothBool*/true,
8676 /*AllowBoolConversions*/false);
Sameer Sahasrabuddhea75db662015-02-25 05:48:23 +00008677 }
Nate Begemane46ee9a2009-10-25 02:26:48 +00008678
Chris Lattner5c11c412007-12-12 05:47:28 +00008679 // Shifts don't perform usual arithmetic conversions, they just do integer
8680 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008681
John McCall57cdd882010-12-16 19:28:59 +00008682 // For the LHS, do usual unary conversions, but then reset them away
8683 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00008684 ExprResult OldLHS = LHS;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008685 LHS = UsualUnaryConversions(LHS.get());
Richard Trieue4a19fb2011-09-06 21:21:28 +00008686 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00008687 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00008688 QualType LHSType = LHS.get()->getType();
Richard Trieuba63ce62011-09-09 01:45:06 +00008689 if (IsCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00008690
8691 // The RHS is simpler.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008692 RHS = UsualUnaryConversions(RHS.get());
Richard Trieue4a19fb2011-09-06 21:21:28 +00008693 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00008694 return QualType();
Douglas Gregor8997dac2013-04-16 15:41:08 +00008695 QualType RHSType = RHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00008696
Douglas Gregor8997dac2013-04-16 15:41:08 +00008697 // C99 6.5.7p2: Each of the operands shall have integer type.
8698 if (!LHSType->hasIntegerRepresentation() ||
8699 !RHSType->hasIntegerRepresentation())
8700 return InvalidOperands(Loc, LHS, RHS);
8701
8702 // C++0x: Don't allow scoped enums. FIXME: Use something better than
8703 // hasIntegerRepresentation() above instead of this.
8704 if (isScopedEnumerationType(LHSType) ||
8705 isScopedEnumerationType(RHSType)) {
8706 return InvalidOperands(Loc, LHS, RHS);
8707 }
Ryan Flynnf53fab82009-08-07 16:20:20 +00008708 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00008709 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00008710
Chris Lattner5c11c412007-12-12 05:47:28 +00008711 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00008712 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00008713}
8714
Chandler Carruth17773fc2010-07-10 12:30:03 +00008715static bool IsWithinTemplateSpecialization(Decl *D) {
8716 if (DeclContext *DC = D->getDeclContext()) {
8717 if (isa<ClassTemplateSpecializationDecl>(DC))
8718 return true;
8719 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8720 return FD->isFunctionTemplateSpecialization();
8721 }
8722 return false;
8723}
8724
Richard Trieueea56f72011-09-02 03:48:46 +00008725/// If two different enums are compared, raise a warning.
Ted Kremenekf2ca8ec2013-01-30 19:10:21 +00008726static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8727 Expr *RHS) {
8728 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8729 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00008730
8731 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8732 if (!LHSEnumType)
8733 return;
8734 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8735 if (!RHSEnumType)
8736 return;
8737
8738 // Ignore anonymous enums.
8739 if (!LHSEnumType->getDecl()->getIdentifier())
8740 return;
8741 if (!RHSEnumType->getDecl()->getIdentifier())
8742 return;
8743
8744 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8745 return;
8746
8747 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8748 << LHSStrippedType << RHSStrippedType
Ted Kremenekf2ca8ec2013-01-30 19:10:21 +00008749 << LHS->getSourceRange() << RHS->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00008750}
8751
Richard Trieudd82a5c2011-09-02 02:55:45 +00008752/// \brief Diagnose bad pointer comparisons.
8753static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00008754 ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00008755 bool IsError) {
8756 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieudd82a5c2011-09-02 02:55:45 +00008757 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00008758 << LHS.get()->getType() << RHS.get()->getType()
8759 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00008760}
8761
8762/// \brief Returns false if the pointers are converted to a composite type,
8763/// true otherwise.
8764static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00008765 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00008766 // C++ [expr.rel]p2:
8767 // [...] Pointer conversions (4.10) and qualification
8768 // conversions (4.4) are performed on pointer operands (or on
8769 // a pointer operand and a null pointer constant) to bring
8770 // them to their composite pointer type. [...]
8771 //
8772 // C++ [expr.eq]p1 uses the same notion for (in)equality
8773 // comparisons of pointers.
8774
8775 // C++ [expr.eq]p2:
8776 // In addition, pointers to members can be compared, or a pointer to
8777 // member and a null pointer constant. Pointer to member conversions
8778 // (4.11) and qualification conversions (4.4) are performed to bring
8779 // them to a common type. If one operand is a null pointer constant,
8780 // the common type is the type of the other operand. Otherwise, the
8781 // common type is a pointer to member type similar (4.4) to the type
8782 // of one of the operands, with a cv-qualification signature (4.4)
8783 // that is the union of the cv-qualification signatures of the operand
8784 // types.
8785
Richard Trieu1762d7c2011-09-06 21:27:33 +00008786 QualType LHSType = LHS.get()->getType();
8787 QualType RHSType = RHS.get()->getType();
8788 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
8789 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieudd82a5c2011-09-02 02:55:45 +00008790
8791 bool NonStandardCompositeType = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00008792 bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
Richard Trieu1762d7c2011-09-06 21:27:33 +00008793 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00008794 if (T.isNull()) {
Richard Trieu1762d7c2011-09-06 21:27:33 +00008795 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieudd82a5c2011-09-02 02:55:45 +00008796 return true;
8797 }
8798
8799 if (NonStandardCompositeType)
8800 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieu1762d7c2011-09-06 21:27:33 +00008801 << LHSType << RHSType << T << LHS.get()->getSourceRange()
8802 << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00008803
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008804 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
8805 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00008806 return false;
8807}
8808
8809static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00008810 ExprResult &LHS,
8811 ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00008812 bool IsError) {
8813 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
8814 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00008815 << LHS.get()->getType() << RHS.get()->getType()
8816 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00008817}
8818
Jordan Rosed49a33e2012-06-08 21:14:25 +00008819static bool isObjCObjectLiteral(ExprResult &E) {
Jordan Rosee2028132012-11-09 23:55:21 +00008820 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
Jordan Rosed49a33e2012-06-08 21:14:25 +00008821 case Stmt::ObjCArrayLiteralClass:
8822 case Stmt::ObjCDictionaryLiteralClass:
8823 case Stmt::ObjCStringLiteralClass:
8824 case Stmt::ObjCBoxedExprClass:
8825 return true;
8826 default:
8827 // Note that ObjCBoolLiteral is NOT an object literal!
8828 return false;
8829 }
8830}
8831
Jordan Rose7660f782012-07-17 17:46:40 +00008832static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
Benjamin Kramer25c05102013-02-15 15:17:50 +00008833 const ObjCObjectPointerType *Type =
8834 LHS->getType()->getAs<ObjCObjectPointerType>();
8835
8836 // If this is not actually an Objective-C object, bail out.
8837 if (!Type)
Jordan Rose7660f782012-07-17 17:46:40 +00008838 return false;
Benjamin Kramer25c05102013-02-15 15:17:50 +00008839
8840 // Get the LHS object's interface type.
8841 QualType InterfaceType = Type->getPointeeType();
Jordan Rose7660f782012-07-17 17:46:40 +00008842
8843 // If the RHS isn't an Objective-C object, bail out.
8844 if (!RHS->getType()->isObjCObjectPointerType())
8845 return false;
8846
8847 // Try to find the -isEqual: method.
8848 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
8849 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
8850 InterfaceType,
8851 /*instance=*/true);
8852 if (!Method) {
8853 if (Type->isObjCIdType()) {
8854 // For 'id', just check the global pool.
8855 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
Fariborz Jahanian890803f2015-04-15 17:26:21 +00008856 /*receiverId=*/true);
Jordan Rose7660f782012-07-17 17:46:40 +00008857 } else {
8858 // Check protocols.
Benjamin Kramer25c05102013-02-15 15:17:50 +00008859 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
Jordan Rose7660f782012-07-17 17:46:40 +00008860 /*instance=*/true);
8861 }
8862 }
8863
8864 if (!Method)
8865 return false;
8866
Alp Toker03376dc2014-07-07 09:02:20 +00008867 QualType T = Method->parameters()[0]->getType();
Jordan Rose7660f782012-07-17 17:46:40 +00008868 if (!T->isObjCObjectPointerType())
8869 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008870
8871 QualType R = Method->getReturnType();
Jordan Rose7660f782012-07-17 17:46:40 +00008872 if (!R->isScalarType())
8873 return false;
8874
8875 return true;
8876}
8877
Ted Kremenek01a33f82012-12-21 21:59:36 +00008878Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
8879 FromE = FromE->IgnoreParenImpCasts();
8880 switch (FromE->getStmtClass()) {
8881 default:
8882 break;
8883 case Stmt::ObjCStringLiteralClass:
8884 // "string literal"
8885 return LK_String;
8886 case Stmt::ObjCArrayLiteralClass:
8887 // "array literal"
8888 return LK_Array;
8889 case Stmt::ObjCDictionaryLiteralClass:
8890 // "dictionary literal"
8891 return LK_Dictionary;
Ted Kremenek64873352012-12-21 22:46:35 +00008892 case Stmt::BlockExprClass:
8893 return LK_Block;
Ted Kremenek01a33f82012-12-21 21:59:36 +00008894 case Stmt::ObjCBoxedExprClass: {
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008895 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
Ted Kremenek01a33f82012-12-21 21:59:36 +00008896 switch (Inner->getStmtClass()) {
8897 case Stmt::IntegerLiteralClass:
8898 case Stmt::FloatingLiteralClass:
8899 case Stmt::CharacterLiteralClass:
8900 case Stmt::ObjCBoolLiteralExprClass:
8901 case Stmt::CXXBoolLiteralExprClass:
8902 // "numeric literal"
8903 return LK_Numeric;
8904 case Stmt::ImplicitCastExprClass: {
8905 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
8906 // Boolean literals can be represented by implicit casts.
8907 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
8908 return LK_Numeric;
8909 break;
8910 }
8911 default:
8912 break;
8913 }
8914 return LK_Boxed;
8915 }
8916 }
8917 return LK_None;
8918}
8919
Jordan Rose7660f782012-07-17 17:46:40 +00008920static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
8921 ExprResult &LHS, ExprResult &RHS,
8922 BinaryOperator::Opcode Opc){
Jordan Rose63ffaa82012-07-17 17:46:48 +00008923 Expr *Literal;
8924 Expr *Other;
8925 if (isObjCObjectLiteral(LHS)) {
8926 Literal = LHS.get();
8927 Other = RHS.get();
8928 } else {
8929 Literal = RHS.get();
8930 Other = LHS.get();
8931 }
8932
8933 // Don't warn on comparisons against nil.
8934 Other = Other->IgnoreParenCasts();
8935 if (Other->isNullPointerConstant(S.getASTContext(),
8936 Expr::NPC_ValueDependentIsNotNull))
8937 return;
Jordan Rosed49a33e2012-06-08 21:14:25 +00008938
Jordan Roseea70bf72012-07-17 17:46:44 +00008939 // This should be kept in sync with warn_objc_literal_comparison.
Ted Kremenek01a33f82012-12-21 21:59:36 +00008940 // LK_String should always be after the other literals, since it has its own
8941 // warning flag.
8942 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
Ted Kremenek64873352012-12-21 22:46:35 +00008943 assert(LiteralKind != Sema::LK_Block);
Ted Kremenek01a33f82012-12-21 21:59:36 +00008944 if (LiteralKind == Sema::LK_None) {
Jordan Rosed49a33e2012-06-08 21:14:25 +00008945 llvm_unreachable("Unknown Objective-C object literal kind");
8946 }
8947
Ted Kremenek01a33f82012-12-21 21:59:36 +00008948 if (LiteralKind == Sema::LK_String)
Jordan Roseea70bf72012-07-17 17:46:44 +00008949 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
8950 << Literal->getSourceRange();
8951 else
8952 S.Diag(Loc, diag::warn_objc_literal_comparison)
8953 << LiteralKind << Literal->getSourceRange();
Jordan Rosed49a33e2012-06-08 21:14:25 +00008954
Jordan Rose7660f782012-07-17 17:46:40 +00008955 if (BinaryOperator::isEqualityOp(Opc) &&
8956 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
8957 SourceLocation Start = LHS.get()->getLocStart();
Craig Topper07fa1762015-11-15 02:31:46 +00008958 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
Fariborz Jahanian4dca1d32013-02-01 20:04:49 +00008959 CharSourceRange OpRange =
Craig Topper07fa1762015-11-15 02:31:46 +00008960 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
Jordan Rosef9198032012-07-09 16:54:44 +00008961
Jordan Rose7660f782012-07-17 17:46:40 +00008962 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
8963 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
Fariborz Jahanian4dca1d32013-02-01 20:04:49 +00008964 << FixItHint::CreateReplacement(OpRange, " isEqual:")
Jordan Rose7660f782012-07-17 17:46:40 +00008965 << FixItHint::CreateInsertion(End, "]");
Jordan Rosed49a33e2012-06-08 21:14:25 +00008966 }
Jordan Rosed49a33e2012-06-08 21:14:25 +00008967}
8968
Richard Trieubb4b8942013-06-10 18:52:07 +00008969static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
8970 ExprResult &RHS,
8971 SourceLocation Loc,
Craig Toppera92ffb02015-12-10 08:51:49 +00008972 BinaryOperatorKind Opc) {
Richard Trieubb4b8942013-06-10 18:52:07 +00008973 // Check that left hand side is !something.
Richard Trieu949abc32013-07-04 00:50:18 +00008974 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
Richard Trieubb4b8942013-06-10 18:52:07 +00008975 if (!UO || UO->getOpcode() != UO_LNot) return;
8976
8977 // Only check if the right hand side is non-bool arithmetic type.
Richard Trieu1cd076e2015-08-19 21:33:54 +00008978 if (RHS.get()->isKnownToHaveBooleanValue()) return;
Richard Trieubb4b8942013-06-10 18:52:07 +00008979
8980 // Make sure that the something in !something is not bool.
8981 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
Richard Trieu1cd076e2015-08-19 21:33:54 +00008982 if (SubExpr->isKnownToHaveBooleanValue()) return;
Richard Trieubb4b8942013-06-10 18:52:07 +00008983
8984 // Emit warning.
8985 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
8986 << Loc;
8987
8988 // First note suggest !(x < y)
8989 SourceLocation FirstOpen = SubExpr->getLocStart();
8990 SourceLocation FirstClose = RHS.get()->getLocEnd();
Craig Topper07fa1762015-11-15 02:31:46 +00008991 FirstClose = S.getLocForEndOfToken(FirstClose);
Eli Friedmanef0b4a32013-07-22 23:09:39 +00008992 if (FirstClose.isInvalid())
8993 FirstOpen = SourceLocation();
Richard Trieubb4b8942013-06-10 18:52:07 +00008994 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
8995 << FixItHint::CreateInsertion(FirstOpen, "(")
8996 << FixItHint::CreateInsertion(FirstClose, ")");
8997
8998 // Second note suggests (!x) < y
8999 SourceLocation SecondOpen = LHS.get()->getLocStart();
9000 SourceLocation SecondClose = LHS.get()->getLocEnd();
Craig Topper07fa1762015-11-15 02:31:46 +00009001 SecondClose = S.getLocForEndOfToken(SecondClose);
Eli Friedmanef0b4a32013-07-22 23:09:39 +00009002 if (SecondClose.isInvalid())
9003 SecondOpen = SourceLocation();
Richard Trieubb4b8942013-06-10 18:52:07 +00009004 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9005 << FixItHint::CreateInsertion(SecondOpen, "(")
9006 << FixItHint::CreateInsertion(SecondClose, ")");
9007}
9008
Eli Friedman5a722e92013-09-06 03:13:09 +00009009// Get the decl for a simple expression: a reference to a variable,
9010// an implicit C++ field reference, or an implicit ObjC ivar reference.
9011static ValueDecl *getCompareDecl(Expr *E) {
9012 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9013 return DR->getDecl();
9014 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9015 if (Ivar->isFreeIvar())
9016 return Ivar->getDecl();
9017 }
9018 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9019 if (Mem->isImplicitAccess())
9020 return Mem->getMemberDecl();
9021 }
Craig Topperc3ec1492014-05-26 06:22:03 +00009022 return nullptr;
Eli Friedman5a722e92013-09-06 03:13:09 +00009023}
9024
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00009025// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00009026QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Craig Toppera92ffb02015-12-10 08:51:49 +00009027 SourceLocation Loc, BinaryOperatorKind Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009028 bool IsRelational) {
Richard Trieuf8916e12011-09-16 00:53:10 +00009029 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9030
Chris Lattner9a152e22009-12-05 05:40:13 +00009031 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00009032 if (LHS.get()->getType()->isVectorType() ||
9033 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00009034 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009035
Richard Trieub80728f2011-09-06 21:43:51 +00009036 QualType LHSType = LHS.get()->getType();
9037 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00009038
Richard Trieub80728f2011-09-06 21:43:51 +00009039 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9040 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00009041
Ted Kremenekf2ca8ec2013-01-30 19:10:21 +00009042 checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
Craig Toppera92ffb02015-12-10 08:51:49 +00009043 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc);
Chandler Carruth712563b2011-02-17 08:37:06 +00009044
Richard Trieub80728f2011-09-06 21:43:51 +00009045 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuba63ce62011-09-09 01:45:06 +00009046 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieub80728f2011-09-06 21:43:51 +00009047 !LHS.get()->getLocStart().isMacroID() &&
Richard Trieu30bfa362013-11-02 02:11:23 +00009048 !RHS.get()->getLocStart().isMacroID() &&
9049 ActiveTemplateInstantiations.empty()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00009050 // For non-floating point types, check for self-comparisons of the form
9051 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
9052 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00009053 //
9054 // NOTE: Don't warn about comparison expressions resulting from macro
9055 // expansion. Also don't warn about comparisons which are only self
9056 // comparisons within a template specialization. The warnings should catch
9057 // obvious cases in the definition of the template anyways. The idea is to
9058 // warn when the typed comparison operator will always evaluate to the same
9059 // result.
Eli Friedman5a722e92013-09-06 03:13:09 +00009060 ValueDecl *DL = getCompareDecl(LHSStripped);
9061 ValueDecl *DR = getCompareDecl(RHSStripped);
9062 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009063 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
Eli Friedman5a722e92013-09-06 03:13:09 +00009064 << 0 // self-
9065 << (Opc == BO_EQ
9066 || Opc == BO_LE
9067 || Opc == BO_GE));
9068 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9069 !DL->getType()->isReferenceType() &&
9070 !DR->getType()->isReferenceType()) {
9071 // what is it always going to eval to?
9072 char always_evals_to;
9073 switch(Opc) {
9074 case BO_EQ: // e.g. array1 == array2
9075 always_evals_to = 0; // false
9076 break;
9077 case BO_NE: // e.g. array1 != array2
9078 always_evals_to = 1; // true
9079 break;
9080 default:
9081 // best we can say is 'a constant'
9082 always_evals_to = 2; // e.g. array1 <= array2
9083 break;
Douglas Gregorec170db2010-06-08 19:50:34 +00009084 }
Craig Topperc3ec1492014-05-26 06:22:03 +00009085 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
Eli Friedman5a722e92013-09-06 03:13:09 +00009086 << 1 // array
9087 << always_evals_to);
Chandler Carruth17773fc2010-07-10 12:30:03 +00009088 }
Mike Stump11289f42009-09-09 15:08:12 +00009089
Chris Lattner222b8bd2009-03-08 19:39:53 +00009090 if (isa<CastExpr>(LHSStripped))
9091 LHSStripped = LHSStripped->IgnoreParenCasts();
9092 if (isa<CastExpr>(RHSStripped))
9093 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00009094
Chris Lattner222b8bd2009-03-08 19:39:53 +00009095 // Warn about comparisons against a string constant (unless the other
9096 // operand is null), the user probably wants strcmp.
Craig Topperc3ec1492014-05-26 06:22:03 +00009097 Expr *literalString = nullptr;
9098 Expr *literalStringStripped = nullptr;
Chris Lattner222b8bd2009-03-08 19:39:53 +00009099 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009100 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00009101 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00009102 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00009103 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00009104 } else if ((isa<StringLiteral>(RHSStripped) ||
9105 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009106 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00009107 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00009108 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00009109 literalStringStripped = RHSStripped;
9110 }
9111
9112 if (literalString) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009113 DiagRuntimeBehavior(Loc, nullptr,
Douglas Gregor49862b82010-01-12 23:18:54 +00009114 PDiag(diag::warn_stringcompare)
9115 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00009116 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00009117 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00009118 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009119
Douglas Gregorec170db2010-06-08 19:50:34 +00009120 // C99 6.5.8p3 / C99 6.5.9p4
Eli Friedmane6d33952013-07-08 20:20:06 +00009121 UsualArithmeticConversions(LHS, RHS);
9122 if (LHS.isInvalid() || RHS.isInvalid())
9123 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00009124
Richard Trieub80728f2011-09-06 21:43:51 +00009125 LHSType = LHS.get()->getType();
9126 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00009127
Douglas Gregorca63811b2008-11-19 03:25:36 +00009128 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00009129 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00009130
Richard Trieuba63ce62011-09-09 01:45:06 +00009131 if (IsRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00009132 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00009133 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00009134 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00009135 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00009136 if (LHSType->hasFloatingRepresentation())
9137 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00009138
Richard Trieub80728f2011-09-06 21:43:51 +00009139 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00009140 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00009141 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009142
Richard Trieu3bb8b562014-02-26 02:36:06 +00009143 const Expr::NullPointerConstantKind LHSNullKind =
9144 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9145 const Expr::NullPointerConstantKind RHSNullKind =
9146 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9147 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9148 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9149
9150 if (!IsRelational && LHSIsNull != RHSIsNull) {
9151 bool IsEquality = Opc == BO_EQ;
9152 if (RHSIsNull)
9153 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9154 RHS.get()->getSourceRange());
9155 else
9156 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9157 LHS.get()->getSourceRange());
9158 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009159
Douglas Gregorf267edd2010-06-15 21:38:40 +00009160 // All of the following pointer-related warnings are GCC extensions, except
9161 // when handling null pointer constants.
Richard Trieub80728f2011-09-06 21:43:51 +00009162 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00009163 QualType LCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00009164 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattner3a0702e2008-04-03 05:07:25 +00009165 QualType RCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00009166 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00009167
David Blaikiebbafb8a2012-03-11 07:00:24 +00009168 if (getLangOpts().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00009169 if (LCanPointeeTy == RCanPointeeTy)
9170 return ResultTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00009171 if (!IsRelational &&
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00009172 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9173 // Valid unless comparison between non-null pointer and function pointer
9174 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00009175 // In a SFINAE context, we treat this as a hard error to maintain
9176 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00009177 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9178 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00009179 diagnoseFunctionPointerToVoidComparison(
David Blaikie3a3c4e02013-02-21 06:05:05 +00009180 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00009181
9182 if (isSFINAEContext())
9183 return QualType();
9184
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009185 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00009186 return ResultTy;
9187 }
9188 }
Anders Carlssona95069c2010-11-04 03:17:43 +00009189
Richard Trieub80728f2011-09-06 21:43:51 +00009190 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00009191 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00009192 else
9193 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00009194 }
Eli Friedman16c209612009-08-23 00:27:47 +00009195 // C99 6.5.9p2 and C99 6.5.8p2
9196 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9197 RCanPointeeTy.getUnqualifiedType())) {
9198 // Valid unless a relational comparison of function pointers
Richard Trieuba63ce62011-09-09 01:45:06 +00009199 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman16c209612009-08-23 00:27:47 +00009200 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00009201 << LHSType << RHSType << LHS.get()->getSourceRange()
9202 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00009203 }
Richard Trieuba63ce62011-09-09 01:45:06 +00009204 } else if (!IsRelational &&
Eli Friedman16c209612009-08-23 00:27:47 +00009205 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9206 // Valid unless comparison between non-null pointer and function pointer
9207 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00009208 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00009209 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00009210 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00009211 } else {
9212 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00009213 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00009214 }
John McCall7684dde2011-03-11 04:25:25 +00009215 if (LCanPointeeTy != RCanPointeeTy) {
Anastasia Stulova2446b8b2015-12-11 17:41:19 +00009216 // Treat NULL constant as a special case in OpenCL.
9217 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
Anastasia Stulovae6e08232015-09-30 13:49:55 +00009218 const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9219 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9220 Diag(Loc,
9221 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9222 << LHSType << RHSType << 0 /* comparison */
9223 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9224 }
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00009225 }
David Tweede1468322013-12-11 13:39:46 +00009226 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9227 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9228 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9229 : CK_BitCast;
John McCall7684dde2011-03-11 04:25:25 +00009230 if (LHSIsNull && !RHSIsNull)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009231 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
John McCall7684dde2011-03-11 04:25:25 +00009232 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009233 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
John McCall7684dde2011-03-11 04:25:25 +00009234 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00009235 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00009236 }
Mike Stump11289f42009-09-09 15:08:12 +00009237
David Blaikiebbafb8a2012-03-11 07:00:24 +00009238 if (getLangOpts().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00009239 // Comparison of nullptr_t with itself.
Richard Trieub80728f2011-09-06 21:43:51 +00009240 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlssona95069c2010-11-04 03:17:43 +00009241 return ResultTy;
9242
Mike Stump11289f42009-09-09 15:08:12 +00009243 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00009244 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00009245 if (RHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00009246 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00009247 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00009248 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009249 RHS = ImpCastExprToType(RHS.get(), LHSType,
Richard Trieub80728f2011-09-06 21:43:51 +00009250 LHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00009251 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00009252 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00009253 return ResultTy;
9254 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00009255 if (LHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00009256 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00009257 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00009258 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009259 LHS = ImpCastExprToType(LHS.get(), RHSType,
Richard Trieub80728f2011-09-06 21:43:51 +00009260 RHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00009261 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00009262 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00009263 return ResultTy;
9264 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00009265
9266 // Comparison of member pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00009267 if (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00009268 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
9269 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00009270 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00009271 else
9272 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00009273 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00009274
9275 // Handle scoped enumeration types specifically, since they don't promote
9276 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00009277 if (LHS.get()->getType()->isEnumeralType() &&
9278 Context.hasSameUnqualifiedType(LHS.get()->getType(),
9279 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00009280 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00009281 }
Mike Stump11289f42009-09-09 15:08:12 +00009282
Steve Naroff081c7422008-09-04 15:10:53 +00009283 // Handle block pointer types.
Richard Trieuba63ce62011-09-09 01:45:06 +00009284 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieub80728f2011-09-06 21:43:51 +00009285 RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00009286 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9287 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00009288
Steve Naroff081c7422008-09-04 15:10:53 +00009289 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00009290 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00009291 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00009292 << LHSType << RHSType << LHS.get()->getSourceRange()
9293 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00009294 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009295 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00009296 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00009297 }
John Wiegley01296292011-04-08 18:41:53 +00009298
Steve Naroffe18f94c2008-09-28 01:11:11 +00009299 // Allow block pointers to be compared with null pointer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00009300 if (!IsRelational
Richard Trieub80728f2011-09-06 21:43:51 +00009301 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9302 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00009303 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00009304 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00009305 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00009306 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00009307 ->getPointeeType()->isVoidType())))
9308 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00009309 << LHSType << RHSType << LHS.get()->getSourceRange()
9310 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00009311 }
John McCall7684dde2011-03-11 04:25:25 +00009312 if (LHSIsNull && !RHSIsNull)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009313 LHS = ImpCastExprToType(LHS.get(), RHSType,
John McCall9320b872011-09-09 05:25:32 +00009314 RHSType->isPointerType() ? CK_BitCast
9315 : CK_AnyPointerToBlockPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00009316 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009317 RHS = ImpCastExprToType(RHS.get(), LHSType,
John McCall9320b872011-09-09 05:25:32 +00009318 LHSType->isPointerType() ? CK_BitCast
9319 : CK_AnyPointerToBlockPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00009320 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00009321 }
Steve Naroff081c7422008-09-04 15:10:53 +00009322
Richard Trieub80728f2011-09-06 21:43:51 +00009323 if (LHSType->isObjCObjectPointerType() ||
9324 RHSType->isObjCObjectPointerType()) {
9325 const PointerType *LPT = LHSType->getAs<PointerType>();
9326 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00009327 if (LPT || RPT) {
9328 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9329 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009330
Steve Naroff753567f2008-11-17 19:49:16 +00009331 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00009332 !Context.typesAreCompatible(LHSType, RHSType)) {
9333 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00009334 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00009335 }
Fariborz Jahanian374089e2013-07-31 17:12:26 +00009336 if (LHSIsNull && !RHSIsNull) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009337 Expr *E = LHS.get();
Fariborz Jahanian374089e2013-07-31 17:12:26 +00009338 if (getLangOpts().ObjCAutoRefCount)
9339 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
9340 LHS = ImpCastExprToType(E, RHSType,
John McCall9320b872011-09-09 05:25:32 +00009341 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Fariborz Jahanian374089e2013-07-31 17:12:26 +00009342 }
9343 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009344 Expr *E = RHS.get();
Fariborz Jahanian374089e2013-07-31 17:12:26 +00009345 if (getLangOpts().ObjCAutoRefCount)
George Burgess IV60bc9722016-01-13 23:36:34 +00009346 CheckObjCARCConversion(SourceRange(), LHSType, E,
9347 CCK_ImplicitConversion, /*Diagnose=*/true,
9348 /*DiagnoseCFAudited=*/false, Opc);
Fariborz Jahanian374089e2013-07-31 17:12:26 +00009349 RHS = ImpCastExprToType(E, LHSType,
John McCall9320b872011-09-09 05:25:32 +00009350 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Fariborz Jahanian374089e2013-07-31 17:12:26 +00009351 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00009352 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00009353 }
Richard Trieub80728f2011-09-06 21:43:51 +00009354 if (LHSType->isObjCObjectPointerType() &&
9355 RHSType->isObjCObjectPointerType()) {
9356 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9357 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00009358 /*isError*/false);
Jordan Rosed49a33e2012-06-08 21:14:25 +00009359 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
Jordan Rose7660f782012-07-17 17:46:40 +00009360 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
Jordan Rosed49a33e2012-06-08 21:14:25 +00009361
John McCall7684dde2011-03-11 04:25:25 +00009362 if (LHSIsNull && !RHSIsNull)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009363 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00009364 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009365 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00009366 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00009367 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00009368 }
Richard Trieub80728f2011-09-06 21:43:51 +00009369 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9370 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00009371 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00009372 bool isError = false;
Douglas Gregor0064c592012-09-14 04:35:37 +00009373 if (LangOpts.DebuggerSupport) {
9374 // Under a debugger, allow the comparison of pointers to integers,
9375 // since users tend to want to compare addresses.
9376 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
Richard Trieub80728f2011-09-06 21:43:51 +00009377 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009378 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00009379 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009380 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00009381 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009382 else if (getLangOpts().CPlusPlus) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00009383 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9384 isError = true;
9385 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00009386 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00009387
Chris Lattnerd99bd522009-08-23 00:03:44 +00009388 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00009389 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00009390 << LHSType << RHSType << LHS.get()->getSourceRange()
9391 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00009392 if (isError)
9393 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00009394 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00009395
Richard Trieub80728f2011-09-06 21:43:51 +00009396 if (LHSType->isIntegerType())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009397 LHS = ImpCastExprToType(LHS.get(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00009398 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00009399 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009400 RHS = ImpCastExprToType(RHS.get(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00009401 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00009402 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00009403 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00009404
Steve Naroff4b191572008-09-04 16:56:14 +00009405 // Handle block pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00009406 if (!IsRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00009407 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009408 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00009409 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00009410 }
Richard Trieuba63ce62011-09-09 01:45:06 +00009411 if (!IsRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00009412 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009413 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00009414 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00009415 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00009416
Richard Trieub80728f2011-09-06 21:43:51 +00009417 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00009418}
9419
Tanya Lattner20248222012-01-16 21:02:28 +00009420
9421// Return a signed type that is of identical size and number of elements.
9422// For floating point vectors, return an integer type of identical size
9423// and number of elements.
9424QualType Sema::GetSignedVectorType(QualType V) {
9425 const VectorType *VTy = V->getAs<VectorType>();
9426 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9427 if (TypeSize == Context.getTypeSize(Context.CharTy))
9428 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9429 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9430 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9431 else if (TypeSize == Context.getTypeSize(Context.IntTy))
9432 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9433 else if (TypeSize == Context.getTypeSize(Context.LongTy))
9434 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9435 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9436 "Unhandled vector element size in vector compare");
9437 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9438}
9439
Nate Begeman191a6b12008-07-14 18:02:46 +00009440/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00009441/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00009442/// like a scalar comparison, a vector comparison produces a vector of integer
9443/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00009444QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00009445 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009446 bool IsRelational) {
Nate Begeman191a6b12008-07-14 18:02:46 +00009447 // Check to make sure we're operating on vectors of the same type and width,
9448 // Allowing one side to be a scalar of element type.
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00009449 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9450 /*AllowBothBool*/true,
9451 /*AllowBoolConversions*/getLangOpts().ZVector);
Nate Begeman191a6b12008-07-14 18:02:46 +00009452 if (vType.isNull())
9453 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009454
Richard Trieubcce2f72011-09-07 01:19:57 +00009455 QualType LHSType = LHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00009456
Anton Yartsev530deb92011-03-27 15:36:07 +00009457 // If AltiVec, the comparison results in a numeric type, i.e.
9458 // bool for C++, int for C
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00009459 if (getLangOpts().AltiVec &&
9460 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00009461 return Context.getLogicalOperationType();
9462
Nate Begeman191a6b12008-07-14 18:02:46 +00009463 // For non-floating point types, check for self-comparisons of the form
9464 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
9465 // often indicate logic errors in the program.
Richard Trieu30bfa362013-11-02 02:11:23 +00009466 if (!LHSType->hasFloatingRepresentation() &&
9467 ActiveTemplateInstantiations.empty()) {
Richard Smith508ebf32011-10-28 03:31:48 +00009468 if (DeclRefExpr* DRL
9469 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9470 if (DeclRefExpr* DRR
9471 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begeman191a6b12008-07-14 18:02:46 +00009472 if (DRL->getDecl() == DRR->getDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00009473 DiagRuntimeBehavior(Loc, nullptr,
Douglas Gregorec170db2010-06-08 19:50:34 +00009474 PDiag(diag::warn_comparison_always)
9475 << 0 // self-
9476 << 2 // "a constant"
9477 );
Nate Begeman191a6b12008-07-14 18:02:46 +00009478 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009479
Nate Begeman191a6b12008-07-14 18:02:46 +00009480 // Check for comparisons of floating point operands using != and ==.
Richard Trieuba63ce62011-09-09 01:45:06 +00009481 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikieca043222012-01-16 05:16:03 +00009482 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieubcce2f72011-09-07 01:19:57 +00009483 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00009484 }
Tanya Lattner20248222012-01-16 21:02:28 +00009485
9486 // Return a signed type for the vector.
Reid Klecknere1a16462016-04-14 21:03:38 +00009487 return GetSignedVectorType(vType);
Tanya Lattner20248222012-01-16 21:02:28 +00009488}
Mike Stump4e1f26a2009-02-19 03:04:26 +00009489
Tanya Lattner3dd33b22012-01-19 01:16:16 +00009490QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9491 SourceLocation Loc) {
Tanya Lattner20248222012-01-16 21:02:28 +00009492 // Ensure that either both operands are of the same vector type, or
9493 // one operand is of a vector type and the other is of its element type.
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00009494 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9495 /*AllowBothBool*/true,
9496 /*AllowBoolConversions*/false);
Joey Gouly7d00f002013-02-21 11:49:56 +00009497 if (vType.isNull())
9498 return InvalidOperands(Loc, LHS, RHS);
9499 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9500 vType->hasFloatingRepresentation())
Tanya Lattner20248222012-01-16 21:02:28 +00009501 return InvalidOperands(Loc, LHS, RHS);
9502
9503 return GetSignedVectorType(LHS.get()->getType());
Nate Begeman191a6b12008-07-14 18:02:46 +00009504}
9505
Steve Naroff218bc2b2007-05-04 21:54:46 +00009506inline QualType Sema::CheckBitwiseOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00009507 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00009508 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9509
Richard Trieubcce2f72011-09-07 01:19:57 +00009510 if (LHS.get()->getType()->isVectorType() ||
9511 RHS.get()->getType()->isVectorType()) {
9512 if (LHS.get()->getType()->hasIntegerRepresentation() &&
9513 RHS.get()->getType()->hasIntegerRepresentation())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00009514 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9515 /*AllowBothBool*/true,
9516 /*AllowBoolConversions*/getLangOpts().ZVector);
Richard Trieubcce2f72011-09-07 01:19:57 +00009517 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00009518 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00009519
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009520 ExprResult LHSResult = LHS, RHSResult = RHS;
Richard Trieubcce2f72011-09-07 01:19:57 +00009521 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuba63ce62011-09-09 01:45:06 +00009522 IsCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00009523 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00009524 return QualType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009525 LHS = LHSResult.get();
9526 RHS = RHSResult.get();
Mike Stump4e1f26a2009-02-19 03:04:26 +00009527
Eli Friedman93ee5ca2012-06-16 02:19:17 +00009528 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00009529 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00009530 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00009531}
9532
Craig Toppera92ffb02015-12-10 08:51:49 +00009533// C99 6.5.[13,14]
9534inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9535 SourceLocation Loc,
9536 BinaryOperatorKind Opc) {
Tanya Lattner20248222012-01-16 21:02:28 +00009537 // Check vector operands differently.
9538 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9539 return CheckVectorLogicalOperands(LHS, RHS, Loc);
9540
Chris Lattner8406c512010-07-13 19:41:32 +00009541 // Diagnose cases where the user write a logical and/or but probably meant a
9542 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
9543 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00009544 if (LHS.get()->getType()->isIntegerType() &&
9545 !LHS.get()->getType()->isBooleanType() &&
9546 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00009547 // Don't warn in macros or template instantiations.
9548 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00009549 // If the RHS can be constant folded, and if it constant folds to something
9550 // that isn't 0 or 1 (which indicate a potential logical operation that
9551 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00009552 // Parens on the RHS are ignored.
Richard Smith00ab3ae2011-10-16 23:01:09 +00009553 llvm::APSInt Result;
9554 if (RHS.get()->EvaluateAsInt(Result, Context))
Argyrios Kyrtzidisd6eb2b92014-04-28 00:20:16 +00009555 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9556 !RHS.get()->getExprLoc().isMacroID()) ||
Richard Smith00ab3ae2011-10-16 23:01:09 +00009557 (Result != 0 && Result != 1)) {
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00009558 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00009559 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00009560 << (Opc == BO_LAnd ? "&&" : "||");
9561 // Suggest replacing the logical operator with the bitwise version
9562 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9563 << (Opc == BO_LAnd ? "&" : "|")
9564 << FixItHint::CreateReplacement(SourceRange(
Craig Topper07fa1762015-11-15 02:31:46 +00009565 Loc, getLocForEndOfToken(Loc)),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00009566 Opc == BO_LAnd ? "&" : "|");
9567 if (Opc == BO_LAnd)
9568 // Suggest replacing "Foo() && kNonZero" with "Foo()"
9569 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9570 << FixItHint::CreateRemoval(
Craig Topper07fa1762015-11-15 02:31:46 +00009571 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9572 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00009573 }
Chris Lattner938533d2010-07-24 01:10:11 +00009574 }
Joey Gouly7d00f002013-02-21 11:49:56 +00009575
David Blaikiebbafb8a2012-03-11 07:00:24 +00009576 if (!Context.getLangOpts().CPlusPlus) {
Joey Gouly7d00f002013-02-21 11:49:56 +00009577 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9578 // not operate on the built-in scalar and vector float types.
9579 if (Context.getLangOpts().OpenCL &&
9580 Context.getLangOpts().OpenCLVersion < 120) {
9581 if (LHS.get()->getType()->isFloatingType() ||
9582 RHS.get()->getType()->isFloatingType())
9583 return InvalidOperands(Loc, LHS, RHS);
9584 }
9585
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009586 LHS = UsualUnaryConversions(LHS.get());
Richard Trieubcce2f72011-09-07 01:19:57 +00009587 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00009588 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00009589
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009590 RHS = UsualUnaryConversions(RHS.get());
Richard Trieubcce2f72011-09-07 01:19:57 +00009591 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00009592 return QualType();
9593
Richard Trieubcce2f72011-09-07 01:19:57 +00009594 if (!LHS.get()->getType()->isScalarType() ||
9595 !RHS.get()->getType()->isScalarType())
9596 return InvalidOperands(Loc, LHS, RHS);
Fariborz Jahanian3365bfc2014-11-11 21:54:19 +00009597
Anders Carlsson2e7bc112009-11-23 21:47:44 +00009598 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00009599 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009600
John McCall4a2429a2010-06-04 00:29:51 +00009601 // The following is safe because we only use this method for
9602 // non-overloadable operands.
9603
Anders Carlsson2e7bc112009-11-23 21:47:44 +00009604 // C++ [expr.log.and]p1
9605 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00009606 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00009607 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9608 if (LHSRes.isInvalid())
9609 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009610 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00009611
Richard Trieubcce2f72011-09-07 01:19:57 +00009612 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9613 if (RHSRes.isInvalid())
9614 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009615 RHS = RHSRes;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009616
Anders Carlsson2e7bc112009-11-23 21:47:44 +00009617 // C++ [expr.log.and]p2
9618 // C++ [expr.log.or]p2
9619 // The result is a bool.
9620 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00009621}
9622
Fariborz Jahanian071caef2011-03-26 19:48:30 +00009623static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00009624 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9625 if (!ME) return false;
9626 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9627 ObjCMessageExpr *Base =
9628 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
9629 if (!Base) return false;
Craig Topperc3ec1492014-05-26 06:22:03 +00009630 return Base->getMethodDecl() != nullptr;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00009631}
9632
John McCall5fa2ef42012-03-13 00:37:01 +00009633/// Is the given expression (which must be 'const') a reference to a
9634/// variable which was originally non-const, but which has become
9635/// 'const' due to being captured within a block?
9636enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9637static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9638 assert(E->isLValue() && E->getType().isConstQualified());
9639 E = E->IgnoreParens();
9640
9641 // Must be a reference to a declaration from an enclosing scope.
9642 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9643 if (!DRE) return NCCK_None;
Alexey Bataev19acc3d2015-01-12 10:17:46 +00009644 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
John McCall5fa2ef42012-03-13 00:37:01 +00009645
9646 // The declaration must be a variable which is not declared 'const'.
9647 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9648 if (!var) return NCCK_None;
9649 if (var->getType().isConstQualified()) return NCCK_None;
9650 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9651
9652 // Decide whether the first capture was for a block or a lambda.
Craig Topperc3ec1492014-05-26 06:22:03 +00009653 DeclContext *DC = S.CurContext, *Prev = nullptr;
Richard Smith75e3f692013-09-28 04:31:26 +00009654 while (DC != var->getDeclContext()) {
9655 Prev = DC;
John McCall5fa2ef42012-03-13 00:37:01 +00009656 DC = DC->getParent();
Richard Smith75e3f692013-09-28 04:31:26 +00009657 }
9658 // Unless we have an init-capture, we've gone one step too far.
9659 if (!var->isInitCapture())
9660 DC = Prev;
John McCall5fa2ef42012-03-13 00:37:01 +00009661 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9662}
9663
Richard Trieuaf7d76c2015-04-11 01:53:13 +00009664static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9665 Ty = Ty.getNonReferenceType();
9666 if (IsDereference && Ty->isPointerType())
9667 Ty = Ty->getPointeeType();
9668 return !Ty.isConstQualified();
9669}
9670
9671/// Emit the "read-only variable not assignable" error and print notes to give
9672/// more information about why the variable is not assignable, such as pointing
9673/// to the declaration of a const variable, showing that a method is const, or
9674/// that the function is returning a const reference.
9675static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9676 SourceLocation Loc) {
9677 // Update err_typecheck_assign_const and note_typecheck_assign_const
9678 // when this enum is changed.
9679 enum {
9680 ConstFunction,
9681 ConstVariable,
9682 ConstMember,
9683 ConstMethod,
9684 ConstUnknown, // Keep as last element
9685 };
9686
9687 SourceRange ExprRange = E->getSourceRange();
9688
9689 // Only emit one error on the first const found. All other consts will emit
9690 // a note to the error.
9691 bool DiagnosticEmitted = false;
9692
9693 // Track if the current expression is the result of a derefence, and if the
9694 // next checked expression is the result of a derefence.
9695 bool IsDereference = false;
9696 bool NextIsDereference = false;
9697
9698 // Loop to process MemberExpr chains.
9699 while (true) {
9700 IsDereference = NextIsDereference;
9701 NextIsDereference = false;
9702
9703 E = E->IgnoreParenImpCasts();
9704 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9705 NextIsDereference = ME->isArrow();
9706 const ValueDecl *VD = ME->getMemberDecl();
9707 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9708 // Mutable fields can be modified even if the class is const.
9709 if (Field->isMutable()) {
9710 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9711 break;
9712 }
9713
9714 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9715 if (!DiagnosticEmitted) {
9716 S.Diag(Loc, diag::err_typecheck_assign_const)
9717 << ExprRange << ConstMember << false /*static*/ << Field
9718 << Field->getType();
9719 DiagnosticEmitted = true;
9720 }
9721 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9722 << ConstMember << false /*static*/ << Field << Field->getType()
9723 << Field->getSourceRange();
9724 }
9725 E = ME->getBase();
9726 continue;
9727 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
9728 if (VDecl->getType().isConstQualified()) {
9729 if (!DiagnosticEmitted) {
9730 S.Diag(Loc, diag::err_typecheck_assign_const)
9731 << ExprRange << ConstMember << true /*static*/ << VDecl
9732 << VDecl->getType();
9733 DiagnosticEmitted = true;
9734 }
9735 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9736 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
9737 << VDecl->getSourceRange();
9738 }
9739 // Static fields do not inherit constness from parents.
9740 break;
9741 }
9742 break;
9743 } // End MemberExpr
9744 break;
9745 }
9746
9747 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9748 // Function calls
9749 const FunctionDecl *FD = CE->getDirectCallee();
David Majnemerd39bcae2015-08-26 05:13:19 +00009750 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
Richard Trieuaf7d76c2015-04-11 01:53:13 +00009751 if (!DiagnosticEmitted) {
9752 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9753 << ConstFunction << FD;
9754 DiagnosticEmitted = true;
9755 }
9756 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
9757 diag::note_typecheck_assign_const)
9758 << ConstFunction << FD << FD->getReturnType()
9759 << FD->getReturnTypeSourceRange();
9760 }
9761 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9762 // Point to variable declaration.
9763 if (const ValueDecl *VD = DRE->getDecl()) {
9764 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
9765 if (!DiagnosticEmitted) {
9766 S.Diag(Loc, diag::err_typecheck_assign_const)
9767 << ExprRange << ConstVariable << VD << VD->getType();
9768 DiagnosticEmitted = true;
9769 }
9770 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9771 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
9772 }
9773 }
9774 } else if (isa<CXXThisExpr>(E)) {
9775 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
9776 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
9777 if (MD->isConst()) {
9778 if (!DiagnosticEmitted) {
9779 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9780 << ConstMethod << MD;
9781 DiagnosticEmitted = true;
9782 }
9783 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
9784 << ConstMethod << MD << MD->getSourceRange();
9785 }
9786 }
9787 }
9788 }
9789
9790 if (DiagnosticEmitted)
9791 return;
9792
9793 // Can't determine a more specific message, so display the generic error.
9794 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
9795}
9796
Chris Lattner30bd3272008-11-18 01:22:49 +00009797/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
9798/// emit an error and return true. If so, return false.
9799static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianca5c5972012-04-10 17:30:10 +00009800 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Reid Klecknerf463a8a2016-04-29 00:37:43 +00009801
9802 S.CheckShadowingDeclModification(E, Loc);
9803
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00009804 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00009805 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00009806 &Loc);
Eli Friedmanaa205c42013-06-27 01:36:36 +00009807 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
Fariborz Jahanian071caef2011-03-26 19:48:30 +00009808 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00009809 if (IsLV == Expr::MLV_Valid)
9810 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009811
David Majnemer3e7743e2014-12-26 06:06:53 +00009812 unsigned DiagID = 0;
Chris Lattner30bd3272008-11-18 01:22:49 +00009813 bool NeedType = false;
9814 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00009815 case Expr::MLV_ConstQualified:
John McCall5fa2ef42012-03-13 00:37:01 +00009816 // Use a specialized diagnostic when we're assigning to an object
9817 // from an enclosing function or block.
9818 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
9819 if (NCCK == NCCK_Block)
David Majnemer3e7743e2014-12-26 06:06:53 +00009820 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
John McCall5fa2ef42012-03-13 00:37:01 +00009821 else
David Majnemer3e7743e2014-12-26 06:06:53 +00009822 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
John McCall5fa2ef42012-03-13 00:37:01 +00009823 break;
9824 }
9825
John McCalld4631322011-06-17 06:42:21 +00009826 // In ARC, use some specialized diagnostics for occasions where we
9827 // infer 'const'. These are always pseudo-strong variables.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009828 if (S.getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00009829 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
9830 if (declRef && isa<VarDecl>(declRef->getDecl())) {
9831 VarDecl *var = cast<VarDecl>(declRef->getDecl());
9832
John McCalld4631322011-06-17 06:42:21 +00009833 // Use the normal diagnostic if it's pseudo-__strong but the
9834 // user actually wrote 'const'.
9835 if (var->isARCPseudoStrong() &&
9836 (!var->getTypeSourceInfo() ||
9837 !var->getTypeSourceInfo()->getType().isConstQualified())) {
9838 // There are two pseudo-strong cases:
9839 // - self
John McCall31168b02011-06-15 23:02:42 +00009840 ObjCMethodDecl *method = S.getCurMethodDecl();
9841 if (method && var == method->getSelfDecl())
David Majnemer3e7743e2014-12-26 06:06:53 +00009842 DiagID = method->isClassMethod()
Ted Kremenek1fcdaa92011-11-14 21:59:25 +00009843 ? diag::err_typecheck_arc_assign_self_class_method
9844 : diag::err_typecheck_arc_assign_self;
John McCalld4631322011-06-17 06:42:21 +00009845
9846 // - fast enumeration variables
9847 else
David Majnemer3e7743e2014-12-26 06:06:53 +00009848 DiagID = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00009849
John McCall31168b02011-06-15 23:02:42 +00009850 SourceRange Assign;
9851 if (Loc != OrigLoc)
9852 Assign = SourceRange(OrigLoc, OrigLoc);
David Majnemer3e7743e2014-12-26 06:06:53 +00009853 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
Richard Trieuaf7d76c2015-04-11 01:53:13 +00009854 // We need to preserve the AST regardless, so migration tool
John McCall31168b02011-06-15 23:02:42 +00009855 // can do its job.
9856 return false;
9857 }
9858 }
9859 }
9860
Richard Trieuaf7d76c2015-04-11 01:53:13 +00009861 // If none of the special cases above are triggered, then this is a
9862 // simple const assignment.
9863 if (DiagID == 0) {
9864 DiagnoseConstAssignment(S, E, Loc);
9865 return true;
9866 }
9867
John McCall31168b02011-06-15 23:02:42 +00009868 break;
Richard Smitha7bd4582015-05-22 01:14:39 +00009869 case Expr::MLV_ConstAddrSpace:
9870 DiagnoseConstAssignment(S, E, Loc);
9871 return true;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009872 case Expr::MLV_ArrayType:
Richard Smitheb3cad52012-06-04 22:27:30 +00009873 case Expr::MLV_ArrayTemporary:
David Majnemer3e7743e2014-12-26 06:06:53 +00009874 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
Chris Lattner30bd3272008-11-18 01:22:49 +00009875 NeedType = true;
9876 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009877 case Expr::MLV_NotObjectType:
David Majnemer3e7743e2014-12-26 06:06:53 +00009878 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
Chris Lattner30bd3272008-11-18 01:22:49 +00009879 NeedType = true;
9880 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00009881 case Expr::MLV_LValueCast:
David Majnemer3e7743e2014-12-26 06:06:53 +00009882 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
Chris Lattner30bd3272008-11-18 01:22:49 +00009883 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00009884 case Expr::MLV_Valid:
9885 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00009886 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00009887 case Expr::MLV_MemberFunction:
9888 case Expr::MLV_ClassTemporary:
David Majnemer3e7743e2014-12-26 06:06:53 +00009889 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
Chris Lattner30bd3272008-11-18 01:22:49 +00009890 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009891 case Expr::MLV_IncompleteType:
9892 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00009893 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009894 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009895 case Expr::MLV_DuplicateVectorComponents:
David Majnemer3e7743e2014-12-26 06:06:53 +00009896 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
Chris Lattner30bd3272008-11-18 01:22:49 +00009897 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00009898 case Expr::MLV_NoSetterProperty:
John McCall526ab472011-10-25 17:37:35 +00009899 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian071caef2011-03-26 19:48:30 +00009900 case Expr::MLV_InvalidMessageExpression:
David Majnemer3e7743e2014-12-26 06:06:53 +00009901 DiagID = diag::error_readonly_message_assignment;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00009902 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00009903 case Expr::MLV_SubObjCPropertySetting:
David Majnemer3e7743e2014-12-26 06:06:53 +00009904 DiagID = diag::error_no_subobject_property_setting;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00009905 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00009906 }
Steve Naroffad373bd2007-07-31 12:34:36 +00009907
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00009908 SourceRange Assign;
9909 if (Loc != OrigLoc)
9910 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00009911 if (NeedType)
David Majnemer3e7743e2014-12-26 06:06:53 +00009912 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00009913 else
David Majnemer3e7743e2014-12-26 06:06:53 +00009914 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00009915 return true;
9916}
9917
Nico Weberb8124d12012-07-03 02:03:06 +00009918static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
9919 SourceLocation Loc,
9920 Sema &Sema) {
9921 // C / C++ fields
Nico Weber33fd5232012-06-28 23:53:12 +00009922 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
9923 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
9924 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
9925 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
Nico Weberb8124d12012-07-03 02:03:06 +00009926 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
Nico Weber33fd5232012-06-28 23:53:12 +00009927 }
Chris Lattner30bd3272008-11-18 01:22:49 +00009928
Nico Weberb8124d12012-07-03 02:03:06 +00009929 // Objective-C instance variables
Nico Weber33fd5232012-06-28 23:53:12 +00009930 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
9931 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
9932 if (OL && OR && OL->getDecl() == OR->getDecl()) {
9933 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
9934 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
9935 if (RL && RR && RL->getDecl() == RR->getDecl())
Nico Weberb8124d12012-07-03 02:03:06 +00009936 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
Nico Weber33fd5232012-06-28 23:53:12 +00009937 }
9938}
Chris Lattner30bd3272008-11-18 01:22:49 +00009939
9940// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +00009941QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00009942 SourceLocation Loc,
9943 QualType CompoundType) {
John McCall526ab472011-10-25 17:37:35 +00009944 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
9945
Chris Lattner326f7572008-11-18 01:30:42 +00009946 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +00009947 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00009948 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00009949
Richard Trieuda4f43a62011-09-07 01:33:52 +00009950 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00009951 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
9952 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009953 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00009954 if (CompoundType.isNull()) {
Nico Weber33fd5232012-06-28 23:53:12 +00009955 Expr *RHSCheck = RHS.get();
9956
Nico Weberb8124d12012-07-03 02:03:06 +00009957 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
Nico Weber33fd5232012-06-28 23:53:12 +00009958
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00009959 QualType LHSTy(LHSType);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00009960 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00009961 if (RHS.isInvalid())
9962 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00009963 // Special case of NSObject attributes on c-style pointer types.
9964 if (ConvTy == IncompatiblePointer &&
9965 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00009966 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00009967 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00009968 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00009969 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009970
John McCall7decc9e2010-11-18 06:31:45 +00009971 if (ConvTy == Compatible &&
Fariborz Jahaniane2a77762012-01-24 19:40:13 +00009972 LHSType->isObjCObjectType())
Fariborz Jahanian3c4225a2012-01-24 18:05:45 +00009973 Diag(Loc, diag::err_objc_object_assignment)
9974 << LHSType;
John McCall7decc9e2010-11-18 06:31:45 +00009975
Chris Lattnerea714382008-08-21 18:04:13 +00009976 // If the RHS is a unary plus or minus, check to see if they = and + are
9977 // right next to each other. If so, the user may have typo'd "x =+ 4"
9978 // instead of "x += 4".
Chris Lattnerea714382008-08-21 18:04:13 +00009979 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
9980 RHSCheck = ICE->getSubExpr();
9981 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00009982 if ((UO->getOpcode() == UO_Plus ||
9983 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00009984 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00009985 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00009986 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner36c39c92009-03-08 06:51:10 +00009987 // And there is a space or other character before the subexpr of the
9988 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00009989 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattnered9f14c2009-03-09 07:11:10 +00009990 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00009991 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00009992 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00009993 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00009994 }
Chris Lattnerea714382008-08-21 18:04:13 +00009995 }
John McCall31168b02011-06-15 23:02:42 +00009996
9997 if (ConvTy == Compatible) {
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009998 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
9999 // Warn about retain cycles where a block captures the LHS, but
10000 // not if the LHS is a simple variable into which the block is
10001 // being stored...unless that variable can be captured by reference!
10002 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10003 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10004 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10005 checkRetainCycles(LHSExpr, RHS.get());
10006
Jordan Rosed3934582012-09-28 22:21:30 +000010007 // It is safe to assign a weak reference into a strong variable.
10008 // Although this code can still have problems:
10009 // id x = self.weakProp;
10010 // id y = self.weakProp;
10011 // we do not warn to warn spuriously when 'x' and 'y' are on separate
10012 // paths through the function. This should be revisited if
10013 // -Wrepeated-use-of-weak is made flow-sensitive.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010014 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10015 RHS.get()->getLocStart()))
Jordan Rosed3934582012-09-28 22:21:30 +000010016 getCurFunction()->markSafeWeakUse(RHS.get());
10017
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010018 } else if (getLangOpts().ObjCAutoRefCount) {
Richard Trieuda4f43a62011-09-07 01:33:52 +000010019 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010020 }
John McCall31168b02011-06-15 23:02:42 +000010021 }
Chris Lattnerea714382008-08-21 18:04:13 +000010022 } else {
10023 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +000010024 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +000010025 }
Chris Lattner9bad62c2008-01-04 18:04:52 +000010026
Chris Lattner326f7572008-11-18 01:30:42 +000010027 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +000010028 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +000010029 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +000010030
Richard Trieuda4f43a62011-09-07 01:33:52 +000010031 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010032
Steve Naroff98cf3e92007-06-06 18:38:38 +000010033 // C99 6.5.16p3: The type of an assignment expression is the type of the
10034 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +000010035 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +000010036 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10037 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +000010038 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +000010039 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010040 return (getLangOpts().CPlusPlus
John McCall01cbf2d2010-10-12 02:19:57 +000010041 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +000010042}
10043
Richard Trieufaca2d82016-02-18 23:58:40 +000010044// Only ignore explicit casts to void.
10045static bool IgnoreCommaOperand(const Expr *E) {
10046 E = E->IgnoreParens();
10047
10048 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10049 if (CE->getCastKind() == CK_ToVoid) {
10050 return true;
10051 }
10052 }
10053
10054 return false;
10055}
10056
10057// Look for instances where it is likely the comma operator is confused with
10058// another operator. There is a whitelist of acceptable expressions for the
10059// left hand side of the comma operator, otherwise emit a warning.
10060void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10061 // No warnings in macros
10062 if (Loc.isMacroID())
10063 return;
10064
10065 // Don't warn in template instantiations.
10066 if (!ActiveTemplateInstantiations.empty())
10067 return;
10068
10069 // Scope isn't fine-grained enough to whitelist the specific cases, so
10070 // instead, skip more than needed, then call back into here with the
10071 // CommaVisitor in SemaStmt.cpp.
10072 // The whitelisted locations are the initialization and increment portions
10073 // of a for loop. The additional checks are on the condition of
10074 // if statements, do/while loops, and for loops.
Richard Trieu54f82bf2016-02-19 00:15:50 +000010075 const unsigned ForIncrementFlags =
Richard Trieufaca2d82016-02-18 23:58:40 +000010076 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10077 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10078 const unsigned ScopeFlags = getCurScope()->getFlags();
10079 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10080 (ScopeFlags & ForInitFlags) == ForInitFlags)
10081 return;
10082
10083 // If there are multiple comma operators used together, get the RHS of the
10084 // of the comma operator as the LHS.
10085 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10086 if (BO->getOpcode() != BO_Comma)
10087 break;
10088 LHS = BO->getRHS();
10089 }
10090
10091 // Only allow some expressions on LHS to not warn.
10092 if (IgnoreCommaOperand(LHS))
10093 return;
10094
10095 Diag(Loc, diag::warn_comma_operator);
10096 Diag(LHS->getLocStart(), diag::note_cast_to_void)
10097 << LHS->getSourceRange()
10098 << FixItHint::CreateInsertion(LHS->getLocStart(),
10099 LangOpts.CPlusPlus ? "static_cast<void>("
10100 : "(void)(")
10101 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10102 ")");
10103}
10104
Chris Lattner326f7572008-11-18 01:30:42 +000010105// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +000010106static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +000010107 SourceLocation Loc) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010108 LHS = S.CheckPlaceholderExpr(LHS.get());
10109 RHS = S.CheckPlaceholderExpr(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +000010110 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +000010111 return QualType();
10112
John McCall73d36182010-10-12 07:14:40 +000010113 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10114 // operands, but not unary promotions.
10115 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +000010116
John McCall34376a62010-12-04 03:47:34 +000010117 // So we treat the LHS as a ignored value, and in C++ we allow the
10118 // containing site to determine what should be done with the RHS.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010119 LHS = S.IgnoredValueConversions(LHS.get());
John Wiegley01296292011-04-08 18:41:53 +000010120 if (LHS.isInvalid())
10121 return QualType();
John McCall34376a62010-12-04 03:47:34 +000010122
Eli Friedmanc11535c2012-05-24 00:47:05 +000010123 S.DiagnoseUnusedExprResult(LHS.get());
10124
David Blaikiebbafb8a2012-03-11 07:00:24 +000010125 if (!S.getLangOpts().CPlusPlus) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010126 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +000010127 if (RHS.isInvalid())
10128 return QualType();
10129 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +000010130 S.RequireCompleteType(Loc, RHS.get()->getType(),
10131 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +000010132 }
Eli Friedmanba961a92009-03-23 00:24:07 +000010133
Richard Trieufaca2d82016-02-18 23:58:40 +000010134 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10135 S.DiagnoseCommaOperator(LHS.get(), Loc);
10136
John Wiegley01296292011-04-08 18:41:53 +000010137 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +000010138}
10139
Steve Naroff7a5af782007-07-13 16:58:59 +000010140/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10141/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +000010142static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10143 ExprValueKind &VK,
David Majnemer74242432014-07-31 04:52:13 +000010144 ExprObjectKind &OK,
John McCall4bc41ae2010-11-18 19:01:18 +000010145 SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +000010146 bool IsInc, bool IsPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000010147 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +000010148 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000010149
Chris Lattner6b0cf142008-11-21 07:05:48 +000010150 QualType ResType = Op->getType();
David Chisnallfa35df62012-01-16 17:27:18 +000010151 // Atomic types can be used for increment / decrement where the non-atomic
10152 // versions can, so ignore the _Atomic() specifier for the purpose of
10153 // checking.
10154 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10155 ResType = ResAtomicType->getValueType();
10156
Chris Lattner6b0cf142008-11-21 07:05:48 +000010157 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +000010158
David Blaikiebbafb8a2012-03-11 07:00:24 +000010159 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +000010160 // Decrement of bool is not allowed.
Richard Trieuba63ce62011-09-09 01:45:06 +000010161 if (!IsInc) {
John McCall4bc41ae2010-11-18 19:01:18 +000010162 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +000010163 return QualType();
10164 }
10165 // Increment of bool sets it to true, but is deprecated.
Richard Smith4a0cd892015-11-26 02:16:37 +000010166 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10167 : diag::warn_increment_bool)
10168 << Op->getSourceRange();
Richard Trieu493df1a2013-08-08 01:50:23 +000010169 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10170 // Error on enum increments and decrements in C++ mode
10171 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10172 return QualType();
Sebastian Redle10c2c32008-12-20 09:35:34 +000010173 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +000010174 // OK!
John McCallf2538342012-07-31 05:14:30 +000010175 } else if (ResType->isPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +000010176 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +000010177 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +000010178 return QualType();
John McCallf2538342012-07-31 05:14:30 +000010179 } else if (ResType->isObjCObjectPointerType()) {
10180 // On modern runtimes, ObjC pointer arithmetic is forbidden.
10181 // Otherwise, we just need a complete type.
10182 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10183 checkArithmeticOnObjCPointer(S, OpLoc, Op))
10184 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +000010185 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +000010186 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +000010187 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +000010188 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +000010189 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +000010190 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +000010191 if (PR.isInvalid()) return QualType();
David Majnemer74242432014-07-31 04:52:13 +000010192 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +000010193 IsInc, IsPrefix);
David Blaikiebbafb8a2012-03-11 07:00:24 +000010194 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev85129b82011-02-07 02:17:30 +000010195 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Ulrich Weigand3c5038a2015-07-30 14:08:36 +000010196 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10197 (ResType->getAs<VectorType>()->getVectorKind() !=
10198 VectorType::AltiVecBool)) {
10199 // The z vector extensions allow ++ and -- for non-bool vectors.
David Tweed16574d82013-09-06 09:58:08 +000010200 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10201 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10202 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
Chris Lattner6b0cf142008-11-21 07:05:48 +000010203 } else {
John McCall4bc41ae2010-11-18 19:01:18 +000010204 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuba63ce62011-09-09 01:45:06 +000010205 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +000010206 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +000010207 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000010208 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +000010209 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +000010210 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +000010211 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +000010212 // In C++, a prefix increment is the same type as the operand. Otherwise
10213 // (in C or with postfix), the increment is the unqualified type of the
10214 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010215 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +000010216 VK = VK_LValue;
David Majnemer74242432014-07-31 04:52:13 +000010217 OK = Op->getObjectKind();
John McCall4bc41ae2010-11-18 19:01:18 +000010218 return ResType;
10219 } else {
10220 VK = VK_RValue;
10221 return ResType.getUnqualifiedType();
10222 }
Steve Naroff26c8ea52007-03-21 21:08:52 +000010223}
Fariborz Jahanian805b74e2010-09-14 23:02:38 +000010224
10225
Anders Carlsson806700f2008-02-01 07:15:58 +000010226/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +000010227/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +000010228/// where the declaration is needed for type checking. We only need to
10229/// handle cases when the expression references a function designator
10230/// or is an lvalue. Here are some examples:
10231/// - &(x) => x
10232/// - &*****f => f for f a function designator.
10233/// - &s.xx => s
10234/// - &s.zz[1].yy -> s, if zz is an array
10235/// - *(x + 1) -> x, if x is an array
10236/// - &"123"[2] -> 0
10237/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +000010238static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +000010239 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +000010240 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +000010241 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +000010242 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +000010243 // If this is an arrow operator, the address is an offset from
10244 // the base's value, so the object the base refers to is
10245 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +000010246 if (cast<MemberExpr>(E)->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +000010247 return nullptr;
Eli Friedman3a1e6922009-04-20 08:23:18 +000010248 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +000010249 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +000010250 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +000010251 // FIXME: This code shouldn't be necessary! We should catch the implicit
10252 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +000010253 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10254 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10255 if (ICE->getSubExpr()->getType()->isArrayType())
10256 return getPrimaryDecl(ICE->getSubExpr());
10257 }
Craig Topperc3ec1492014-05-26 06:22:03 +000010258 return nullptr;
Anders Carlsson806700f2008-02-01 07:15:58 +000010259 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +000010260 case Stmt::UnaryOperatorClass: {
10261 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +000010262
Daniel Dunbarb692ef42008-08-04 20:02:37 +000010263 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010264 case UO_Real:
10265 case UO_Imag:
10266 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +000010267 return getPrimaryDecl(UO->getSubExpr());
10268 default:
Craig Topperc3ec1492014-05-26 06:22:03 +000010269 return nullptr;
Daniel Dunbarb692ef42008-08-04 20:02:37 +000010270 }
10271 }
Steve Naroff47500512007-04-19 23:00:49 +000010272 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +000010273 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +000010274 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +000010275 // If the result of an implicit cast is an l-value, we care about
10276 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +000010277 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +000010278 default:
Craig Topperc3ec1492014-05-26 06:22:03 +000010279 return nullptr;
Steve Naroff47500512007-04-19 23:00:49 +000010280 }
10281}
10282
Richard Trieu5f376f62011-09-07 21:46:33 +000010283namespace {
10284 enum {
10285 AO_Bit_Field = 0,
10286 AO_Vector_Element = 1,
10287 AO_Property_Expansion = 2,
10288 AO_Register_Variable = 3,
10289 AO_No_Error = 4
10290 };
10291}
Richard Trieu3fd7bb82011-09-02 00:47:55 +000010292/// \brief Diagnose invalid operand for address of operations.
10293///
10294/// \param Type The type of operand which cannot have its address taken.
Richard Trieu3fd7bb82011-09-02 00:47:55 +000010295static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10296 Expr *E, unsigned Type) {
10297 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10298}
10299
Steve Naroff47500512007-04-19 23:00:49 +000010300/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +000010301/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +000010302/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +000010303/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +000010304/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +000010305/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +000010306/// we allow the '&' but retain the overloaded-function type.
Richard Smithaf9de912013-07-11 02:26:56 +000010307QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
John McCall526ab472011-10-25 17:37:35 +000010308 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10309 if (PTy->getKind() == BuiltinType::Overload) {
David Majnemer0f328442013-07-05 06:23:33 +000010310 Expr *E = OrigOp.get()->IgnoreParens();
10311 if (!isa<OverloadExpr>(E)) {
10312 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
Richard Smithaf9de912013-07-11 02:26:56 +000010313 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
John McCall526ab472011-10-25 17:37:35 +000010314 << OrigOp.get()->getSourceRange();
10315 return QualType();
10316 }
David Majnemer66ad5742013-06-11 03:56:29 +000010317
David Majnemer0f328442013-07-05 06:23:33 +000010318 OverloadExpr *Ovl = cast<OverloadExpr>(E);
David Majnemer66ad5742013-06-11 03:56:29 +000010319 if (isa<UnresolvedMemberExpr>(Ovl))
Richard Smithaf9de912013-07-11 02:26:56 +000010320 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10321 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
David Majnemer66ad5742013-06-11 03:56:29 +000010322 << OrigOp.get()->getSourceRange();
10323 return QualType();
10324 }
10325
Richard Smithaf9de912013-07-11 02:26:56 +000010326 return Context.OverloadTy;
John McCall526ab472011-10-25 17:37:35 +000010327 }
10328
10329 if (PTy->getKind() == BuiltinType::UnknownAny)
Richard Smithaf9de912013-07-11 02:26:56 +000010330 return Context.UnknownAnyTy;
John McCall526ab472011-10-25 17:37:35 +000010331
10332 if (PTy->getKind() == BuiltinType::BoundMember) {
Richard Smithaf9de912013-07-11 02:26:56 +000010333 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +000010334 << OrigOp.get()->getSourceRange();
Douglas Gregor668d3622011-10-09 19:10:41 +000010335 return QualType();
10336 }
John McCall526ab472011-10-25 17:37:35 +000010337
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010338 OrigOp = CheckPlaceholderExpr(OrigOp.get());
John McCall526ab472011-10-25 17:37:35 +000010339 if (OrigOp.isInvalid()) return QualType();
John McCall0009fcc2011-04-26 20:42:42 +000010340 }
John McCall8d08b9b2010-08-27 09:08:28 +000010341
John McCall526ab472011-10-25 17:37:35 +000010342 if (OrigOp.get()->isTypeDependent())
Richard Smithaf9de912013-07-11 02:26:56 +000010343 return Context.DependentTy;
John McCall526ab472011-10-25 17:37:35 +000010344
10345 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +000010346
John McCall8d08b9b2010-08-27 09:08:28 +000010347 // Make sure to ignore parentheses in subsequent checks
John McCall526ab472011-10-25 17:37:35 +000010348 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +000010349
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +000010350 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10351 if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10352 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10353 return QualType();
10354 }
10355
Richard Smithaf9de912013-07-11 02:26:56 +000010356 if (getLangOpts().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +000010357 // Implement C99-only parts of addressof rules.
10358 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +000010359 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +000010360 // Per C99 6.5.3.2, the address of a deref always returns a valid result
10361 // (assuming the deref expression is valid).
10362 return uOp->getSubExpr()->getType();
10363 }
10364 // Technically, there should be a check for array subscript
10365 // expressions here, but the result of one is always an lvalue anyway.
10366 }
John McCallf3a88602011-02-03 08:15:49 +000010367 ValueDecl *dcl = getPrimaryDecl(op);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010368
10369 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10370 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10371 op->getLocStart()))
10372 return QualType();
10373
Richard Smithaf9de912013-07-11 02:26:56 +000010374 Expr::LValueClassification lval = op->ClassifyLValue(Context);
Richard Trieu5f376f62011-09-07 21:46:33 +000010375 unsigned AddressOfError = AO_No_Error;
Nuno Lopes17f345f2008-12-16 22:59:47 +000010376
Richard Smithc084bd282013-02-02 02:14:45 +000010377 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
Richard Smithaf9de912013-07-11 02:26:56 +000010378 bool sfinae = (bool)isSFINAEContext();
10379 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10380 : diag::ext_typecheck_addrof_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +000010381 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +000010382 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +000010383 return QualType();
Richard Smith9f8400e2013-05-01 19:00:39 +000010384 // Materialize the temporary as an lvalue so that we can take its address.
Richard Smithaf9de912013-07-11 02:26:56 +000010385 OrigOp = op = new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010386 MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
John McCall8d08b9b2010-08-27 09:08:28 +000010387 } else if (isa<ObjCSelectorExpr>(op)) {
Richard Smithaf9de912013-07-11 02:26:56 +000010388 return Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +000010389 } else if (lval == Expr::LV_MemberFunction) {
10390 // If it's an instance method, make a member pointer.
10391 // The expression must have exactly the form &A::foo.
10392
10393 // If the underlying expression isn't a decl ref, give up.
10394 if (!isa<DeclRefExpr>(op)) {
Richard Smithaf9de912013-07-11 02:26:56 +000010395 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +000010396 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +000010397 return QualType();
10398 }
10399 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10400 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10401
10402 // The id-expression was parenthesized.
John McCall526ab472011-10-25 17:37:35 +000010403 if (OrigOp.get() != DRE) {
Richard Smithaf9de912013-07-11 02:26:56 +000010404 Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +000010405 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +000010406
10407 // The method was named without a qualifier.
10408 } else if (!DRE->getQualifier()) {
David Blaikiec2ff8e12012-10-11 22:55:07 +000010409 if (MD->getParent()->getName().empty())
Richard Smithaf9de912013-07-11 02:26:56 +000010410 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
David Blaikiec2ff8e12012-10-11 22:55:07 +000010411 << op->getSourceRange();
10412 else {
10413 SmallString<32> Str;
10414 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
Richard Smithaf9de912013-07-11 02:26:56 +000010415 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
David Blaikiec2ff8e12012-10-11 22:55:07 +000010416 << op->getSourceRange()
10417 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10418 }
John McCall8d08b9b2010-08-27 09:08:28 +000010419 }
10420
Benjamin Kramer915d1692013-10-10 09:44:41 +000010421 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10422 if (isa<CXXDestructorDecl>(MD))
10423 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10424
David Majnemer1cdd96d2014-01-17 09:01:00 +000010425 QualType MPTy = Context.getMemberPointerType(
10426 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
Richard Smithdb0ac552015-12-18 22:40:25 +000010427 // Under the MS ABI, lock down the inheritance model now.
David Majnemer1cdd96d2014-01-17 09:01:00 +000010428 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
Richard Smithdb0ac552015-12-18 22:40:25 +000010429 (void)isCompleteType(OpLoc, MPTy);
David Majnemer1cdd96d2014-01-17 09:01:00 +000010430 return MPTy;
John McCall8d08b9b2010-08-27 09:08:28 +000010431 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +000010432 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +000010433 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +000010434 if (!op->getType()->isFunctionType()) {
John McCall526ab472011-10-25 17:37:35 +000010435 // Use a special diagnostic for loads from property references.
John McCallfe96e0b2011-11-06 09:01:30 +000010436 if (isa<PseudoObjectExpr>(op)) {
John McCall526ab472011-10-25 17:37:35 +000010437 AddressOfError = AO_Property_Expansion;
10438 } else {
Richard Smithaf9de912013-07-11 02:26:56 +000010439 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Richard Smithc084bd282013-02-02 02:14:45 +000010440 << op->getType() << op->getSourceRange();
John McCall526ab472011-10-25 17:37:35 +000010441 return QualType();
10442 }
Steve Naroff35d85152007-05-07 00:24:15 +000010443 }
John McCall086a4642010-11-24 05:12:34 +000010444 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +000010445 // The operand cannot be a bit-field
Richard Trieu5f376f62011-09-07 21:46:33 +000010446 AddressOfError = AO_Bit_Field;
John McCall086a4642010-11-24 05:12:34 +000010447 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +000010448 // The operand cannot be an element of a vector
Richard Trieu5f376f62011-09-07 21:46:33 +000010449 AddressOfError = AO_Vector_Element;
Steve Naroffb96e4ab62008-02-29 23:30:25 +000010450 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +000010451 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +000010452 // with the register storage-class specifier.
10453 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +000010454 // in C++ it is not error to take address of a register
10455 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +000010456 if (vd->getStorageClass() == SC_Register &&
Richard Smithaf9de912013-07-11 02:26:56 +000010457 !getLangOpts().CPlusPlus) {
Richard Trieu5f376f62011-09-07 21:46:33 +000010458 AddressOfError = AO_Register_Variable;
Steve Naroff35d85152007-05-07 00:24:15 +000010459 }
Reid Kleckner85c7e0a2015-02-24 20:29:40 +000010460 } else if (isa<MSPropertyDecl>(dcl)) {
10461 AddressOfError = AO_Property_Expansion;
John McCalld14a8642009-11-21 08:51:07 +000010462 } else if (isa<FunctionTemplateDecl>(dcl)) {
Richard Smithaf9de912013-07-11 02:26:56 +000010463 return Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +000010464 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +000010465 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +000010466 // Could be a pointer to member, though, if there is an explicit
10467 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +000010468 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +000010469 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +000010470 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +000010471 if (dcl->getType()->isReferenceType()) {
Richard Smithaf9de912013-07-11 02:26:56 +000010472 Diag(OpLoc,
10473 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +000010474 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +000010475 return QualType();
10476 }
Mike Stump11289f42009-09-09 15:08:12 +000010477
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +000010478 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10479 Ctx = Ctx->getParent();
David Majnemer1cdd96d2014-01-17 09:01:00 +000010480
10481 QualType MPTy = Context.getMemberPointerType(
10482 op->getType(),
10483 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Richard Smithdb0ac552015-12-18 22:40:25 +000010484 // Under the MS ABI, lock down the inheritance model now.
David Majnemer1cdd96d2014-01-17 09:01:00 +000010485 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
Richard Smithdb0ac552015-12-18 22:40:25 +000010486 (void)isCompleteType(OpLoc, MPTy);
David Majnemer1cdd96d2014-01-17 09:01:00 +000010487 return MPTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +000010488 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +000010489 }
Eli Friedman755c0c92011-08-26 20:28:17 +000010490 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikie83d382b2011-09-23 05:06:16 +000010491 llvm_unreachable("Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +000010492 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010493
Richard Trieu5f376f62011-09-07 21:46:33 +000010494 if (AddressOfError != AO_No_Error) {
Richard Smithaf9de912013-07-11 02:26:56 +000010495 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
Richard Trieu5f376f62011-09-07 21:46:33 +000010496 return QualType();
10497 }
10498
Eli Friedmance7f9002009-05-16 23:27:50 +000010499 if (lval == Expr::LV_IncompleteVoidType) {
10500 // Taking the address of a void variable is technically illegal, but we
10501 // allow it in cases which are otherwise valid.
10502 // Example: "extern void x; void* y = &x;".
Richard Smithaf9de912013-07-11 02:26:56 +000010503 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +000010504 }
10505
Steve Naroff47500512007-04-19 23:00:49 +000010506 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +000010507 if (op->getType()->isObjCObjectType())
Richard Smithaf9de912013-07-11 02:26:56 +000010508 return Context.getObjCObjectPointerType(op->getType());
Xiuli Pan89307aa2016-02-24 04:29:36 +000010509
10510 // OpenCL v2.0 s6.12.5 - The unary operators & cannot be used with a block.
10511 if (getLangOpts().OpenCL && OrigOp.get()->getType()->isBlockPointerType()) {
10512 Diag(OpLoc, diag::err_typecheck_unary_expr) << OrigOp.get()->getType()
10513 << op->getSourceRange();
10514 return QualType();
10515 }
10516
Richard Smithaf9de912013-07-11 02:26:56 +000010517 return Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +000010518}
10519
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010520static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10521 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10522 if (!DRE)
10523 return;
10524 const Decl *D = DRE->getDecl();
10525 if (!D)
10526 return;
10527 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10528 if (!Param)
10529 return;
10530 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
Aaron Ballman2521f362014-12-11 19:35:42 +000010531 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010532 return;
10533 if (FunctionScopeInfo *FD = S.getCurFunction())
10534 if (!FD->ModifiedNonNullParams.count(Param))
10535 FD->ModifiedNonNullParams.insert(Param);
10536}
10537
Chris Lattner9156f1b2010-07-05 19:17:26 +000010538/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +000010539static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10540 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000010541 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +000010542 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000010543
John Wiegley01296292011-04-08 18:41:53 +000010544 ExprResult ConvResult = S.UsualUnaryConversions(Op);
10545 if (ConvResult.isInvalid())
10546 return QualType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010547 Op = ConvResult.get();
Chris Lattner9156f1b2010-07-05 19:17:26 +000010548 QualType OpTy = Op->getType();
10549 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +000010550
10551 if (isa<CXXReinterpretCastExpr>(Op)) {
10552 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10553 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10554 Op->getSourceRange());
10555 }
10556
Chris Lattner9156f1b2010-07-05 19:17:26 +000010557 if (const PointerType *PT = OpTy->getAs<PointerType>())
Xiuli Pan89307aa2016-02-24 04:29:36 +000010558 {
Chris Lattner9156f1b2010-07-05 19:17:26 +000010559 Result = PT->getPointeeType();
Xiuli Pan89307aa2016-02-24 04:29:36 +000010560 // OpenCL v2.0 s6.12.5 - The unary operators * cannot be used with a block.
10561 if (S.getLangOpts().OpenCLVersion >= 200 && Result->isBlockPointerType()) {
10562 S.Diag(OpLoc, diag::err_opencl_dereferencing) << OpTy
10563 << Op->getSourceRange();
10564 return QualType();
10565 }
10566 }
Chris Lattner9156f1b2010-07-05 19:17:26 +000010567 else if (const ObjCObjectPointerType *OPT =
10568 OpTy->getAs<ObjCObjectPointerType>())
10569 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +000010570 else {
John McCall3aef3d82011-04-10 19:13:55 +000010571 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +000010572 if (PR.isInvalid()) return QualType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010573 if (PR.get() != Op)
10574 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +000010575 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000010576
Chris Lattner9156f1b2010-07-05 19:17:26 +000010577 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +000010578 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +000010579 << OpTy << Op->getSourceRange();
10580 return QualType();
10581 }
John McCall4bc41ae2010-11-18 19:01:18 +000010582
Richard Smith80877c22014-05-07 21:53:27 +000010583 // Note that per both C89 and C99, indirection is always legal, even if Result
10584 // is an incomplete type or void. It would be possible to warn about
10585 // dereferencing a void pointer, but it's completely well-defined, and such a
10586 // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10587 // for pointers to 'void' but is fine for any other pointer type:
10588 //
10589 // C++ [expr.unary.op]p1:
10590 // [...] the expression to which [the unary * operator] is applied shall
10591 // be a pointer to an object type, or a pointer to a function type
10592 if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10593 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10594 << OpTy << Op->getSourceRange();
10595
John McCall4bc41ae2010-11-18 19:01:18 +000010596 // Dereferences are usually l-values...
10597 VK = VK_LValue;
10598
10599 // ...except that certain expressions are never l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010600 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +000010601 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +000010602
10603 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +000010604}
Steve Naroff218bc2b2007-05-04 21:54:46 +000010605
Richard Smith0f0af192014-11-08 05:07:16 +000010606BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +000010607 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +000010608 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +000010609 default: llvm_unreachable("Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +000010610 case tok::periodstar: Opc = BO_PtrMemD; break;
10611 case tok::arrowstar: Opc = BO_PtrMemI; break;
10612 case tok::star: Opc = BO_Mul; break;
10613 case tok::slash: Opc = BO_Div; break;
10614 case tok::percent: Opc = BO_Rem; break;
10615 case tok::plus: Opc = BO_Add; break;
10616 case tok::minus: Opc = BO_Sub; break;
10617 case tok::lessless: Opc = BO_Shl; break;
10618 case tok::greatergreater: Opc = BO_Shr; break;
10619 case tok::lessequal: Opc = BO_LE; break;
10620 case tok::less: Opc = BO_LT; break;
10621 case tok::greaterequal: Opc = BO_GE; break;
10622 case tok::greater: Opc = BO_GT; break;
10623 case tok::exclaimequal: Opc = BO_NE; break;
10624 case tok::equalequal: Opc = BO_EQ; break;
10625 case tok::amp: Opc = BO_And; break;
10626 case tok::caret: Opc = BO_Xor; break;
10627 case tok::pipe: Opc = BO_Or; break;
10628 case tok::ampamp: Opc = BO_LAnd; break;
10629 case tok::pipepipe: Opc = BO_LOr; break;
10630 case tok::equal: Opc = BO_Assign; break;
10631 case tok::starequal: Opc = BO_MulAssign; break;
10632 case tok::slashequal: Opc = BO_DivAssign; break;
10633 case tok::percentequal: Opc = BO_RemAssign; break;
10634 case tok::plusequal: Opc = BO_AddAssign; break;
10635 case tok::minusequal: Opc = BO_SubAssign; break;
10636 case tok::lesslessequal: Opc = BO_ShlAssign; break;
10637 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
10638 case tok::ampequal: Opc = BO_AndAssign; break;
10639 case tok::caretequal: Opc = BO_XorAssign; break;
10640 case tok::pipeequal: Opc = BO_OrAssign; break;
10641 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +000010642 }
10643 return Opc;
10644}
10645
John McCalle3027922010-08-25 11:45:40 +000010646static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +000010647 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +000010648 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +000010649 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +000010650 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +000010651 case tok::plusplus: Opc = UO_PreInc; break;
10652 case tok::minusminus: Opc = UO_PreDec; break;
10653 case tok::amp: Opc = UO_AddrOf; break;
10654 case tok::star: Opc = UO_Deref; break;
10655 case tok::plus: Opc = UO_Plus; break;
10656 case tok::minus: Opc = UO_Minus; break;
10657 case tok::tilde: Opc = UO_Not; break;
10658 case tok::exclaim: Opc = UO_LNot; break;
10659 case tok::kw___real: Opc = UO_Real; break;
10660 case tok::kw___imag: Opc = UO_Imag; break;
10661 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +000010662 }
10663 return Opc;
10664}
10665
Chandler Carruthe0cee6a2011-01-04 06:52:15 +000010666/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
10667/// This warning is only emitted for builtin assignment operations. It is also
10668/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +000010669static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +000010670 SourceLocation OpLoc) {
10671 if (!S.ActiveTemplateInstantiations.empty())
10672 return;
10673 if (OpLoc.isInvalid() || OpLoc.isMacroID())
10674 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +000010675 LHSExpr = LHSExpr->IgnoreParenImpCasts();
10676 RHSExpr = RHSExpr->IgnoreParenImpCasts();
10677 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10678 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10679 if (!LHSDeclRef || !RHSDeclRef ||
10680 LHSDeclRef->getLocation().isMacroID() ||
10681 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +000010682 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +000010683 const ValueDecl *LHSDecl =
10684 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
10685 const ValueDecl *RHSDecl =
10686 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
10687 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +000010688 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +000010689 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +000010690 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +000010691 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +000010692 if (RefTy->getPointeeType().isVolatileQualified())
10693 return;
10694
10695 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +000010696 << LHSDeclRef->getType()
10697 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +000010698}
10699
Ted Kremenekebeabab2013-04-22 22:46:52 +000010700/// Check if a bitwise-& is performed on an Objective-C pointer. This
10701/// is usually indicative of introspection within the Objective-C pointer.
10702static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
10703 SourceLocation OpLoc) {
10704 if (!S.getLangOpts().ObjC1)
10705 return;
10706
Craig Topperc3ec1492014-05-26 06:22:03 +000010707 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
Ted Kremenekebeabab2013-04-22 22:46:52 +000010708 const Expr *LHS = L.get();
10709 const Expr *RHS = R.get();
10710
10711 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10712 ObjCPointerExpr = LHS;
10713 OtherExpr = RHS;
10714 }
10715 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10716 ObjCPointerExpr = RHS;
10717 OtherExpr = LHS;
10718 }
10719
10720 // This warning is deliberately made very specific to reduce false
10721 // positives with logic that uses '&' for hashing. This logic mainly
10722 // looks for code trying to introspect into tagged pointers, which
10723 // code should generally never do.
10724 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
Ted Kremenek009d61d2013-06-24 21:35:39 +000010725 unsigned Diag = diag::warn_objc_pointer_masking;
10726 // Determine if we are introspecting the result of performSelectorXXX.
10727 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
10728 // Special case messages to -performSelector and friends, which
10729 // can return non-pointer values boxed in a pointer value.
10730 // Some clients may wish to silence warnings in this subcase.
10731 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
10732 Selector S = ME->getSelector();
10733 StringRef SelArg0 = S.getNameForSlot(0);
10734 if (SelArg0.startswith("performSelector"))
10735 Diag = diag::warn_objc_pointer_masking_performSelector;
10736 }
10737
10738 S.Diag(OpLoc, Diag)
Ted Kremenekebeabab2013-04-22 22:46:52 +000010739 << ObjCPointerExpr->getSourceRange();
10740 }
10741}
10742
Kaelyn Takata7a503692015-01-27 22:01:39 +000010743static NamedDecl *getDeclFromExpr(Expr *E) {
10744 if (!E)
10745 return nullptr;
10746 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
10747 return DRE->getDecl();
10748 if (auto *ME = dyn_cast<MemberExpr>(E))
10749 return ME->getMemberDecl();
10750 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
10751 return IRE->getDecl();
10752 return nullptr;
10753}
10754
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010755/// CreateBuiltinBinOp - Creates a new built-in binary operation with
10756/// operator @p Opc at location @c TokLoc. This routine only supports
10757/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +000010758ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +000010759 BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +000010760 Expr *LHSExpr, Expr *RHSExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010761 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl67766732012-02-27 20:34:02 +000010762 // The syntax only allows initializer lists on the RHS of assignment,
10763 // so we don't need to worry about accepting invalid code for
10764 // non-assignment operators.
10765 // C++11 5.17p9:
10766 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
10767 // of x = {} is x = T().
10768 InitializationKind Kind =
10769 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
10770 InitializedEntity Entity =
10771 InitializedEntity::InitializeTemporary(LHSExpr->getType());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000010772 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010773 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
Sebastian Redl67766732012-02-27 20:34:02 +000010774 if (Init.isInvalid())
10775 return Init;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010776 RHSExpr = Init.get();
Sebastian Redl67766732012-02-27 20:34:02 +000010777 }
10778
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010779 ExprResult LHS = LHSExpr, RHS = RHSExpr;
Eli Friedman8b7b1b12009-03-28 01:22:36 +000010780 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +000010781 // The following two variables are used for compound assignment operators
10782 QualType CompLHSTy; // Type of LHS after promotions for computation
10783 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +000010784 ExprValueKind VK = VK_RValue;
10785 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010786
Kaelyn Takata15867822014-11-21 18:48:04 +000010787 if (!getLangOpts().CPlusPlus) {
10788 // C cannot handle TypoExpr nodes on either side of a binop because it
10789 // doesn't handle dependent types properly, so make sure any TypoExprs have
10790 // been dealt with before checking the operands.
10791 LHS = CorrectDelayedTyposInExpr(LHSExpr);
Kaelyn Takata7a503692015-01-27 22:01:39 +000010792 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
10793 if (Opc != BO_Assign)
10794 return ExprResult(E);
10795 // Avoid correcting the RHS to the same Expr as the LHS.
10796 Decl *D = getDeclFromExpr(E);
10797 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
10798 });
Kaelyn Takata15867822014-11-21 18:48:04 +000010799 if (!LHS.isUsable() || !RHS.isUsable())
10800 return ExprError();
10801 }
10802
Anastasia Stulovade0e4242015-09-30 13:18:52 +000010803 if (getLangOpts().OpenCL) {
10804 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
10805 // the ATOMIC_VAR_INIT macro.
10806 if (LHSExpr->getType()->isAtomicType() ||
10807 RHSExpr->getType()->isAtomicType()) {
10808 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
10809 if (BO_Assign == Opc)
10810 Diag(OpLoc, diag::err_atomic_init_constant) << SR;
10811 else
10812 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
10813 return ExprError();
10814 }
10815 }
10816
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010817 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +000010818 case BO_Assign:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010819 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikiebbafb8a2012-03-11 07:00:24 +000010820 if (getLangOpts().CPlusPlus &&
Richard Trieu4a287fb2011-09-07 01:49:20 +000010821 LHS.get()->getObjectKind() != OK_ObjCProperty) {
10822 VK = LHS.get()->getValueKind();
10823 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +000010824 }
Richard Trieu17ddb822015-01-10 06:04:18 +000010825 if (!ResultTy.isNull()) {
Richard Trieu4a287fb2011-09-07 01:49:20 +000010826 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010827 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
Richard Trieu17ddb822015-01-10 06:04:18 +000010828 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010829 RecordModifiableNonNullParam(*this, LHS.get());
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010830 break;
John McCalle3027922010-08-25 11:45:40 +000010831 case BO_PtrMemD:
10832 case BO_PtrMemI:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010833 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +000010834 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +000010835 break;
John McCalle3027922010-08-25 11:45:40 +000010836 case BO_Mul:
10837 case BO_Div:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010838 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +000010839 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010840 break;
John McCalle3027922010-08-25 11:45:40 +000010841 case BO_Rem:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010842 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010843 break;
John McCalle3027922010-08-25 11:45:40 +000010844 case BO_Add:
Nico Weberccec40d2012-03-02 22:01:22 +000010845 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010846 break;
John McCalle3027922010-08-25 11:45:40 +000010847 case BO_Sub:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010848 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010849 break;
John McCalle3027922010-08-25 11:45:40 +000010850 case BO_Shl:
10851 case BO_Shr:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010852 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010853 break;
John McCalle3027922010-08-25 11:45:40 +000010854 case BO_LE:
10855 case BO_LT:
10856 case BO_GE:
10857 case BO_GT:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010858 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010859 break;
John McCalle3027922010-08-25 11:45:40 +000010860 case BO_EQ:
10861 case BO_NE:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010862 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010863 break;
John McCalle3027922010-08-25 11:45:40 +000010864 case BO_And:
Ted Kremenekebeabab2013-04-22 22:46:52 +000010865 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
John McCalle3027922010-08-25 11:45:40 +000010866 case BO_Xor:
10867 case BO_Or:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010868 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010869 break;
John McCalle3027922010-08-25 11:45:40 +000010870 case BO_LAnd:
10871 case BO_LOr:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010872 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010873 break;
John McCalle3027922010-08-25 11:45:40 +000010874 case BO_MulAssign:
10875 case BO_DivAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010876 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +000010877 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +000010878 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +000010879 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10880 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010881 break;
John McCalle3027922010-08-25 11:45:40 +000010882 case BO_RemAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010883 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +000010884 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +000010885 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10886 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010887 break;
John McCalle3027922010-08-25 11:45:40 +000010888 case BO_AddAssign:
Nico Weberccec40d2012-03-02 22:01:22 +000010889 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu4a287fb2011-09-07 01:49:20 +000010890 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10891 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010892 break;
John McCalle3027922010-08-25 11:45:40 +000010893 case BO_SubAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010894 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
10895 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10896 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010897 break;
John McCalle3027922010-08-25 11:45:40 +000010898 case BO_ShlAssign:
10899 case BO_ShrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010900 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +000010901 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +000010902 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10903 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010904 break;
John McCalle3027922010-08-25 11:45:40 +000010905 case BO_AndAssign:
Nikola Smiljanic292b5ce2014-05-30 00:15:04 +000010906 case BO_OrAssign: // fallthrough
Craig Topperbd44cd92015-12-08 04:33:04 +000010907 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
John McCalle3027922010-08-25 11:45:40 +000010908 case BO_XorAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010909 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +000010910 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +000010911 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10912 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010913 break;
John McCalle3027922010-08-25 11:45:40 +000010914 case BO_Comma:
Richard Trieu4a287fb2011-09-07 01:49:20 +000010915 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikiebbafb8a2012-03-11 07:00:24 +000010916 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu4a287fb2011-09-07 01:49:20 +000010917 VK = RHS.get()->getValueKind();
10918 OK = RHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +000010919 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010920 break;
10921 }
Richard Trieu4a287fb2011-09-07 01:49:20 +000010922 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +000010923 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010924
10925 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu4a287fb2011-09-07 01:49:20 +000010926 CheckArrayAccess(LHS.get());
10927 CheckArrayAccess(RHS.get());
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010928
Fariborz Jahanian06bb7f72013-03-28 19:50:55 +000010929 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
10930 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
10931 &Context.Idents.get("object_setClass"),
10932 SourceLocation(), LookupOrdinaryName);
10933 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
Craig Topper07fa1762015-11-15 02:31:46 +000010934 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
Fariborz Jahanian06bb7f72013-03-28 19:50:55 +000010935 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
10936 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
10937 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
10938 FixItHint::CreateInsertion(RHSLocEnd, ")");
10939 }
10940 else
10941 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
10942 }
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +000010943 else if (const ObjCIvarRefExpr *OIRE =
10944 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +000010945 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +000010946
Eli Friedman8b7b1b12009-03-28 01:22:36 +000010947 if (CompResultTy.isNull())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010948 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
10949 OK, OpLoc, FPFeatures.fp_contract);
David Blaikiebbafb8a2012-03-11 07:00:24 +000010950 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieucfc491d2011-08-02 04:35:43 +000010951 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +000010952 VK = VK_LValue;
Richard Trieu4a287fb2011-09-07 01:49:20 +000010953 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +000010954 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010955 return new (Context) CompoundAssignOperator(
10956 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
10957 OpLoc, FPFeatures.fp_contract);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000010958}
10959
Sebastian Redl44615072009-10-27 12:10:02 +000010960/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
10961/// operators are mixed in a way that suggests that the programmer forgot that
10962/// comparison operators have higher precedence. The most typical example of
10963/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +000010964static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +000010965 SourceLocation OpLoc, Expr *LHSExpr,
10966 Expr *RHSExpr) {
Eli Friedman37feb2d2012-11-15 00:29:07 +000010967 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
10968 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +000010969
Craig Topperf942fde2015-12-12 06:30:48 +000010970 // Check that one of the sides is a comparison operator and the other isn't.
Eli Friedman37feb2d2012-11-15 00:29:07 +000010971 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
10972 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
Craig Topperf942fde2015-12-12 06:30:48 +000010973 if (isLeftComp == isRightComp)
Sebastian Redl43028242009-10-26 15:24:15 +000010974 return;
10975
10976 // Bitwise operations are sometimes used as eager logical ops.
10977 // Don't diagnose this.
Eli Friedman37feb2d2012-11-15 00:29:07 +000010978 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
10979 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
Craig Topperf942fde2015-12-12 06:30:48 +000010980 if (isLeftBitwise || isRightBitwise)
Sebastian Redl43028242009-10-26 15:24:15 +000010981 return;
10982
Richard Trieu4a287fb2011-09-07 01:49:20 +000010983 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
10984 OpLoc)
10985 : SourceRange(OpLoc, RHSExpr->getLocEnd());
Eli Friedman37feb2d2012-11-15 00:29:07 +000010986 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
Richard Trieu73088052011-08-10 22:41:34 +000010987 SourceRange ParensRange = isLeftComp ?
Eli Friedman37feb2d2012-11-15 00:29:07 +000010988 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
Richard Trieu7ec1a312014-08-23 00:30:57 +000010989 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
Richard Trieu73088052011-08-10 22:41:34 +000010990
10991 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
Eli Friedman37feb2d2012-11-15 00:29:07 +000010992 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
Richard Trieu73088052011-08-10 22:41:34 +000010993 SuggestParentheses(Self, OpLoc,
David Blaikiedac86fd2012-10-08 01:19:49 +000010994 Self.PDiag(diag::note_precedence_silence) << OpStr,
Nico Webercdfb1ae2012-06-03 07:07:00 +000010995 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu73088052011-08-10 22:41:34 +000010996 SuggestParentheses(Self, OpLoc,
Eli Friedman37feb2d2012-11-15 00:29:07 +000010997 Self.PDiag(diag::note_precedence_bitwise_first)
10998 << BinaryOperator::getOpcodeStr(Opc),
Richard Trieu73088052011-08-10 22:41:34 +000010999 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +000011000}
11001
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +000011002/// \brief It accepts a '&&' expr that is inside a '||' one.
11003/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11004/// in parentheses.
11005static void
11006EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +000011007 BinaryOperator *Bop) {
11008 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +000011009 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11010 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +000011011 SuggestParentheses(Self, Bop->getOperatorLoc(),
David Blaikiedac86fd2012-10-08 01:19:49 +000011012 Self.PDiag(diag::note_precedence_silence)
11013 << Bop->getOpcodeStr(),
Chandler Carruthb00e8c02011-06-16 01:05:14 +000011014 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +000011015}
11016
11017/// \brief Returns true if the given expression can be evaluated as a constant
11018/// 'true'.
11019static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11020 bool Res;
Richard Smitha6c87032013-08-19 22:06:05 +000011021 return !E->isValueDependent() &&
11022 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +000011023}
11024
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +000011025/// \brief Returns true if the given expression can be evaluated as a constant
11026/// 'false'.
11027static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11028 bool Res;
Richard Smitha6c87032013-08-19 22:06:05 +000011029 return !E->isValueDependent() &&
11030 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +000011031}
11032
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +000011033/// \brief Look for '&&' in the left hand of a '||' expr.
11034static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +000011035 Expr *LHSExpr, Expr *RHSExpr) {
11036 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +000011037 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +000011038 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +000011039 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +000011040 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +000011041 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11042 if (!EvaluatesAsTrue(S, Bop->getLHS()))
11043 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11044 } else if (Bop->getOpcode() == BO_LOr) {
11045 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11046 // If it's "a || b && 1 || c" we didn't warn earlier for
11047 // "a || b && 1", but warn now.
11048 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11049 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11050 }
11051 }
11052 }
11053}
11054
11055/// \brief Look for '&&' in the right hand of a '||' expr.
11056static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +000011057 Expr *LHSExpr, Expr *RHSExpr) {
11058 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +000011059 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +000011060 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +000011061 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +000011062 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +000011063 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11064 if (!EvaluatesAsTrue(S, Bop->getRHS()))
11065 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +000011066 }
11067 }
11068}
11069
Craig Topper84543b02015-12-13 05:41:41 +000011070/// \brief Look for bitwise op in the left or right hand of a bitwise op with
11071/// lower precedence and emit a diagnostic together with a fixit hint that wraps
11072/// the '&' expression in parentheses.
11073static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11074 SourceLocation OpLoc, Expr *SubExpr) {
11075 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11076 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11077 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11078 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11079 << Bop->getSourceRange() << OpLoc;
11080 SuggestParentheses(S, Bop->getOperatorLoc(),
11081 S.PDiag(diag::note_precedence_silence)
11082 << Bop->getOpcodeStr(),
11083 Bop->getSourceRange());
11084 }
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +000011085 }
11086}
11087
David Blaikie15f17cb2012-10-05 00:41:03 +000011088static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
David Blaikie82d3ab92012-10-19 18:26:06 +000011089 Expr *SubExpr, StringRef Shift) {
David Blaikie15f17cb2012-10-05 00:41:03 +000011090 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11091 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
David Blaikiedac86fd2012-10-08 01:19:49 +000011092 StringRef Op = Bop->getOpcodeStr();
David Blaikie15f17cb2012-10-05 00:41:03 +000011093 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
David Blaikie82d3ab92012-10-19 18:26:06 +000011094 << Bop->getSourceRange() << OpLoc << Shift << Op;
David Blaikie15f17cb2012-10-05 00:41:03 +000011095 SuggestParentheses(S, Bop->getOperatorLoc(),
David Blaikiedac86fd2012-10-08 01:19:49 +000011096 S.PDiag(diag::note_precedence_silence) << Op,
David Blaikie15f17cb2012-10-05 00:41:03 +000011097 Bop->getSourceRange());
11098 }
11099 }
11100}
11101
Richard Trieufe042e62013-04-17 02:12:45 +000011102static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11103 Expr *LHSExpr, Expr *RHSExpr) {
11104 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11105 if (!OCE)
11106 return;
11107
11108 FunctionDecl *FD = OCE->getDirectCallee();
11109 if (!FD || !FD->isOverloadedOperator())
11110 return;
11111
11112 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11113 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11114 return;
11115
11116 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11117 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11118 << (Kind == OO_LessLess);
Richard Trieufe042e62013-04-17 02:12:45 +000011119 SuggestParentheses(S, OCE->getOperatorLoc(),
11120 S.PDiag(diag::note_precedence_silence)
11121 << (Kind == OO_LessLess ? "<<" : ">>"),
11122 OCE->getSourceRange());
Richard Trieue0894972013-04-18 01:04:37 +000011123 SuggestParentheses(S, OpLoc,
11124 S.PDiag(diag::note_evaluate_comparison_first),
11125 SourceRange(OCE->getArg(1)->getLocStart(),
11126 RHSExpr->getLocEnd()));
Richard Trieufe042e62013-04-17 02:12:45 +000011127}
11128
Sebastian Redl43028242009-10-26 15:24:15 +000011129/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +000011130/// precedence.
John McCalle3027922010-08-25 11:45:40 +000011131static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +000011132 SourceLocation OpLoc, Expr *LHSExpr,
11133 Expr *RHSExpr){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +000011134 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +000011135 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieuf9bd0f52011-09-07 02:02:10 +000011136 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +000011137
11138 // Diagnose "arg1 & arg2 | arg3"
Craig Topper84543b02015-12-13 05:41:41 +000011139 if ((Opc == BO_Or || Opc == BO_Xor) &&
11140 !OpLoc.isMacroID()/* Don't warn in macros. */) {
11141 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11142 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +000011143 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +000011144
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +000011145 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11146 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +000011147 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +000011148 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11149 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +000011150 }
David Blaikie15f17cb2012-10-05 00:41:03 +000011151
11152 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11153 || Opc == BO_Shr) {
David Blaikie82d3ab92012-10-19 18:26:06 +000011154 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11155 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11156 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
David Blaikie15f17cb2012-10-05 00:41:03 +000011157 }
Richard Trieufe042e62013-04-17 02:12:45 +000011158
11159 // Warn on overloaded shift operators and comparisons, such as:
11160 // cout << 5 == 4;
11161 if (BinaryOperator::isComparisonOp(Opc))
11162 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +000011163}
11164
Steve Naroff218bc2b2007-05-04 21:54:46 +000011165// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +000011166ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +000011167 tok::TokenKind Kind,
Richard Trieuf9bd0f52011-09-07 02:02:10 +000011168 Expr *LHSExpr, Expr *RHSExpr) {
John McCalle3027922010-08-25 11:45:40 +000011169 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Craig Topperc3ec1492014-05-26 06:22:03 +000011170 assert(LHSExpr && "ActOnBinOp(): missing left expression");
11171 assert(RHSExpr && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +000011172
Sebastian Redl43028242009-10-26 15:24:15 +000011173 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieuf9bd0f52011-09-07 02:02:10 +000011174 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +000011175
Richard Trieuf9bd0f52011-09-07 02:02:10 +000011176 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor5287f092009-11-05 00:51:44 +000011177}
11178
John McCall526ab472011-10-25 17:37:35 +000011179/// Build an overloaded binary operator expression in the given scope.
11180static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11181 BinaryOperatorKind Opc,
11182 Expr *LHS, Expr *RHS) {
11183 // Find all of the overloaded operators visible from this
11184 // point. We perform both an operator-name lookup from the local
11185 // scope and an argument-dependent lookup based on the types of
11186 // the arguments.
11187 UnresolvedSet<16> Functions;
11188 OverloadedOperatorKind OverOp
11189 = BinaryOperator::getOverloadedOperator(Opc);
Richard Smith0daabd72014-09-23 20:31:39 +000011190 if (Sc && OverOp != OO_None && OverOp != OO_Equal)
John McCall526ab472011-10-25 17:37:35 +000011191 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11192 RHS->getType(), Functions);
11193
11194 // Build the (potentially-overloaded, potentially-dependent)
11195 // binary operation.
11196 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11197}
11198
John McCalldadc5752010-08-24 06:29:42 +000011199ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +000011200 BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +000011201 Expr *LHSExpr, Expr *RHSExpr) {
John McCall9a43e122011-10-28 01:04:34 +000011202 // We want to end up calling one of checkPseudoObjectAssignment
11203 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11204 // both expressions are overloadable or either is type-dependent),
11205 // or CreateBuiltinBinOp (in any other case). We also want to get
11206 // any placeholder types out of the way.
11207
John McCall526ab472011-10-25 17:37:35 +000011208 // Handle pseudo-objects in the LHS.
11209 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11210 // Assignments with a pseudo-object l-value need special analysis.
11211 if (pty->getKind() == BuiltinType::PseudoObject &&
11212 BinaryOperator::isAssignmentOp(Opc))
11213 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11214
11215 // Don't resolve overloads if the other type is overloadable.
11216 if (pty->getKind() == BuiltinType::Overload) {
11217 // We can't actually test that if we still have a placeholder,
11218 // though. Fortunately, none of the exceptions we see in that
John McCall9a43e122011-10-28 01:04:34 +000011219 // code below are valid when the LHS is an overload set. Note
11220 // that an overload set can be dependently-typed, but it never
11221 // instantiates to having an overloadable type.
John McCall526ab472011-10-25 17:37:35 +000011222 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11223 if (resolvedRHS.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011224 RHSExpr = resolvedRHS.get();
John McCall526ab472011-10-25 17:37:35 +000011225
John McCall9a43e122011-10-28 01:04:34 +000011226 if (RHSExpr->isTypeDependent() ||
11227 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +000011228 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11229 }
11230
11231 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11232 if (LHS.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011233 LHSExpr = LHS.get();
John McCall526ab472011-10-25 17:37:35 +000011234 }
11235
11236 // Handle pseudo-objects in the RHS.
11237 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11238 // An overload in the RHS can potentially be resolved by the type
11239 // being assigned to.
John McCall9a43e122011-10-28 01:04:34 +000011240 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11241 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11242 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11243
Eli Friedman419b1ff2012-01-17 21:27:43 +000011244 if (LHSExpr->getType()->isOverloadableType())
11245 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11246
John McCall526ab472011-10-25 17:37:35 +000011247 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCall9a43e122011-10-28 01:04:34 +000011248 }
John McCall526ab472011-10-25 17:37:35 +000011249
11250 // Don't resolve overloads if the other type is overloadable.
11251 if (pty->getKind() == BuiltinType::Overload &&
11252 LHSExpr->getType()->isOverloadableType())
11253 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11254
11255 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11256 if (!resolvedRHS.isUsable()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011257 RHSExpr = resolvedRHS.get();
John McCall526ab472011-10-25 17:37:35 +000011258 }
11259
David Blaikiebbafb8a2012-03-11 07:00:24 +000011260 if (getLangOpts().CPlusPlus) {
John McCall9a43e122011-10-28 01:04:34 +000011261 // If either expression is type-dependent, always build an
11262 // overloaded op.
11263 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11264 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011265
John McCall9a43e122011-10-28 01:04:34 +000011266 // Otherwise, build an overloaded op if either expression has an
11267 // overloadable type.
11268 if (LHSExpr->getType()->isOverloadableType() ||
11269 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +000011270 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb5d49352009-01-19 22:31:54 +000011271 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011272
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000011273 // Build a built-in binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +000011274 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Steve Naroff218bc2b2007-05-04 21:54:46 +000011275}
11276
John McCalldadc5752010-08-24 06:29:42 +000011277ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +000011278 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +000011279 Expr *InputExpr) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011280 ExprResult Input = InputExpr;
John McCall7decc9e2010-11-18 06:31:45 +000011281 ExprValueKind VK = VK_RValue;
11282 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +000011283 QualType resultType;
Anastasia Stulovade0e4242015-09-30 13:18:52 +000011284 if (getLangOpts().OpenCL) {
11285 // The only legal unary operation for atomics is '&'.
11286 if (Opc != UO_AddrOf && InputExpr->getType()->isAtomicType()) {
11287 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11288 << InputExpr->getType()
11289 << Input.get()->getSourceRange());
11290 }
11291 }
Steve Naroff35d85152007-05-07 00:24:15 +000011292 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +000011293 case UO_PreInc:
11294 case UO_PreDec:
11295 case UO_PostInc:
11296 case UO_PostDec:
David Majnemer74242432014-07-31 04:52:13 +000011297 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11298 OpLoc,
John McCalle3027922010-08-25 11:45:40 +000011299 Opc == UO_PreInc ||
11300 Opc == UO_PostInc,
11301 Opc == UO_PreInc ||
11302 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +000011303 break;
John McCalle3027922010-08-25 11:45:40 +000011304 case UO_AddrOf:
Richard Smithaf9de912013-07-11 02:26:56 +000011305 resultType = CheckAddressOfOperand(Input, OpLoc);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011306 RecordModifiableNonNullParam(*this, InputExpr);
Steve Naroff35d85152007-05-07 00:24:15 +000011307 break;
John McCall31996342011-04-07 08:22:57 +000011308 case UO_Deref: {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011309 Input = DefaultFunctionArrayLvalueConversion(Input.get());
Eli Friedman34866c72012-08-31 00:14:07 +000011310 if (Input.isInvalid()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011311 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +000011312 break;
John McCall31996342011-04-07 08:22:57 +000011313 }
John McCalle3027922010-08-25 11:45:40 +000011314 case UO_Plus:
11315 case UO_Minus:
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011316 Input = UsualUnaryConversions(Input.get());
John Wiegley01296292011-04-08 18:41:53 +000011317 if (Input.isInvalid()) return ExprError();
11318 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000011319 if (resultType->isDependentType())
11320 break;
Ulrich Weigand3c5038a2015-07-30 14:08:36 +000011321 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11322 break;
11323 else if (resultType->isVectorType() &&
11324 // The z vector extensions don't allow + or - with bool vectors.
11325 (!Context.getLangOpts().ZVector ||
11326 resultType->getAs<VectorType>()->getVectorKind() !=
11327 VectorType::AltiVecBool))
Douglas Gregord08452f2008-11-19 15:42:04 +000011328 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +000011329 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +000011330 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +000011331 resultType->isPointerType())
11332 break;
11333
Sebastian Redlc215cfc2009-01-19 00:08:26 +000011334 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +000011335 << resultType << Input.get()->getSourceRange());
11336
John McCalle3027922010-08-25 11:45:40 +000011337 case UO_Not: // bitwise complement
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011338 Input = UsualUnaryConversions(Input.get());
Joey Gouly7d00f002013-02-21 11:49:56 +000011339 if (Input.isInvalid())
11340 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011341 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000011342 if (resultType->isDependentType())
11343 break;
Chris Lattner0d707612008-07-25 23:52:49 +000011344 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11345 if (resultType->isComplexType() || resultType->isComplexIntegerType())
11346 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +000011347 Diag(OpLoc, diag::ext_integer_complement_complex)
Joey Gouly7d00f002013-02-21 11:49:56 +000011348 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +000011349 else if (resultType->hasIntegerRepresentation())
11350 break;
Joey Gouly7d00f002013-02-21 11:49:56 +000011351 else if (resultType->isExtVectorType()) {
11352 if (Context.getLangOpts().OpenCL) {
11353 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11354 // on vector float types.
11355 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11356 if (!T->isIntegerType())
11357 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11358 << resultType << Input.get()->getSourceRange());
11359 }
11360 break;
11361 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +000011362 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
Joey Gouly7d00f002013-02-21 11:49:56 +000011363 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +000011364 }
Steve Naroff35d85152007-05-07 00:24:15 +000011365 break;
John Wiegley01296292011-04-08 18:41:53 +000011366
John McCalle3027922010-08-25 11:45:40 +000011367 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +000011368 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011369 Input = DefaultFunctionArrayLvalueConversion(Input.get());
John Wiegley01296292011-04-08 18:41:53 +000011370 if (Input.isInvalid()) return ExprError();
11371 resultType = Input.get()->getType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000011372
11373 // Though we still have to promote half FP to float...
Joey Goulydd7f4562013-01-23 11:56:20 +000011374 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011375 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000011376 resultType = Context.FloatTy;
11377 }
11378
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000011379 if (resultType->isDependentType())
11380 break;
Alp Tokerc620cab2014-01-20 07:20:22 +000011381 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
Abramo Bagnara7ccce982011-04-07 09:26:19 +000011382 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikiebbafb8a2012-03-11 07:00:24 +000011383 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara7ccce982011-04-07 09:26:19 +000011384 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11385 // operand contextually converted to bool.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011386 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
John Wiegley01296292011-04-08 18:41:53 +000011387 ScalarTypeToBooleanCastKind(resultType));
Joey Gouly7d00f002013-02-21 11:49:56 +000011388 } else if (Context.getLangOpts().OpenCL &&
11389 Context.getLangOpts().OpenCLVersion < 120) {
11390 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11391 // operate on scalar float types.
11392 if (!resultType->isIntegerType())
11393 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11394 << resultType << Input.get()->getSourceRange());
Abramo Bagnara7ccce982011-04-07 09:26:19 +000011395 }
Tanya Lattner3dd33b22012-01-19 01:16:16 +000011396 } else if (resultType->isExtVectorType()) {
Joey Gouly7d00f002013-02-21 11:49:56 +000011397 if (Context.getLangOpts().OpenCL &&
11398 Context.getLangOpts().OpenCLVersion < 120) {
11399 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11400 // operate on vector float types.
11401 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11402 if (!T->isIntegerType())
11403 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11404 << resultType << Input.get()->getSourceRange());
11405 }
Tanya Lattner20248222012-01-16 21:02:28 +000011406 // Vector logical not returns the signed variant of the operand type.
11407 resultType = GetSignedVectorType(resultType);
11408 break;
John McCall36226622010-10-12 02:09:17 +000011409 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +000011410 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +000011411 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +000011412 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +000011413
Chris Lattnerbe31ed82007-06-02 19:11:33 +000011414 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +000011415 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +000011416 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +000011417 break;
John McCalle3027922010-08-25 11:45:40 +000011418 case UO_Real:
11419 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +000011420 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smith0b6b8e42012-02-18 20:53:32 +000011421 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11422 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley01296292011-04-08 18:41:53 +000011423 if (Input.isInvalid()) return ExprError();
Richard Smith0b6b8e42012-02-18 20:53:32 +000011424 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11425 if (Input.get()->getValueKind() != VK_RValue &&
11426 Input.get()->getObjectKind() == OK_Ordinary)
11427 VK = Input.get()->getValueKind();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011428 } else if (!getLangOpts().CPlusPlus) {
Richard Smith0b6b8e42012-02-18 20:53:32 +000011429 // In C, a volatile scalar is read by __imag. In C++, it is not.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011430 Input = DefaultLvalueConversion(Input.get());
Richard Smith0b6b8e42012-02-18 20:53:32 +000011431 }
Chris Lattner30b5dd02007-08-24 21:16:53 +000011432 break;
John McCalle3027922010-08-25 11:45:40 +000011433 case UO_Extension:
Richard Smith9f690bd2015-10-27 06:02:45 +000011434 case UO_Coawait:
John Wiegley01296292011-04-08 18:41:53 +000011435 resultType = Input.get()->getType();
11436 VK = Input.get()->getValueKind();
11437 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +000011438 break;
Steve Naroff35d85152007-05-07 00:24:15 +000011439 }
John Wiegley01296292011-04-08 18:41:53 +000011440 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +000011441 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +000011442
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011443 // Check for array bounds violations in the operand of the UnaryOperator,
11444 // except for the '*' and '&' operators that have to be handled specially
11445 // by CheckArrayAccess (as there are special cases like &array[arraysize]
11446 // that are explicitly defined as valid by the standard).
11447 if (Opc != UO_AddrOf && Opc != UO_Deref)
11448 CheckArrayAccess(Input.get());
11449
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011450 return new (Context)
11451 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +000011452}
Chris Lattnereefa10e2007-05-28 06:56:27 +000011453
Douglas Gregor72341032011-12-14 21:23:13 +000011454/// \brief Determine whether the given expression is a qualified member
11455/// access expression, of a form that could be turned into a pointer to member
11456/// with the address-of operator.
11457static bool isQualifiedMemberAccess(Expr *E) {
11458 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11459 if (!DRE->getQualifier())
11460 return false;
11461
11462 ValueDecl *VD = DRE->getDecl();
11463 if (!VD->isCXXClassMember())
11464 return false;
11465
11466 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11467 return true;
11468 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11469 return Method->isInstance();
11470
11471 return false;
11472 }
11473
11474 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11475 if (!ULE->getQualifier())
11476 return false;
11477
Craig Topperdfe29ae2015-12-21 06:35:56 +000011478 for (NamedDecl *D : ULE->decls()) {
11479 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor72341032011-12-14 21:23:13 +000011480 if (Method->isInstance())
11481 return true;
11482 } else {
11483 // Overload set does not contain methods.
11484 break;
11485 }
11486 }
11487
11488 return false;
11489 }
11490
11491 return false;
11492}
11493
John McCalldadc5752010-08-24 06:29:42 +000011494ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +000011495 UnaryOperatorKind Opc, Expr *Input) {
John McCall526ab472011-10-25 17:37:35 +000011496 // First things first: handle placeholders so that the
11497 // overloaded-operator check considers the right type.
11498 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11499 // Increment and decrement of pseudo-object references.
11500 if (pty->getKind() == BuiltinType::PseudoObject &&
11501 UnaryOperator::isIncrementDecrementOp(Opc))
11502 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11503
11504 // extension is always a builtin operator.
11505 if (Opc == UO_Extension)
11506 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11507
11508 // & gets special logic for several kinds of placeholder.
11509 // The builtin code knows what to do.
11510 if (Opc == UO_AddrOf &&
11511 (pty->getKind() == BuiltinType::Overload ||
11512 pty->getKind() == BuiltinType::UnknownAny ||
11513 pty->getKind() == BuiltinType::BoundMember))
11514 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11515
11516 // Anything else needs to be handled now.
11517 ExprResult Result = CheckPlaceholderExpr(Input);
11518 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011519 Input = Result.get();
John McCall526ab472011-10-25 17:37:35 +000011520 }
11521
David Blaikiebbafb8a2012-03-11 07:00:24 +000011522 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregor72341032011-12-14 21:23:13 +000011523 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11524 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011525 // Find all of the overloaded operators visible from this
11526 // point. We perform both an operator-name lookup from the local
11527 // scope and an argument-dependent lookup based on the types of
11528 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +000011529 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +000011530 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +000011531 if (S && OverOp != OO_None)
11532 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11533 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011534
John McCallb268a282010-08-23 23:25:46 +000011535 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011536 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011537
John McCallb268a282010-08-23 23:25:46 +000011538 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011539}
11540
Douglas Gregor5287f092009-11-05 00:51:44 +000011541// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +000011542ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +000011543 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +000011544 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +000011545}
11546
Steve Naroff66356bd2007-09-16 14:56:35 +000011547/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +000011548ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +000011549 LabelDecl *TheDecl) {
Eli Friedman276dd182013-09-05 00:02:25 +000011550 TheDecl->markUsed(Context);
Chris Lattnereefa10e2007-05-28 06:56:27 +000011551 // Create the AST node. The address of a label always has type 'void*'.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011552 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11553 Context.getPointerType(Context.VoidTy));
Chris Lattnereefa10e2007-05-28 06:56:27 +000011554}
11555
John McCall31168b02011-06-15 23:02:42 +000011556/// Given the last statement in a statement-expression, check whether
11557/// the result is a producing expression (like a call to an
11558/// ns_returns_retained function) and, if so, rebuild it to hoist the
11559/// release out of the full-expression. Otherwise, return null.
11560/// Cannot fail.
Richard Trieuba63ce62011-09-09 01:45:06 +000011561static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCall31168b02011-06-15 23:02:42 +000011562 // Should always be wrapped with one of these.
Richard Trieuba63ce62011-09-09 01:45:06 +000011563 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
Craig Topperc3ec1492014-05-26 06:22:03 +000011564 if (!cleanups) return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011565
11566 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall2d637d22011-09-10 06:18:15 +000011567 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
Craig Topperc3ec1492014-05-26 06:22:03 +000011568 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011569
11570 // Splice out the cast. This shouldn't modify any interesting
11571 // features of the statement.
11572 Expr *producer = cast->getSubExpr();
11573 assert(producer->getType() == cast->getType());
11574 assert(producer->getValueKind() == cast->getValueKind());
11575 cleanups->setSubExpr(producer);
11576 return cleanups;
11577}
11578
John McCall3abee492012-04-04 01:27:53 +000011579void Sema::ActOnStartStmtExpr() {
11580 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11581}
11582
11583void Sema::ActOnStmtExprError() {
John McCalled7b2782012-04-06 18:20:53 +000011584 // Note that function is also called by TreeTransform when leaving a
11585 // StmtExpr scope without rebuilding anything.
11586
John McCall3abee492012-04-04 01:27:53 +000011587 DiscardCleanupsInEvaluationContext();
11588 PopExpressionEvaluationContext();
11589}
11590
John McCalldadc5752010-08-24 06:29:42 +000011591ExprResult
John McCallb268a282010-08-23 23:25:46 +000011592Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +000011593 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +000011594 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11595 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11596
John McCall3abee492012-04-04 01:27:53 +000011597 if (hasAnyUnrecoverableErrorsInThisFunction())
11598 DiscardCleanupsInEvaluationContext();
11599 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
11600 PopExpressionEvaluationContext();
11601
Chris Lattner366727f2007-07-24 16:58:17 +000011602 // FIXME: there are a variety of strange constraints to enforce here, for
11603 // example, it is not possible to goto into a stmt expression apparently.
11604 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +000011605
Alp Toker028ed912013-12-06 17:56:43 +000011606 // If there are sub-stmts in the compound stmt, take the type of the last one
Chris Lattner366727f2007-07-24 16:58:17 +000011607 // as the type of the stmtexpr.
11608 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +000011609 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +000011610 if (!Compound->body_empty()) {
11611 Stmt *LastStmt = Compound->body_back();
Craig Topperc3ec1492014-05-26 06:22:03 +000011612 LabelStmt *LastLabelStmt = nullptr;
Chris Lattner944d3062008-07-26 19:51:01 +000011613 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +000011614 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11615 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +000011616 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +000011617 }
John McCall31168b02011-06-15 23:02:42 +000011618
John Wiegley01296292011-04-08 18:41:53 +000011619 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +000011620 // Do function/array conversion on the last expression, but not
11621 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +000011622 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11623 if (LastExpr.isInvalid())
11624 return ExprError();
11625 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +000011626
John Wiegley01296292011-04-08 18:41:53 +000011627 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +000011628 // In ARC, if the final expression ends in a consume, splice
11629 // the consume out and bind it later. In the alternate case
11630 // (when dealing with a retainable type), the result
11631 // initialization will create a produce. In both cases the
11632 // result will be +1, and we'll need to balance that out with
11633 // a bind.
11634 if (Expr *rebuiltLastStmt
11635 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11636 LastExpr = rebuiltLastStmt;
11637 } else {
11638 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +000011639 InitializedEntity::InitializeResult(LPLoc,
11640 Ty,
11641 false),
11642 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +000011643 LastExpr);
11644 }
11645
John Wiegley01296292011-04-08 18:41:53 +000011646 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +000011647 return ExprError();
Craig Topperc3ec1492014-05-26 06:22:03 +000011648 if (LastExpr.get() != nullptr) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +000011649 if (!LastLabelStmt)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011650 Compound->setLastStmt(LastExpr.get());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +000011651 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011652 LastLabelStmt->setSubStmt(LastExpr.get());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +000011653 StmtExprMayBindToTemp = true;
11654 }
11655 }
11656 }
Chris Lattner944d3062008-07-26 19:51:01 +000011657 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000011658
Eli Friedmanba961a92009-03-23 00:24:07 +000011659 // FIXME: Check that expression type is complete/non-abstract; statement
11660 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +000011661 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
11662 if (StmtExprMayBindToTemp)
11663 return MaybeBindToTemporary(ResStmtExpr);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011664 return ResStmtExpr;
Chris Lattner366727f2007-07-24 16:58:17 +000011665}
Steve Naroff78864672007-08-01 22:05:33 +000011666
John McCalldadc5752010-08-24 06:29:42 +000011667ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +000011668 TypeSourceInfo *TInfo,
Craig Topperb5518242015-10-22 04:59:59 +000011669 ArrayRef<OffsetOfComponent> Components,
John McCall36226622010-10-12 02:09:17 +000011670 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +000011671 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000011672 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000011673 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +000011674
Chris Lattnerf17bd422007-08-30 17:45:32 +000011675 // We must have at least one component that refers to the type, and the first
11676 // one is known to be a field designator. Verify that the ArgTy represents
11677 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000011678 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +000011679 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
11680 << ArgTy << TypeRange);
11681
11682 // Type must be complete per C99 7.17p3 because a declaring a variable
11683 // with an incomplete type would be ill-formed.
11684 if (!Dependent
11685 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011686 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor882211c2010-04-28 22:16:22 +000011687 return ExprError();
11688
Chris Lattner78502cf2007-08-31 21:49:13 +000011689 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
11690 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +000011691 // FIXME: This diagnostic isn't actually visible because the location is in
11692 // a system header!
Craig Topperb5518242015-10-22 04:59:59 +000011693 if (Components.size() != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +000011694 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
Craig Topperb5518242015-10-22 04:59:59 +000011695 << SourceRange(Components[1].LocStart, Components.back().LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +000011696
11697 bool DidWarnAboutNonPOD = false;
11698 QualType CurrentType = ArgTy;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011699 SmallVector<OffsetOfNode, 4> Comps;
11700 SmallVector<Expr*, 4> Exprs;
Craig Topperb5518242015-10-22 04:59:59 +000011701 for (const OffsetOfComponent &OC : Components) {
Douglas Gregor882211c2010-04-28 22:16:22 +000011702 if (OC.isBrackets) {
11703 // Offset of an array sub-field. TODO: Should we allow vector elements?
11704 if (!CurrentType->isDependentType()) {
11705 const ArrayType *AT = Context.getAsArrayType(CurrentType);
11706 if(!AT)
11707 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
11708 << CurrentType);
11709 CurrentType = AT->getElementType();
11710 } else
11711 CurrentType = Context.DependentTy;
11712
Richard Smith9fcc5c32011-10-17 23:29:39 +000011713 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
11714 if (IdxRval.isInvalid())
11715 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011716 Expr *Idx = IdxRval.get();
Richard Smith9fcc5c32011-10-17 23:29:39 +000011717
Douglas Gregor882211c2010-04-28 22:16:22 +000011718 // The expression must be an integral expression.
11719 // FIXME: An integral constant expression?
Douglas Gregor882211c2010-04-28 22:16:22 +000011720 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
11721 !Idx->getType()->isIntegerType())
11722 return ExprError(Diag(Idx->getLocStart(),
11723 diag::err_typecheck_subscript_not_integer)
11724 << Idx->getSourceRange());
Richard Smitheda612882011-10-17 05:48:07 +000011725
Douglas Gregor882211c2010-04-28 22:16:22 +000011726 // Record this array index.
11727 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smith9fcc5c32011-10-17 23:29:39 +000011728 Exprs.push_back(Idx);
Douglas Gregor882211c2010-04-28 22:16:22 +000011729 continue;
11730 }
11731
11732 // Offset of a field.
11733 if (CurrentType->isDependentType()) {
11734 // We have the offset of a field, but we can't look into the dependent
11735 // type. Just record the identifier of the field.
11736 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
11737 CurrentType = Context.DependentTy;
11738 continue;
11739 }
11740
11741 // We need to have a complete type to look into.
11742 if (RequireCompleteType(OC.LocStart, CurrentType,
11743 diag::err_offsetof_incomplete_type))
11744 return ExprError();
11745
11746 // Look for the designated field.
11747 const RecordType *RC = CurrentType->getAs<RecordType>();
11748 if (!RC)
11749 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
11750 << CurrentType);
11751 RecordDecl *RD = RC->getDecl();
11752
11753 // C++ [lib.support.types]p5:
11754 // The macro offsetof accepts a restricted set of type arguments in this
11755 // International Standard. type shall be a POD structure or a POD union
11756 // (clause 9).
Benjamin Kramer9e7876b2012-04-28 11:14:51 +000011757 // C++11 [support.types]p4:
11758 // If type is not a standard-layout class (Clause 9), the results are
11759 // undefined.
Douglas Gregor882211c2010-04-28 22:16:22 +000011760 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011761 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
Benjamin Kramer9e7876b2012-04-28 11:14:51 +000011762 unsigned DiagID =
Richard Smith1b98ccc2014-07-19 01:39:17 +000011763 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
11764 : diag::ext_offsetof_non_pod_type;
Benjamin Kramer9e7876b2012-04-28 11:14:51 +000011765
11766 if (!IsSafe && !DidWarnAboutNonPOD &&
Craig Topperc3ec1492014-05-26 06:22:03 +000011767 DiagRuntimeBehavior(BuiltinLoc, nullptr,
Benjamin Kramer9e7876b2012-04-28 11:14:51 +000011768 PDiag(DiagID)
Craig Topperb5518242015-10-22 04:59:59 +000011769 << SourceRange(Components[0].LocStart, OC.LocEnd)
Douglas Gregor882211c2010-04-28 22:16:22 +000011770 << CurrentType))
11771 DidWarnAboutNonPOD = true;
11772 }
11773
11774 // Look for the field.
11775 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
11776 LookupQualifiedName(R, RD);
11777 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Craig Topperc3ec1492014-05-26 06:22:03 +000011778 IndirectFieldDecl *IndirectMemberDecl = nullptr;
Francois Pichet783dd6e2010-11-21 06:08:52 +000011779 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +000011780 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +000011781 MemberDecl = IndirectMemberDecl->getAnonField();
11782 }
11783
Douglas Gregor882211c2010-04-28 22:16:22 +000011784 if (!MemberDecl)
11785 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
11786 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
11787 OC.LocEnd));
11788
Douglas Gregor10982ea2010-04-28 22:36:06 +000011789 // C99 7.17p3:
11790 // (If the specified member is a bit-field, the behavior is undefined.)
11791 //
11792 // We diagnose this as an error.
Richard Smithcaf33902011-10-10 18:28:20 +000011793 if (MemberDecl->isBitField()) {
Douglas Gregor10982ea2010-04-28 22:36:06 +000011794 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
11795 << MemberDecl->getDeclName()
11796 << SourceRange(BuiltinLoc, RParenLoc);
11797 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
11798 return ExprError();
11799 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +000011800
11801 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +000011802 if (IndirectMemberDecl)
11803 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +000011804
Douglas Gregord1702062010-04-29 00:18:15 +000011805 // If the member was found in a base class, introduce OffsetOfNodes for
11806 // the base class indirections.
David Majnemerff17f832013-10-15 06:28:23 +000011807 CXXBasePaths Paths;
Richard Smith0f59cb32015-12-18 21:45:41 +000011808 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
11809 Paths)) {
David Majnemerff17f832013-10-15 06:28:23 +000011810 if (Paths.getDetectedVirtual()) {
11811 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
11812 << MemberDecl->getDeclName()
11813 << SourceRange(BuiltinLoc, RParenLoc);
11814 return ExprError();
11815 }
11816
Douglas Gregord1702062010-04-29 00:18:15 +000011817 CXXBasePath &Path = Paths.front();
Craig Topperdfe29ae2015-12-21 06:35:56 +000011818 for (const CXXBasePathElement &B : Path)
11819 Comps.push_back(OffsetOfNode(B.Base));
Douglas Gregord1702062010-04-29 00:18:15 +000011820 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +000011821
Francois Pichet783dd6e2010-11-21 06:08:52 +000011822 if (IndirectMemberDecl) {
Aaron Ballman29c94602014-03-07 18:36:15 +000011823 for (auto *FI : IndirectMemberDecl->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +000011824 assert(isa<FieldDecl>(FI));
Francois Pichet783dd6e2010-11-21 06:08:52 +000011825 Comps.push_back(OffsetOfNode(OC.LocStart,
Aaron Ballman13916082014-03-07 18:11:58 +000011826 cast<FieldDecl>(FI), OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +000011827 }
11828 } else
Douglas Gregor882211c2010-04-28 22:16:22 +000011829 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +000011830
Douglas Gregor882211c2010-04-28 22:16:22 +000011831 CurrentType = MemberDecl->getType().getNonReferenceType();
11832 }
11833
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011834 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
11835 Comps, Exprs, RParenLoc);
Douglas Gregor882211c2010-04-28 22:16:22 +000011836}
Mike Stump4e1f26a2009-02-19 03:04:26 +000011837
John McCalldadc5752010-08-24 06:29:42 +000011838ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +000011839 SourceLocation BuiltinLoc,
11840 SourceLocation TypeLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +000011841 ParsedType ParsedArgTy,
Craig Topperb5518242015-10-22 04:59:59 +000011842 ArrayRef<OffsetOfComponent> Components,
Richard Trieuba63ce62011-09-09 01:45:06 +000011843 SourceLocation RParenLoc) {
John McCall36226622010-10-12 02:09:17 +000011844
Douglas Gregor882211c2010-04-28 22:16:22 +000011845 TypeSourceInfo *ArgTInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +000011846 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor882211c2010-04-28 22:16:22 +000011847 if (ArgTy.isNull())
11848 return ExprError();
11849
Eli Friedman06dcfd92010-08-05 10:15:45 +000011850 if (!ArgTInfo)
11851 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
11852
Craig Topperb5518242015-10-22 04:59:59 +000011853 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +000011854}
11855
11856
John McCalldadc5752010-08-24 06:29:42 +000011857ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +000011858 Expr *CondExpr,
11859 Expr *LHSExpr, Expr *RHSExpr,
11860 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +000011861 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
11862
John McCall7decc9e2010-11-18 06:31:45 +000011863 ExprValueKind VK = VK_RValue;
11864 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000011865 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +000011866 bool ValueDependent = false;
Eli Friedman75807f22013-07-20 00:40:58 +000011867 bool CondIsTrue = false;
Douglas Gregor0df91122009-05-19 22:43:30 +000011868 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000011869 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +000011870 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000011871 } else {
11872 // The conditional expression is required to be a constant expression.
11873 llvm::APSInt condEval(32);
Douglas Gregore2b37442012-05-04 22:38:52 +000011874 ExprResult CondICE
11875 = VerifyIntegerConstantExpression(CondExpr, &condEval,
11876 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smithf4c51d92012-02-04 09:53:13 +000011877 if (CondICE.isInvalid())
11878 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011879 CondExpr = CondICE.get();
Eli Friedman75807f22013-07-20 00:40:58 +000011880 CondIsTrue = condEval.getZExtValue();
Steve Naroff9efdabc2007-08-03 21:21:27 +000011881
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000011882 // If the condition is > zero, then the AST type is the same as the LSHExpr.
Eli Friedman75807f22013-07-20 00:40:58 +000011883 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
John McCall7decc9e2010-11-18 06:31:45 +000011884
11885 resType = ActiveExpr->getType();
11886 ValueDependent = ActiveExpr->isValueDependent();
11887 VK = ActiveExpr->getValueKind();
11888 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000011889 }
11890
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011891 return new (Context)
11892 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
11893 CondIsTrue, resType->isDependentType(), ValueDependent);
Steve Naroff9efdabc2007-08-03 21:21:27 +000011894}
11895
Steve Naroffc540d662008-09-03 18:15:37 +000011896//===----------------------------------------------------------------------===//
11897// Clang Extensions.
11898//===----------------------------------------------------------------------===//
11899
11900/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuba63ce62011-09-09 01:45:06 +000011901void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +000011902 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Eli Friedman7e346a82013-07-01 20:22:57 +000011903
Eli Friedman4ef077a2013-09-12 22:36:24 +000011904 if (LangOpts.CPlusPlus) {
Eli Friedman7e346a82013-07-01 20:22:57 +000011905 Decl *ManglingContextDecl;
11906 if (MangleNumberingContext *MCtx =
11907 getCurrentMangleNumberContext(Block->getDeclContext(),
11908 ManglingContextDecl)) {
11909 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
11910 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
11911 }
11912 }
11913
Richard Trieuba63ce62011-09-09 01:45:06 +000011914 PushBlockScope(CurScope, Block);
Douglas Gregor9a28e842010-03-01 23:15:13 +000011915 CurContext->addDecl(Block);
Richard Trieuba63ce62011-09-09 01:45:06 +000011916 if (CurScope)
11917 PushDeclContext(CurScope, Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +000011918 else
11919 CurContext = Block;
John McCallf1a3c2a2011-11-11 03:19:12 +000011920
Eli Friedman34b49062012-01-26 03:00:14 +000011921 getCurBlock()->HasImplicitReturnType = true;
11922
John McCallf1a3c2a2011-11-11 03:19:12 +000011923 // Enter a new evaluation context to insulate the block from any
11924 // cleanups from the enclosing full-expression.
11925 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff1d95e5a2008-10-10 01:28:17 +000011926}
11927
Douglas Gregor7efd007c2012-06-15 16:59:29 +000011928void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
11929 Scope *CurScope) {
Craig Topperc3ec1492014-05-26 06:22:03 +000011930 assert(ParamInfo.getIdentifier() == nullptr &&
11931 "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +000011932 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +000011933 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011934
John McCall8cb7bdf2010-06-04 23:28:52 +000011935 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +000011936 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +000011937
Douglas Gregor7efd007c2012-06-15 16:59:29 +000011938 // FIXME: We should allow unexpanded parameter packs here, but that would,
11939 // in turn, make the block expression contain unexpanded parameter packs.
11940 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
11941 // Drop the parameters.
11942 FunctionProtoType::ExtProtoInfo EPI;
11943 EPI.HasTrailingReturn = false;
11944 EPI.TypeQuals |= DeclSpec::TQ_const;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000011945 T = Context.getFunctionType(Context.DependentTy, None, EPI);
Douglas Gregor7efd007c2012-06-15 16:59:29 +000011946 Sig = Context.getTrivialTypeSourceInfo(T);
11947 }
11948
John McCall3882ace2011-01-05 12:14:39 +000011949 // GetTypeForDeclarator always produces a function type for a block
11950 // literal signature. Furthermore, it is always a FunctionProtoType
11951 // unless the function was written with a typedef.
11952 assert(T->isFunctionType() &&
11953 "GetTypeForDeclarator made a non-function block signature");
11954
11955 // Look for an explicit signature in that function type.
11956 FunctionProtoTypeLoc ExplicitSignature;
11957
11958 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +000011959 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
John McCall3882ace2011-01-05 12:14:39 +000011960
11961 // Check whether that explicit signature was synthesized by
11962 // GetTypeForDeclarator. If so, don't save that as part of the
11963 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000011964 if (ExplicitSignature.getLocalRangeBegin() ==
11965 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +000011966 // This would be much cheaper if we stored TypeLocs instead of
11967 // TypeSourceInfos.
Alp Toker42a16a62014-01-25 23:51:36 +000011968 TypeLoc Result = ExplicitSignature.getReturnLoc();
John McCall3882ace2011-01-05 12:14:39 +000011969 unsigned Size = Result.getFullDataSize();
11970 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
11971 Sig->getTypeLoc().initializeFullCopy(Result, Size);
11972
11973 ExplicitSignature = FunctionProtoTypeLoc();
11974 }
John McCalla3ccba02010-06-04 11:21:44 +000011975 }
Mike Stump11289f42009-09-09 15:08:12 +000011976
John McCall3882ace2011-01-05 12:14:39 +000011977 CurBlock->TheDecl->setSignatureAsWritten(Sig);
11978 CurBlock->FunctionType = T;
11979
11980 const FunctionType *Fn = T->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +000011981 QualType RetTy = Fn->getReturnType();
John McCall3882ace2011-01-05 12:14:39 +000011982 bool isVariadic =
11983 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
11984
John McCall8e346702010-06-04 19:02:56 +000011985 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +000011986
John McCalla3ccba02010-06-04 11:21:44 +000011987 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +000011988 // return type. TODO: what should we do with declarators like:
11989 // ^ * { ... }
11990 // If the answer is "apply template argument deduction"....
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +000011991 if (RetTy != Context.DependentTy) {
John McCalla3ccba02010-06-04 11:21:44 +000011992 CurBlock->ReturnType = RetTy;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +000011993 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman34b49062012-01-26 03:00:14 +000011994 CurBlock->HasImplicitReturnType = false;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +000011995 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000011996
John McCalla3ccba02010-06-04 11:21:44 +000011997 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011998 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +000011999 if (ExplicitSignature) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012000 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12001 ParmVarDecl *Param = ExplicitSignature.getParam(I);
Craig Topperc3ec1492014-05-26 06:22:03 +000012002 if (Param->getIdentifier() == nullptr &&
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +000012003 !Param->isImplicit() &&
12004 !Param->isInvalidDecl() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000012005 !getLangOpts().CPlusPlus)
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +000012006 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +000012007 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +000012008 }
John McCalla3ccba02010-06-04 11:21:44 +000012009
12010 // Fake up parameter variables if we have a typedef, like
12011 // ^ fntype { ... }
12012 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +000012013 for (const auto &I : Fn->param_types()) {
12014 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12015 CurBlock->TheDecl, ParamInfo.getLocStart(), I);
John McCall8e346702010-06-04 19:02:56 +000012016 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +000012017 }
Steve Naroffc540d662008-09-03 18:15:37 +000012018 }
John McCalla3ccba02010-06-04 11:21:44 +000012019
John McCall8e346702010-06-04 19:02:56 +000012020 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +000012021 if (!Params.empty()) {
David Blaikie9c70e042011-09-21 18:16:56 +000012022 CurBlock->TheDecl->setParams(Params);
Douglas Gregorb524d902010-11-01 18:37:59 +000012023 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
12024 CurBlock->TheDecl->param_end(),
12025 /*CheckParameterNames=*/false);
12026 }
12027
John McCalla3ccba02010-06-04 11:21:44 +000012028 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +000012029 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +000012030
Eli Friedman7e346a82013-07-01 20:22:57 +000012031 // Put the parameter variables in scope.
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +000012032 for (auto AI : CurBlock->TheDecl->params()) {
12033 AI->setOwningFunction(CurBlock->TheDecl);
John McCallf7b2fb52010-01-22 00:28:27 +000012034
Steve Naroff1d95e5a2008-10-10 01:28:17 +000012035 // If this has an identifier, add it to the scope stack.
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +000012036 if (AI->getIdentifier()) {
12037 CheckShadow(CurBlock->TheScope, AI);
John McCalldf8b37c2010-03-22 09:20:08 +000012038
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +000012039 PushOnScopeChains(AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +000012040 }
John McCallf7b2fb52010-01-22 00:28:27 +000012041 }
Steve Naroffc540d662008-09-03 18:15:37 +000012042}
12043
12044/// ActOnBlockError - If there is an error parsing a block, this callback
12045/// is invoked to pop the information about the block from the action impl.
12046void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCallf1a3c2a2011-11-11 03:19:12 +000012047 // Leave the expression-evaluation context.
12048 DiscardCleanupsInEvaluationContext();
12049 PopExpressionEvaluationContext();
12050
Steve Naroffc540d662008-09-03 18:15:37 +000012051 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +000012052 PopDeclContext();
Eli Friedman71c80552012-01-05 03:35:19 +000012053 PopFunctionScopeInfo();
Steve Naroffc540d662008-09-03 18:15:37 +000012054}
12055
12056/// ActOnBlockStmtExpr - This is called when the body of a block statement
12057/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +000012058ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +000012059 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +000012060 // If blocks are disabled, emit an error.
12061 if (!LangOpts.Blocks)
12062 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +000012063
John McCallf1a3c2a2011-11-11 03:19:12 +000012064 // Leave the expression-evaluation context.
John McCall85110b42012-03-08 22:00:17 +000012065 if (hasAnyUnrecoverableErrorsInThisFunction())
12066 DiscardCleanupsInEvaluationContext();
John McCallf1a3c2a2011-11-11 03:19:12 +000012067 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
12068 PopExpressionEvaluationContext();
12069
Douglas Gregor9a28e842010-03-01 23:15:13 +000012070 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Jordan Rosed39e5f12012-07-02 21:19:23 +000012071
12072 if (BSI->HasImplicitReturnType)
12073 deduceClosureReturnType(*BSI);
12074
Steve Naroff1d95e5a2008-10-10 01:28:17 +000012075 PopDeclContext();
12076
Steve Naroffc540d662008-09-03 18:15:37 +000012077 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +000012078 if (!BSI->ReturnType.isNull())
12079 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +000012080
Aaron Ballman9ead1242013-12-19 02:39:40 +000012081 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +000012082 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +000012083
John McCallc63de662011-02-02 13:00:07 +000012084 // Set the captured variables on the block.
Eli Friedman20139d32012-01-11 02:36:31 +000012085 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12086 SmallVector<BlockDecl::Capture, 4> Captures;
Craig Topperdfe29ae2015-12-21 06:35:56 +000012087 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
Eli Friedman20139d32012-01-11 02:36:31 +000012088 if (Cap.isThisCapture())
12089 continue;
Eli Friedman24af8502012-02-03 22:47:37 +000012090 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Richard Smithba71c082013-05-16 06:20:58 +000012091 Cap.isNested(), Cap.getInitExpr());
Eli Friedman20139d32012-01-11 02:36:31 +000012092 Captures.push_back(NewCap);
12093 }
Benjamin Kramerb40e4af2015-08-05 09:40:35 +000012094 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
John McCallc63de662011-02-02 13:00:07 +000012095
John McCall8e346702010-06-04 19:02:56 +000012096 // If the user wrote a function type in some form, try to use that.
12097 if (!BSI->FunctionType.isNull()) {
12098 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12099
12100 FunctionType::ExtInfo Ext = FTy->getExtInfo();
12101 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12102
12103 // Turn protoless block types into nullary block types.
12104 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +000012105 FunctionProtoType::ExtProtoInfo EPI;
12106 EPI.ExtInfo = Ext;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012107 BlockTy = Context.getFunctionType(RetTy, None, EPI);
John McCall8e346702010-06-04 19:02:56 +000012108
12109 // Otherwise, if we don't need to change anything about the function type,
12110 // preserve its sugar structure.
Alp Toker314cc812014-01-25 16:55:45 +000012111 } else if (FTy->getReturnType() == RetTy &&
John McCall8e346702010-06-04 19:02:56 +000012112 (!NoReturn || FTy->getNoReturnAttr())) {
12113 BlockTy = BSI->FunctionType;
12114
12115 // Otherwise, make the minimal modifications to the function type.
12116 } else {
12117 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +000012118 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12119 EPI.TypeQuals = 0; // FIXME: silently?
12120 EPI.ExtInfo = Ext;
Alp Toker9cacbab2014-01-20 20:26:09 +000012121 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
John McCall8e346702010-06-04 19:02:56 +000012122 }
12123
12124 // If we don't have a function type, just build one from nothing.
12125 } else {
John McCalldb40c7f2010-12-14 08:05:40 +000012126 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +000012127 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012128 BlockTy = Context.getFunctionType(RetTy, None, EPI);
John McCall8e346702010-06-04 19:02:56 +000012129 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000012130
John McCall8e346702010-06-04 19:02:56 +000012131 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
12132 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +000012133 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +000012134
Chris Lattner45542ea2009-04-19 05:28:12 +000012135 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +000012136 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor5d944db2012-08-17 05:12:08 +000012137 !PP.isCodeCompletionEnabled())
John McCallb268a282010-08-23 23:25:46 +000012138 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +000012139
Chris Lattner60f84492011-02-17 23:58:47 +000012140 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000012141
Jordan Rosed39e5f12012-07-02 21:19:23 +000012142 // Try to apply the named return value optimization. We have to check again
12143 // if we can do this, though, because blocks keep return statements around
12144 // to deduce an implicit return type.
12145 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12146 !BSI->TheDecl->isDependentContext())
Argyrios Kyrtzidisea75aad2014-04-26 18:29:13 +000012147 computeNRVO(Body, BSI);
Douglas Gregor49695f02011-09-06 20:46:03 +000012148
Benjamin Kramera4fb8362011-07-12 14:11:05 +000012149 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
David Blaikie43472b32013-09-03 21:40:15 +000012150 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedman71c80552012-01-05 03:35:19 +000012151 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramera4fb8362011-07-12 14:11:05 +000012152
John McCall28fc7092011-11-10 05:35:25 +000012153 // If the block isn't obviously global, i.e. it captures anything at
John McCalld2393872012-04-13 01:08:17 +000012154 // all, then we need to do a few things in the surrounding context:
John McCall28fc7092011-11-10 05:35:25 +000012155 if (Result->getBlockDecl()->hasCaptures()) {
John McCalld2393872012-04-13 01:08:17 +000012156 // First, this expression has a new cleanup object.
John McCall28fc7092011-11-10 05:35:25 +000012157 ExprCleanupObjects.push_back(Result->getBlockDecl());
12158 ExprNeedsCleanups = true;
John McCalld2393872012-04-13 01:08:17 +000012159
12160 // It also gets a branch-protected scope if any of the captured
12161 // variables needs destruction.
Aaron Ballman9371dd22014-03-14 18:34:04 +000012162 for (const auto &CI : Result->getBlockDecl()->captures()) {
12163 const VarDecl *var = CI.getVariable();
John McCalld2393872012-04-13 01:08:17 +000012164 if (var->getType().isDestructedType() != QualType::DK_none) {
12165 getCurFunction()->setHasBranchProtectedScope();
12166 break;
12167 }
12168 }
John McCall28fc7092011-11-10 05:35:25 +000012169 }
Fariborz Jahanian197c68c2012-03-06 18:41:35 +000012170
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012171 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +000012172}
12173
Justin Lebar6644e362016-01-20 00:27:00 +000012174ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12175 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +000012176 TypeSourceInfo *TInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +000012177 GetTypeFromParser(Ty, &TInfo);
12178 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +000012179}
12180
John McCalldadc5752010-08-24 06:29:42 +000012181ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +000012182 Expr *E, TypeSourceInfo *TInfo,
12183 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +000012184 Expr *OrigExpr = E;
Charles Davisc7d5c942015-09-17 20:55:33 +000012185 bool IsMS = false;
12186
Justin Lebar6644e362016-01-20 00:27:00 +000012187 // CUDA device code does not support varargs.
12188 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12189 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12190 CUDAFunctionTarget T = IdentifyCUDATarget(F);
12191 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12192 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12193 }
12194 }
12195
Charles Davisc7d5c942015-09-17 20:55:33 +000012196 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12197 // as Microsoft ABI on an actual Microsoft platform, where
12198 // __builtin_ms_va_list and __builtin_va_list are the same.)
12199 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12200 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12201 QualType MSVaListType = Context.getBuiltinMSVaListType();
12202 if (Context.hasSameType(MSVaListType, E->getType())) {
12203 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12204 return ExprError();
12205 IsMS = true;
12206 }
12207 }
Mike Stump11289f42009-09-09 15:08:12 +000012208
Eli Friedman121ba0c2008-08-09 23:32:40 +000012209 // Get the va_list type
12210 QualType VaListType = Context.getBuiltinVaListType();
Charles Davisc7d5c942015-09-17 20:55:33 +000012211 if (!IsMS) {
12212 if (VaListType->isArrayType()) {
12213 // Deal with implicit array decay; for example, on x86-64,
12214 // va_list is an array, but it's supposed to decay to
12215 // a pointer for va_arg.
12216 VaListType = Context.getArrayDecayedType(VaListType);
12217 // Make sure the input expression also decays appropriately.
12218 ExprResult Result = UsualUnaryConversions(E);
12219 if (Result.isInvalid())
12220 return ExprError();
12221 E = Result.get();
12222 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12223 // If va_list is a record type and we are compiling in C++ mode,
12224 // check the argument using reference binding.
12225 InitializedEntity Entity = InitializedEntity::InitializeParameter(
12226 Context, Context.getLValueReferenceType(VaListType), false);
12227 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12228 if (Init.isInvalid())
12229 return ExprError();
12230 E = Init.getAs<Expr>();
12231 } else {
12232 // Otherwise, the va_list argument must be an l-value because
12233 // it is modified by va_arg.
12234 if (!E->isTypeDependent() &&
12235 CheckForModifiableLvalue(E, BuiltinLoc, *this))
12236 return ExprError();
12237 }
Eli Friedmane2cad652009-05-16 12:46:54 +000012238 }
Eli Friedman121ba0c2008-08-09 23:32:40 +000012239
Charles Davisc7d5c942015-09-17 20:55:33 +000012240 if (!IsMS && !E->isTypeDependent() &&
12241 !Context.hasSameType(VaListType, E->getType()))
Sebastian Redl6d4256c2009-03-15 17:47:39 +000012242 return ExprError(Diag(E->getLocStart(),
12243 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +000012244 << OrigExpr->getType() << E->getSourceRange());
Mike Stump4e1f26a2009-02-19 03:04:26 +000012245
David Majnemerc75d1a12011-06-14 05:17:32 +000012246 if (!TInfo->getType()->isDependentType()) {
12247 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012248 diag::err_second_parameter_to_va_arg_incomplete,
12249 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +000012250 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +000012251
David Majnemerc75d1a12011-06-14 05:17:32 +000012252 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregorae298422012-05-04 17:09:59 +000012253 TInfo->getType(),
12254 diag::err_second_parameter_to_va_arg_abstract,
12255 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +000012256 return ExprError();
12257
Douglas Gregor7e1eb932011-07-30 06:45:27 +000012258 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +000012259 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +000012260 TInfo->getType()->isObjCLifetimeType()
12261 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12262 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +000012263 << TInfo->getType()
12264 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +000012265 }
Eli Friedman6290ae42011-07-11 21:45:59 +000012266
12267 // Check for va_arg where arguments of the given type will be promoted
12268 // (i.e. this va_arg is guaranteed to have undefined behavior).
12269 QualType PromoteType;
12270 if (TInfo->getType()->isPromotableIntegerType()) {
12271 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12272 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12273 PromoteType = QualType();
12274 }
12275 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12276 PromoteType = Context.DoubleTy;
12277 if (!PromoteType.isNull())
Ted Kremeneka0461692013-01-08 01:50:40 +000012278 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12279 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12280 << TInfo->getType()
12281 << PromoteType
12282 << TInfo->getTypeLoc().getSourceRange());
David Majnemerc75d1a12011-06-14 05:17:32 +000012283 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000012284
Abramo Bagnara27db2392010-08-10 10:06:15 +000012285 QualType T = TInfo->getType().getNonLValueExprType(Context);
Charles Davisc7d5c942015-09-17 20:55:33 +000012286 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
Anders Carlsson7e13ab82007-10-15 20:28:48 +000012287}
12288
John McCalldadc5752010-08-24 06:29:42 +000012289ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +000012290 // The type of __null will be int or long, depending on the size of
12291 // pointers on the target.
12292 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +000012293 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12294 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +000012295 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +000012296 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +000012297 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +000012298 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +000012299 Ty = Context.LongLongTy;
12300 else {
David Blaikie83d382b2011-09-23 05:06:16 +000012301 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +000012302 }
Douglas Gregor3be4b122008-11-29 04:51:27 +000012303
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012304 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregor3be4b122008-11-29 04:51:27 +000012305}
12306
George Burgess IV60bc9722016-01-13 23:36:34 +000012307bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12308 bool Diagnose) {
Fariborz Jahanianbd714e92013-12-17 19:33:43 +000012309 if (!getLangOpts().ObjC1)
Fariborz Jahanian283bf892013-12-18 21:04:43 +000012310 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000012311
Anders Carlssonace5d072009-11-10 04:46:30 +000012312 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12313 if (!PT)
Fariborz Jahanian283bf892013-12-18 21:04:43 +000012314 return false;
Anders Carlssonace5d072009-11-10 04:46:30 +000012315
Anders Carlssonace5d072009-11-10 04:46:30 +000012316 if (!PT->isObjCIdType()) {
12317 // Check if the destination is the 'NSString' interface.
12318 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12319 if (!ID || !ID->getIdentifier()->isStr("NSString"))
Fariborz Jahanian283bf892013-12-18 21:04:43 +000012320 return false;
Anders Carlssonace5d072009-11-10 04:46:30 +000012321 }
Fariborz Jahanian283bf892013-12-18 21:04:43 +000012322
John McCallfe96e0b2011-11-06 09:01:30 +000012323 // Ignore any parens, implicit casts (should only be
12324 // array-to-pointer decays), and not-so-opaque values. The last is
12325 // important for making this trigger for property assignments.
Fariborz Jahanian283bf892013-12-18 21:04:43 +000012326 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
John McCallfe96e0b2011-11-06 09:01:30 +000012327 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12328 if (OV->getSourceExpr())
12329 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12330
12331 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregorfb65e592011-07-27 05:40:30 +000012332 if (!SL || !SL->isAscii())
Fariborz Jahanian283bf892013-12-18 21:04:43 +000012333 return false;
Bob Wilsonf5c53b82016-02-13 01:41:41 +000012334 if (Diagnose) {
George Burgess IV60bc9722016-01-13 23:36:34 +000012335 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12336 << FixItHint::CreateInsertion(SL->getLocStart(), "@");
Bob Wilsonf5c53b82016-02-13 01:41:41 +000012337 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12338 }
Fariborz Jahanian283bf892013-12-18 21:04:43 +000012339 return true;
Anders Carlssonace5d072009-11-10 04:46:30 +000012340}
12341
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000012342static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12343 const Expr *SrcExpr) {
12344 if (!DstType->isFunctionPointerType() ||
12345 !SrcExpr->getType()->isFunctionType())
12346 return false;
12347
12348 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12349 if (!DRE)
12350 return false;
12351
12352 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12353 if (!FD)
12354 return false;
12355
12356 return !S.checkAddressOfFunctionIsAvailable(FD,
12357 /*Complain=*/true,
12358 SrcExpr->getLocStart());
12359}
12360
Chris Lattner9bad62c2008-01-04 18:04:52 +000012361bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12362 SourceLocation Loc,
12363 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +000012364 Expr *SrcExpr, AssignmentAction Action,
12365 bool *Complained) {
12366 if (Complained)
12367 *Complained = false;
12368
Chris Lattner9bad62c2008-01-04 18:04:52 +000012369 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +000012370 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +000012371 bool isInvalid = false;
Eli Friedman381f4312012-02-29 20:59:56 +000012372 unsigned DiagKind = 0;
Douglas Gregora771f462010-03-31 17:46:05 +000012373 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +000012374 ConversionFixItGenerator ConvHints;
12375 bool MayHaveConvFixit = false;
Richard Trieucaff2472011-11-23 22:32:32 +000012376 bool MayHaveFunctionDiff = false;
Fariborz Jahaniand3296742014-06-19 23:05:46 +000012377 const ObjCInterfaceDecl *IFace = nullptr;
12378 const ObjCProtocolDecl *PDecl = nullptr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000012379
Chris Lattner9bad62c2008-01-04 18:04:52 +000012380 switch (ConvTy) {
Fariborz Jahanian268fec12012-07-17 18:00:08 +000012381 case Compatible:
Joerg Sonnenberger05bd2da2013-11-19 13:38:38 +000012382 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12383 return false;
Fariborz Jahanian268fec12012-07-17 18:00:08 +000012384
Chris Lattner940cfeb2008-01-04 18:22:42 +000012385 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +000012386 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +000012387 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12388 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +000012389 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +000012390 case IntToPointer:
12391 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +000012392 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12393 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +000012394 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +000012395 case IncompatiblePointer:
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +000012396 DiagKind =
12397 (Action == AA_Passing_CFAudited ?
12398 diag::err_arc_typecheck_convert_incompatible_pointer :
12399 diag::ext_typecheck_convert_incompatible_pointer);
Douglas Gregor33823722011-06-11 01:09:30 +000012400 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12401 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +000012402 if (Hint.isNull() && !CheckInferredResultType) {
12403 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12404 }
Fariborz Jahanian3beec202013-04-30 00:30:48 +000012405 else if (CheckInferredResultType) {
12406 SrcType = SrcType.getUnqualifiedType();
12407 DstType = DstType.getUnqualifiedType();
12408 }
Anna Zaks3b402712011-07-28 19:51:27 +000012409 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +000012410 break;
Eli Friedman80160bd2009-03-22 23:59:44 +000012411 case IncompatiblePointerSign:
12412 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12413 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +000012414 case FunctionVoidPointer:
12415 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12416 break;
John McCall4fff8f62011-02-01 00:10:29 +000012417 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +000012418 // Perform array-to-pointer decay if necessary.
12419 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12420
John McCall4fff8f62011-02-01 00:10:29 +000012421 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12422 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12423 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12424 DiagKind = diag::err_typecheck_incompatible_address_space;
12425 break;
John McCall31168b02011-06-15 23:02:42 +000012426
12427
12428 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +000012429 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +000012430 break;
John McCall4fff8f62011-02-01 00:10:29 +000012431 }
12432
12433 llvm_unreachable("unknown error case for discarding qualifiers!");
12434 // fallthrough
12435 }
Chris Lattner9bad62c2008-01-04 18:04:52 +000012436 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +000012437 // If the qualifiers lost were because we were applying the
12438 // (deprecated) C++ conversion from a string literal to a char*
12439 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
12440 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +000012441 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +000012442 // bit of refactoring (so that the second argument is an
12443 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +000012444 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +000012445 // C++ semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012446 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +000012447 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12448 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +000012449 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12450 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +000012451 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +000012452 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +000012453 break;
Steve Naroff081c7422008-09-04 15:10:53 +000012454 case IntToBlockPointer:
12455 DiagKind = diag::err_int_to_block_pointer;
12456 break;
12457 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +000012458 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +000012459 break;
Fariborz Jahaniand3296742014-06-19 23:05:46 +000012460 case IncompatibleObjCQualifiedId: {
12461 if (SrcType->isObjCQualifiedIdType()) {
12462 const ObjCObjectPointerType *srcOPT =
12463 SrcType->getAs<ObjCObjectPointerType>();
12464 for (auto *srcProto : srcOPT->quals()) {
12465 PDecl = srcProto;
12466 break;
12467 }
12468 if (const ObjCInterfaceType *IFaceT =
12469 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12470 IFace = IFaceT->getDecl();
12471 }
12472 else if (DstType->isObjCQualifiedIdType()) {
12473 const ObjCObjectPointerType *dstOPT =
12474 DstType->getAs<ObjCObjectPointerType>();
12475 for (auto *dstProto : dstOPT->quals()) {
12476 PDecl = dstProto;
12477 break;
12478 }
12479 if (const ObjCInterfaceType *IFaceT =
12480 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12481 IFace = IFaceT->getDecl();
12482 }
Steve Naroff8afa9892008-10-14 22:18:38 +000012483 DiagKind = diag::warn_incompatible_qualified_id;
12484 break;
Fariborz Jahaniand3296742014-06-19 23:05:46 +000012485 }
Anders Carlssondb5a9b62009-01-30 23:17:46 +000012486 case IncompatibleVectors:
12487 DiagKind = diag::warn_incompatible_vectors;
12488 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +000012489 case IncompatibleObjCWeakRef:
12490 DiagKind = diag::err_arc_weak_unavailable_assign;
12491 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +000012492 case Incompatible:
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000012493 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12494 if (Complained)
12495 *Complained = true;
12496 return true;
12497 }
12498
Chris Lattner9bad62c2008-01-04 18:04:52 +000012499 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +000012500 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12501 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +000012502 isInvalid = true;
Richard Trieucaff2472011-11-23 22:32:32 +000012503 MayHaveFunctionDiff = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +000012504 break;
12505 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000012506
Douglas Gregorc68e1402010-04-09 00:35:39 +000012507 QualType FirstType, SecondType;
12508 switch (Action) {
12509 case AA_Assigning:
12510 case AA_Initializing:
12511 // The destination type comes first.
12512 FirstType = DstType;
12513 SecondType = SrcType;
12514 break;
Alexis Huntc46382e2010-04-28 23:02:27 +000012515
Douglas Gregorc68e1402010-04-09 00:35:39 +000012516 case AA_Returning:
12517 case AA_Passing:
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +000012518 case AA_Passing_CFAudited:
Douglas Gregorc68e1402010-04-09 00:35:39 +000012519 case AA_Converting:
12520 case AA_Sending:
12521 case AA_Casting:
12522 // The source type comes first.
12523 FirstType = SrcType;
12524 SecondType = DstType;
12525 break;
12526 }
Alexis Huntc46382e2010-04-28 23:02:27 +000012527
Anna Zaks3b402712011-07-28 19:51:27 +000012528 PartialDiagnostic FDiag = PDiag(DiagKind);
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +000012529 if (Action == AA_Passing_CFAudited)
Fariborz Jahanian68e18672014-09-10 18:23:34 +000012530 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +000012531 else
12532 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
Anna Zaks3b402712011-07-28 19:51:27 +000012533
12534 // If we can fix the conversion, suggest the FixIts.
12535 assert(ConvHints.isNull() || Hint.isNull());
12536 if (!ConvHints.isNull()) {
Craig Topperdfe29ae2015-12-21 06:35:56 +000012537 for (FixItHint &H : ConvHints.Hints)
12538 FDiag << H;
Anna Zaks3b402712011-07-28 19:51:27 +000012539 } else {
12540 FDiag << Hint;
12541 }
12542 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12543
Richard Trieucaff2472011-11-23 22:32:32 +000012544 if (MayHaveFunctionDiff)
12545 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12546
Anna Zaks3b402712011-07-28 19:51:27 +000012547 Diag(Loc, FDiag);
Fariborz Jahaniand3296742014-06-19 23:05:46 +000012548 if (DiagKind == diag::warn_incompatible_qualified_id &&
12549 PDecl && IFace && !IFace->hasDefinition())
12550 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
12551 << IFace->getName() << PDecl->getName();
12552
Richard Trieucaff2472011-11-23 22:32:32 +000012553 if (SecondType == Context.OverloadTy)
12554 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
George Burgess IV5f21c712015-10-12 19:57:04 +000012555 FirstType, /*TakingAddress=*/true);
Richard Trieucaff2472011-11-23 22:32:32 +000012556
Douglas Gregor33823722011-06-11 01:09:30 +000012557 if (CheckInferredResultType)
12558 EmitRelatedResultTypeNote(SrcExpr);
John McCall5ec7e7d2013-03-19 07:04:25 +000012559
12560 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12561 EmitRelatedResultTypeNoteForReturn(DstType);
Douglas Gregor33823722011-06-11 01:09:30 +000012562
Douglas Gregor4f4946a2010-04-22 00:20:18 +000012563 if (Complained)
12564 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +000012565 return isInvalid;
12566}
Anders Carlssone54e8a12008-11-30 19:50:32 +000012567
Richard Smithf4c51d92012-02-04 09:53:13 +000012568ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12569 llvm::APSInt *Result) {
Douglas Gregore2b37442012-05-04 22:38:52 +000012570 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12571 public:
Craig Toppere14c0f82014-03-12 04:55:44 +000012572 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +000012573 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12574 }
12575 } Diagnoser;
12576
12577 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12578}
12579
12580ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12581 llvm::APSInt *Result,
12582 unsigned DiagID,
12583 bool AllowFold) {
12584 class IDDiagnoser : public VerifyICEDiagnoser {
12585 unsigned DiagID;
12586
12587 public:
12588 IDDiagnoser(unsigned DiagID)
12589 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12590
Craig Toppere14c0f82014-03-12 04:55:44 +000012591 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +000012592 S.Diag(Loc, DiagID) << SR;
12593 }
12594 } Diagnoser(DiagID);
12595
12596 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12597}
12598
12599void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12600 SourceRange SR) {
12601 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smithf4c51d92012-02-04 09:53:13 +000012602}
12603
Benjamin Kramer33adaae2012-04-18 14:22:41 +000012604ExprResult
12605Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregore2b37442012-05-04 22:38:52 +000012606 VerifyICEDiagnoser &Diagnoser,
12607 bool AllowFold) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012608 SourceLocation DiagLoc = E->getLocStart();
Richard Smithf4c51d92012-02-04 09:53:13 +000012609
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012610 if (getLangOpts().CPlusPlus11) {
Richard Smithf4c51d92012-02-04 09:53:13 +000012611 // C++11 [expr.const]p5:
12612 // If an expression of literal class type is used in a context where an
12613 // integral constant expression is required, then that class type shall
12614 // have a single non-explicit conversion function to an integral or
12615 // unscoped enumeration type
12616 ExprResult Converted;
Richard Smithccc11812013-05-21 19:05:48 +000012617 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12618 public:
12619 CXX11ConvertDiagnoser(bool Silent)
12620 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12621 Silent, true) {}
Douglas Gregore2b37442012-05-04 22:38:52 +000012622
Craig Toppere14c0f82014-03-12 04:55:44 +000012623 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12624 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +000012625 return S.Diag(Loc, diag::err_ice_not_integral) << T;
12626 }
12627
Craig Toppere14c0f82014-03-12 04:55:44 +000012628 SemaDiagnosticBuilder diagnoseIncomplete(
12629 Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +000012630 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12631 }
12632
Craig Toppere14c0f82014-03-12 04:55:44 +000012633 SemaDiagnosticBuilder diagnoseExplicitConv(
12634 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +000012635 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12636 }
12637
Craig Toppere14c0f82014-03-12 04:55:44 +000012638 SemaDiagnosticBuilder noteExplicitConv(
12639 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +000012640 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12641 << ConvTy->isEnumeralType() << ConvTy;
12642 }
12643
Craig Toppere14c0f82014-03-12 04:55:44 +000012644 SemaDiagnosticBuilder diagnoseAmbiguous(
12645 Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +000012646 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
12647 }
12648
Craig Toppere14c0f82014-03-12 04:55:44 +000012649 SemaDiagnosticBuilder noteAmbiguous(
12650 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +000012651 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12652 << ConvTy->isEnumeralType() << ConvTy;
12653 }
12654
Craig Toppere14c0f82014-03-12 04:55:44 +000012655 SemaDiagnosticBuilder diagnoseConversion(
12656 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +000012657 llvm_unreachable("conversion functions are permitted");
12658 }
12659 } ConvertDiagnoser(Diagnoser.Suppress);
12660
12661 Converted = PerformContextualImplicitConversion(DiagLoc, E,
12662 ConvertDiagnoser);
Richard Smithf4c51d92012-02-04 09:53:13 +000012663 if (Converted.isInvalid())
12664 return Converted;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012665 E = Converted.get();
Richard Smithf4c51d92012-02-04 09:53:13 +000012666 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
12667 return ExprError();
12668 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12669 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregore2b37442012-05-04 22:38:52 +000012670 if (!Diagnoser.Suppress)
12671 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithf4c51d92012-02-04 09:53:13 +000012672 return ExprError();
12673 }
12674
Richard Smith902ca212011-12-14 23:32:26 +000012675 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
12676 // in the non-ICE case.
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012677 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
Richard Smithf4c51d92012-02-04 09:53:13 +000012678 if (Result)
12679 *Result = E->EvaluateKnownConstInt(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012680 return E;
Eli Friedmanbb967cc2009-04-25 22:26:58 +000012681 }
12682
Anders Carlssone54e8a12008-11-30 19:50:32 +000012683 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012684 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith92b1ce02011-12-12 09:28:41 +000012685 EvalResult.Diag = &Notes;
Anders Carlssone54e8a12008-11-30 19:50:32 +000012686
Richard Smith902ca212011-12-14 23:32:26 +000012687 // Try to evaluate the expression, and produce diagnostics explaining why it's
12688 // not a constant expression as a side-effect.
12689 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
12690 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
12691
12692 // In C++11, we can rely on diagnostics being produced for any expression
12693 // which is not a constant expression. If no diagnostics were produced, then
12694 // this is a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012695 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
Richard Smith902ca212011-12-14 23:32:26 +000012696 if (Result)
12697 *Result = EvalResult.Val.getInt();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012698 return E;
Richard Smithf4c51d92012-02-04 09:53:13 +000012699 }
12700
12701 // If our only note is the usual "invalid subexpression" note, just point
12702 // the caret at its location rather than producing an essentially
12703 // redundant note.
12704 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12705 diag::note_invalid_subexpr_in_const_expr) {
12706 DiagLoc = Notes[0].first;
12707 Notes.clear();
Richard Smith902ca212011-12-14 23:32:26 +000012708 }
12709
12710 if (!Folded || !AllowFold) {
Douglas Gregore2b37442012-05-04 22:38:52 +000012711 if (!Diagnoser.Suppress) {
12712 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Craig Topperdfe29ae2015-12-21 06:35:56 +000012713 for (const PartialDiagnosticAt &Note : Notes)
12714 Diag(Note.first, Note.second);
Anders Carlssone54e8a12008-11-30 19:50:32 +000012715 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000012716
Richard Smithf4c51d92012-02-04 09:53:13 +000012717 return ExprError();
Anders Carlssone54e8a12008-11-30 19:50:32 +000012718 }
12719
Douglas Gregore2b37442012-05-04 22:38:52 +000012720 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Craig Topperdfe29ae2015-12-21 06:35:56 +000012721 for (const PartialDiagnosticAt &Note : Notes)
12722 Diag(Note.first, Note.second);
Mike Stump4e1f26a2009-02-19 03:04:26 +000012723
Anders Carlssone54e8a12008-11-30 19:50:32 +000012724 if (Result)
12725 *Result = EvalResult.Val.getInt();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012726 return E;
Anders Carlssone54e8a12008-11-30 19:50:32 +000012727}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000012728
Eli Friedman456f0182012-01-20 01:26:23 +000012729namespace {
12730 // Handle the case where we conclude a expression which we speculatively
12731 // considered to be unevaluated is actually evaluated.
12732 class TransformToPE : public TreeTransform<TransformToPE> {
12733 typedef TreeTransform<TransformToPE> BaseTransform;
12734
12735 public:
12736 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
12737
12738 // Make sure we redo semantic analysis
12739 bool AlwaysRebuild() { return true; }
12740
Eli Friedman5f0ca242012-02-06 23:29:57 +000012741 // Make sure we handle LabelStmts correctly.
12742 // FIXME: This does the right thing, but maybe we need a more general
12743 // fix to TreeTransform?
12744 StmtResult TransformLabelStmt(LabelStmt *S) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012745 S->getDecl()->setStmt(nullptr);
Eli Friedman5f0ca242012-02-06 23:29:57 +000012746 return BaseTransform::TransformLabelStmt(S);
12747 }
12748
Eli Friedman456f0182012-01-20 01:26:23 +000012749 // We need to special-case DeclRefExprs referring to FieldDecls which
12750 // are not part of a member pointer formation; normal TreeTransforming
12751 // doesn't catch this case because of the way we represent them in the AST.
12752 // FIXME: This is a bit ugly; is it really the best way to handle this
12753 // case?
12754 //
12755 // Error on DeclRefExprs referring to FieldDecls.
12756 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
12757 if (isa<FieldDecl>(E->getDecl()) &&
David Blaikie131fcb42012-08-06 22:47:24 +000012758 !SemaRef.isUnevaluatedContext())
Eli Friedman456f0182012-01-20 01:26:23 +000012759 return SemaRef.Diag(E->getLocation(),
12760 diag::err_invalid_non_static_member_use)
12761 << E->getDecl() << E->getSourceRange();
12762
12763 return BaseTransform::TransformDeclRefExpr(E);
12764 }
12765
12766 // Exception: filter out member pointer formation
12767 ExprResult TransformUnaryOperator(UnaryOperator *E) {
12768 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
12769 return E;
12770
12771 return BaseTransform::TransformUnaryOperator(E);
12772 }
12773
Douglas Gregor89625492012-02-09 08:14:43 +000012774 ExprResult TransformLambdaExpr(LambdaExpr *E) {
12775 // Lambdas never need to be transformed.
12776 return E;
12777 }
Eli Friedman456f0182012-01-20 01:26:23 +000012778 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000012779}
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000012780
Benjamin Kramerd81108f2012-11-14 15:08:31 +000012781ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
John McCallf413f5e2013-05-03 00:10:13 +000012782 assert(isUnevaluatedContext() &&
Eli Friedmane4f22df2012-02-29 04:03:55 +000012783 "Should only transform unevaluated expressions");
Eli Friedman456f0182012-01-20 01:26:23 +000012784 ExprEvalContexts.back().Context =
12785 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
John McCallf413f5e2013-05-03 00:10:13 +000012786 if (isUnevaluatedContext())
Eli Friedman456f0182012-01-20 01:26:23 +000012787 return E;
12788 return TransformToPE(*this).TransformExpr(E);
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000012789}
12790
Douglas Gregorff790f12009-11-26 00:44:06 +000012791void
Douglas Gregor7fcbd902012-02-21 00:37:24 +000012792Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smithfd555f62012-02-22 02:04:18 +000012793 Decl *LambdaContextDecl,
12794 bool IsDecltype) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +000012795 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(),
12796 ExprNeedsCleanups, LambdaContextDecl,
12797 IsDecltype);
John McCall31168b02011-06-15 23:02:42 +000012798 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +000012799 if (!MaybeODRUseExprs.empty())
12800 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +000012801}
12802
Eli Friedman15681d62012-09-26 04:34:21 +000012803void
12804Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12805 ReuseLambdaContextDecl_t,
12806 bool IsDecltype) {
Eli Friedman7e346a82013-07-01 20:22:57 +000012807 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
12808 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
Eli Friedman15681d62012-09-26 04:34:21 +000012809}
12810
Richard Trieucfc491d2011-08-02 04:35:43 +000012811void Sema::PopExpressionEvaluationContext() {
Eli Friedmanfa0df832012-02-02 03:46:19 +000012812 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Kaelyn Takata6c759512014-10-27 18:07:37 +000012813 unsigned NumTypos = Rec.NumTypos;
Douglas Gregor0b6a6242009-06-22 20:57:11 +000012814
Douglas Gregor89625492012-02-09 08:14:43 +000012815 if (!Rec.Lambdas.empty()) {
David Majnemer9adc3612013-10-25 09:12:52 +000012816 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12817 unsigned D;
12818 if (Rec.isUnevaluated()) {
12819 // C++11 [expr.prim.lambda]p2:
12820 // A lambda-expression shall not appear in an unevaluated operand
12821 // (Clause 5).
12822 D = diag::err_lambda_unevaluated_operand;
12823 } else {
12824 // C++1y [expr.const]p2:
12825 // A conditional-expression e is a core constant expression unless the
12826 // evaluation of e, following the rules of the abstract machine, would
12827 // evaluate [...] a lambda-expression.
12828 D = diag::err_lambda_in_constant_expression;
12829 }
Aaron Ballmanae2144e2014-10-16 17:53:07 +000012830 for (const auto *L : Rec.Lambdas)
12831 Diag(L->getLocStart(), D);
Douglas Gregor89625492012-02-09 08:14:43 +000012832 } else {
12833 // Mark the capture expressions odr-used. This was deferred
12834 // during lambda expression creation.
Aaron Ballmanae2144e2014-10-16 17:53:07 +000012835 for (auto *Lambda : Rec.Lambdas) {
12836 for (auto *C : Lambda->capture_inits())
12837 MarkDeclarationsReferencedInExpr(C);
Douglas Gregor89625492012-02-09 08:14:43 +000012838 }
12839 }
12840 }
12841
Douglas Gregorff790f12009-11-26 00:44:06 +000012842 // When are coming out of an unevaluated context, clear out any
12843 // temporaries that we may have created as part of the evaluation of
12844 // the expression in that context: they aren't relevant because they
12845 // will never be constructed.
John McCallf413f5e2013-05-03 00:10:13 +000012846 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
John McCall28fc7092011-11-10 05:35:25 +000012847 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
12848 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +000012849 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +000012850 CleanupVarDeclMarking();
12851 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCall31168b02011-06-15 23:02:42 +000012852 // Otherwise, merge the contexts together.
12853 } else {
12854 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +000012855 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
12856 Rec.SavedMaybeODRUseExprs.end());
John McCall31168b02011-06-15 23:02:42 +000012857 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000012858
12859 // Pop the current expression evaluation context off the stack.
12860 ExprEvalContexts.pop_back();
Kaelyn Takata6c759512014-10-27 18:07:37 +000012861
12862 if (!ExprEvalContexts.empty())
12863 ExprEvalContexts.back().NumTypos += NumTypos;
12864 else
12865 assert(NumTypos == 0 && "There are outstanding typos after popping the "
12866 "last ExpressionEvaluationContextRecord");
Douglas Gregor0b6a6242009-06-22 20:57:11 +000012867}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000012868
John McCall31168b02011-06-15 23:02:42 +000012869void Sema::DiscardCleanupsInEvaluationContext() {
John McCall28fc7092011-11-10 05:35:25 +000012870 ExprCleanupObjects.erase(
12871 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
12872 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +000012873 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +000012874 MaybeODRUseExprs.clear();
John McCall31168b02011-06-15 23:02:42 +000012875}
12876
Eli Friedmane0afc982012-01-21 01:01:51 +000012877ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
12878 if (!E->getType()->isVariablyModifiedType())
12879 return E;
Benjamin Kramerd81108f2012-11-14 15:08:31 +000012880 return TransformToPotentiallyEvaluated(E);
Eli Friedmane0afc982012-01-21 01:01:51 +000012881}
12882
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +000012883static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000012884 // Do not mark anything as "used" within a dependent context; wait for
12885 // an instantiation.
Eli Friedmanfa0df832012-02-02 03:46:19 +000012886 if (SemaRef.CurContext->isDependentContext())
12887 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012888
Eli Friedmanfa0df832012-02-02 03:46:19 +000012889 switch (SemaRef.ExprEvalContexts.back().Context) {
12890 case Sema::Unevaluated:
John McCallf413f5e2013-05-03 00:10:13 +000012891 case Sema::UnevaluatedAbstract:
Douglas Gregor0b6a6242009-06-22 20:57:11 +000012892 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman02b58512012-01-21 04:44:06 +000012893 // (Depending on how you read the standard, we actually do need to do
12894 // something here for null pointer constants, but the standard's
12895 // definition of a null pointer constant is completely crazy.)
Eli Friedmanfa0df832012-02-02 03:46:19 +000012896 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012897
Eli Friedmanfa0df832012-02-02 03:46:19 +000012898 case Sema::ConstantEvaluated:
12899 case Sema::PotentiallyEvaluated:
Eli Friedman02b58512012-01-21 04:44:06 +000012900 // We are in a potentially evaluated expression (or a constant-expression
12901 // in C++03); we need to do implicit template instantiation, implicitly
12902 // define class members, and mark most declarations as used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000012903 return true;
Mike Stump11289f42009-09-09 15:08:12 +000012904
Eli Friedmanfa0df832012-02-02 03:46:19 +000012905 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000012906 // Referenced declarations will only be used if the construct in the
12907 // containing expression is used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000012908 return false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +000012909 }
Matt Beaumont-Gay248bc722012-02-02 18:35:35 +000012910 llvm_unreachable("Invalid context");
Eli Friedmanfa0df832012-02-02 03:46:19 +000012911}
12912
12913/// \brief Mark a function referenced, and check whether it is odr-used
12914/// (C++ [basic.def.odr]p2, C99 6.9p3)
Nico Weber8bf410f2014-08-27 17:04:39 +000012915void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
Richard Smith0e32c522016-03-25 22:29:27 +000012916 bool MightBeOdrUse) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000012917 assert(Func && "No function?");
12918
12919 Func->setReferenced();
12920
Richard Smithe10d3042012-11-07 01:14:25 +000012921 // C++11 [basic.def.odr]p3:
12922 // A function whose name appears as a potentially-evaluated expression is
12923 // odr-used if it is the unique lookup result or the selected member of a
12924 // set of overloaded functions [...].
12925 //
12926 // We (incorrectly) mark overload resolution as an unevaluated context, so we
Richard Smith6739a102016-05-05 00:56:12 +000012927 // can just check that here.
Richard Smith0e32c522016-03-25 22:29:27 +000012928 bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this);
Richard Smith6739a102016-05-05 00:56:12 +000012929
12930 // Determine whether we require a function definition to exist, per
12931 // C++11 [temp.inst]p3:
12932 // Unless a function template specialization has been explicitly
12933 // instantiated or explicitly specialized, the function template
12934 // specialization is implicitly instantiated when the specialization is
12935 // referenced in a context that requires a function definition to exist.
12936 //
12937 // We consider constexpr function templates to be referenced in a context
12938 // that requires a definition to exist whenever they are referenced.
12939 //
12940 // FIXME: This instantiates constexpr functions too frequently. If this is
12941 // really an unevaluated context (and we're not just in the definition of a
12942 // function template or overload resolution or other cases which we
12943 // incorrectly consider to be unevaluated contexts), and we're not in a
12944 // subexpression which we actually need to evaluate (for instance, a
12945 // template argument, array bound or an expression in a braced-init-list),
12946 // we are not permitted to instantiate this constexpr function definition.
12947 //
12948 // FIXME: This also implicitly defines special members too frequently. They
12949 // are only supposed to be implicitly defined if they are odr-used, but they
12950 // are not odr-used from constant expressions in unevaluated contexts.
12951 // However, they cannot be referenced if they are deleted, and they are
12952 // deleted whenever the implicit definition of the special member would
12953 // fail (with very few exceptions).
12954 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
12955 bool NeedDefinition =
12956 OdrUse || (Func->isConstexpr() && (Func->isImplicitlyInstantiable() ||
12957 (MD && !MD->isUserProvided())));
12958
12959 // C++14 [temp.expl.spec]p6:
12960 // If a template [...] is explicitly specialized then that specialization
12961 // shall be declared before the first use of that specialization that would
12962 // cause an implicit instantiation to take place, in every translation unit
12963 // in which such a use occurs
12964 if (NeedDefinition &&
12965 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
12966 Func->getMemberSpecializationInfo()))
12967 checkSpecializationVisibility(Loc, Func);
12968
12969 // If we don't need to mark the function as used, and we don't need to
12970 // try to provide a definition, there's nothing more to do.
12971 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
12972 (!NeedDefinition || Func->getBody()))
12973 return;
Mike Stump11289f42009-09-09 15:08:12 +000012974
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000012975 // Note that this declaration has been used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000012976 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smithab44d5b2013-12-10 08:25:00 +000012977 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
Richard Smith273c4e92012-02-26 07:51:39 +000012978 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000012979 if (Constructor->isDefaultConstructor()) {
Hans Wennborg853ae942014-05-30 16:59:42 +000012980 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
Sebastian Redl22653ba2011-08-30 19:58:05 +000012981 return;
Richard Smithab44d5b2013-12-10 08:25:00 +000012982 DefineImplicitDefaultConstructor(Loc, Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012983 } else if (Constructor->isCopyConstructor()) {
Richard Smithab44d5b2013-12-10 08:25:00 +000012984 DefineImplicitCopyConstructor(Loc, Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012985 } else if (Constructor->isMoveConstructor()) {
Richard Smithab44d5b2013-12-10 08:25:00 +000012986 DefineImplicitMoveConstructor(Loc, Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012987 }
Richard Smithc2bc61b2013-03-18 21:12:30 +000012988 } else if (Constructor->getInheritedConstructor()) {
Richard Smithab44d5b2013-12-10 08:25:00 +000012989 DefineInheritingConstructor(Loc, Constructor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +000012990 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000012991 } else if (CXXDestructorDecl *Destructor =
12992 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smithab44d5b2013-12-10 08:25:00 +000012993 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
Nico Weber55905142015-03-06 06:01:06 +000012994 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
12995 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
12996 return;
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000012997 DefineImplicitDestructor(Loc, Destructor);
Nico Weber55905142015-03-06 06:01:06 +000012998 }
Nico Weberb3a99782015-01-26 06:23:36 +000012999 if (Destructor->isVirtual() && getLangOpts().AppleKext)
Douglas Gregor88d292c2010-05-13 16:44:06 +000013000 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +000013001 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smithab44d5b2013-12-10 08:25:00 +000013002 if (MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +000013003 MethodDecl->getOverloadedOperator() == OO_Equal) {
Richard Smithab44d5b2013-12-10 08:25:00 +000013004 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13005 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000013006 if (MethodDecl->isCopyAssignmentOperator())
13007 DefineImplicitCopyAssignment(Loc, MethodDecl);
13008 else
13009 DefineImplicitMoveAssignment(Loc, MethodDecl);
13010 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000013011 } else if (isa<CXXConversionDecl>(MethodDecl) &&
13012 MethodDecl->getParent()->isLambda()) {
Richard Smithab44d5b2013-12-10 08:25:00 +000013013 CXXConversionDecl *Conversion =
13014 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
Douglas Gregord3b672c2012-02-16 01:06:16 +000013015 if (Conversion->isLambdaToBlockPointerConversion())
13016 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13017 else
13018 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Nico Weberb3a99782015-01-26 06:23:36 +000013019 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
Douglas Gregor88d292c2010-05-13 16:44:06 +000013020 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000013021 }
John McCall83779672011-02-19 02:53:41 +000013022
Eli Friedmanfa0df832012-02-02 03:46:19 +000013023 // Recursive functions should be marked when used from another function.
13024 // FIXME: Is this really right?
13025 if (CurContext == Func) return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000013026
Richard Smithd3b5c9082012-07-27 04:22:15 +000013027 // Resolve the exception specification for any function which is
Richard Smithf623c962012-04-17 00:58:00 +000013028 // used: CodeGen will need it.
Richard Smithd3729422012-04-19 00:08:28 +000013029 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +000013030 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13031 ResolveExceptionSpec(Loc, FPT);
Richard Smithf623c962012-04-17 00:58:00 +000013032
Eli Friedmanfa0df832012-02-02 03:46:19 +000013033 // Implicit instantiation of function templates and member functions of
13034 // class templates.
13035 if (Func->isImplicitlyInstantiable()) {
13036 bool AlreadyInstantiated = false;
Richard Smith4a941e22012-02-14 22:25:15 +000013037 SourceLocation PointOfInstantiation = Loc;
Eli Friedmanfa0df832012-02-02 03:46:19 +000013038 if (FunctionTemplateSpecializationInfo *SpecInfo
13039 = Func->getTemplateSpecializationInfo()) {
13040 if (SpecInfo->getPointOfInstantiation().isInvalid())
13041 SpecInfo->setPointOfInstantiation(Loc);
13042 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000013043 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000013044 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000013045 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13046 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000013047 } else if (MemberSpecializationInfo *MSInfo
13048 = Func->getMemberSpecializationInfo()) {
13049 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregor06db9f52009-10-12 20:18:28 +000013050 MSInfo->setPointOfInstantiation(Loc);
Eli Friedmanfa0df832012-02-02 03:46:19 +000013051 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000013052 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000013053 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000013054 PointOfInstantiation = MSInfo->getPointOfInstantiation();
13055 }
Douglas Gregor06db9f52009-10-12 20:18:28 +000013056 }
Mike Stump11289f42009-09-09 15:08:12 +000013057
David Majnemerc85ed7e2013-10-23 21:31:20 +000013058 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000013059 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
Faisal Vali18d35982013-06-26 02:34:24 +000013060 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13061 ActiveTemplateInstantiations.size())
Richard Smith4a941e22012-02-14 22:25:15 +000013062 PendingLocalImplicitInstantiations.push_back(
13063 std::make_pair(Func, PointOfInstantiation));
David Majnemerc85ed7e2013-10-23 21:31:20 +000013064 else if (Func->isConstexpr())
Eli Friedmanfa0df832012-02-02 03:46:19 +000013065 // Do not defer instantiations of constexpr functions, to avoid the
13066 // expression evaluator needing to call back into Sema if it sees a
13067 // call to such a function.
Richard Smith4a941e22012-02-14 22:25:15 +000013068 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000013069 else {
Richard Smith4a941e22012-02-14 22:25:15 +000013070 PendingInstantiations.push_back(std::make_pair(Func,
13071 PointOfInstantiation));
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000013072 // Notify the consumer that a function was implicitly instantiated.
13073 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13074 }
John McCall83779672011-02-19 02:53:41 +000013075 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000013076 } else {
13077 // Walk redefinitions, as some of them may be instantiable.
Aaron Ballman86c93902014-03-06 23:45:36 +000013078 for (auto i : Func->redecls()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000013079 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Richard Smith0e32c522016-03-25 22:29:27 +000013080 MarkFunctionReferenced(Loc, i, OdrUse);
Eli Friedmanfa0df832012-02-02 03:46:19 +000013081 }
Sam Weinigbae69142009-09-11 03:29:30 +000013082 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000013083
Richard Smith0e32c522016-03-25 22:29:27 +000013084 if (!OdrUse) return;
13085
Eli Friedmanfa0df832012-02-02 03:46:19 +000013086 // Keep track of used but undefined functions.
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +000013087 if (!Func->isDefined()) {
Rafael Espindola0e0d0092013-03-14 03:07:35 +000013088 if (mightHaveNonExternalLinkage(Func))
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +000013089 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13090 else if (Func->getMostRecentDecl()->isInlined() &&
Peter Collingbourne470d9422015-05-13 22:07:22 +000013091 !LangOpts.GNUInline &&
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +000013092 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13093 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
Eli Friedmanfa0df832012-02-02 03:46:19 +000013094 }
13095
Vassil Vassilev928c8252016-04-28 14:13:28 +000013096 Func->markUsed(Context);
Eli Friedmanfa0df832012-02-02 03:46:19 +000013097}
13098
Eli Friedman9bb33f52012-02-03 02:04:35 +000013099static void
13100diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13101 VarDecl *var, DeclContext *DC) {
Eli Friedmandd053f62012-02-07 00:15:00 +000013102 DeclContext *VarDC = var->getDeclContext();
13103
Eli Friedman9bb33f52012-02-03 02:04:35 +000013104 // If the parameter still belongs to the translation unit, then
13105 // we're actually just using one parameter in the declaration of
13106 // the next.
13107 if (isa<ParmVarDecl>(var) &&
Eli Friedmandd053f62012-02-07 00:15:00 +000013108 isa<TranslationUnitDecl>(VarDC))
Eli Friedman9bb33f52012-02-03 02:04:35 +000013109 return;
13110
Eli Friedmandd053f62012-02-07 00:15:00 +000013111 // For C code, don't diagnose about capture if we're not actually in code
13112 // right now; it's impossible to write a non-constant expression outside of
13113 // function context, so we'll get other (more useful) diagnostics later.
13114 //
13115 // For C++, things get a bit more nasty... it would be nice to suppress this
13116 // diagnostic for certain cases like using a local variable in an array bound
13117 // for a member of a local class, but the correct predicate is not obvious.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013118 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman9bb33f52012-02-03 02:04:35 +000013119 return;
13120
Eli Friedmandd053f62012-02-07 00:15:00 +000013121 if (isa<CXXMethodDecl>(VarDC) &&
13122 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13123 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
13124 << var->getIdentifier();
13125 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
13126 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
13127 << var->getIdentifier() << fn->getDeclName();
13128 } else if (isa<BlockDecl>(VarDC)) {
13129 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
13130 << var->getIdentifier();
13131 } else {
13132 // FIXME: Is there any other context where a local variable can be
13133 // declared?
13134 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
13135 << var->getIdentifier();
13136 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000013137
Alp Toker2afa8782014-05-28 12:20:14 +000013138 S.Diag(var->getLocation(), diag::note_entity_declared_at)
13139 << var->getIdentifier();
Eli Friedmandd053f62012-02-07 00:15:00 +000013140
13141 // FIXME: Add additional diagnostic info about class etc. which prevents
13142 // capture.
Eli Friedman9bb33f52012-02-03 02:04:35 +000013143}
13144
Faisal Valiad090d82013-10-07 05:13:48 +000013145
13146static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
13147 bool &SubCapturesAreNested,
13148 QualType &CaptureType,
13149 QualType &DeclRefType) {
13150 // Check whether we've already captured it.
13151 if (CSI->CaptureMap.count(Var)) {
13152 // If we found a capture, any subcaptures are nested.
13153 SubCapturesAreNested = true;
13154
13155 // Retrieve the capture type for this variable.
13156 CaptureType = CSI->getCapture(Var).getCaptureType();
13157
13158 // Compute the type of an expression that refers to this variable.
13159 DeclRefType = CaptureType.getNonReferenceType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +000013160
13161 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13162 // are mutable in the sense that user can change their value - they are
13163 // private instances of the captured declarations.
Faisal Valiad090d82013-10-07 05:13:48 +000013164 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13165 if (Cap.isCopyCapture() &&
Samuel Antao4af1b7b2015-12-02 17:44:43 +000013166 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13167 !(isa<CapturedRegionScopeInfo>(CSI) &&
13168 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
Faisal Valiad090d82013-10-07 05:13:48 +000013169 DeclRefType.addConst();
13170 return true;
13171 }
13172 return false;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000013173}
13174
Faisal Valiad090d82013-10-07 05:13:48 +000013175// Only block literals, captured statements, and lambda expressions can
13176// capture; other scopes don't work.
13177static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
13178 SourceLocation Loc,
13179 const bool Diagnose, Sema &S) {
Faisal Valia17d19f2013-11-07 05:17:06 +000013180 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13181 return getLambdaAwareParentOfDeclContext(DC);
Alexey Bataevf841bd92014-12-16 07:00:22 +000013182 else if (Var->hasLocalStorage()) {
Faisal Valiad090d82013-10-07 05:13:48 +000013183 if (Diagnose)
13184 diagnoseUncapturableValueReference(S, Loc, Var, DC);
13185 }
Craig Topperc3ec1492014-05-26 06:22:03 +000013186 return nullptr;
Faisal Valiad090d82013-10-07 05:13:48 +000013187}
13188
13189// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13190// certain types of variables (unnamed, variably modified types etc.)
13191// so check for eligibility.
13192static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
13193 SourceLocation Loc,
13194 const bool Diagnose, Sema &S) {
13195
13196 bool IsBlock = isa<BlockScopeInfo>(CSI);
13197 bool IsLambda = isa<LambdaScopeInfo>(CSI);
13198
13199 // Lambdas are not allowed to capture unnamed variables
13200 // (e.g. anonymous unions).
13201 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13202 // assuming that's the intent.
13203 if (IsLambda && !Var->getDeclName()) {
13204 if (Diagnose) {
13205 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13206 S.Diag(Var->getLocation(), diag::note_declared_at);
13207 }
13208 return false;
13209 }
13210
Alexey Bataev39c81e22014-08-28 04:28:19 +000013211 // Prohibit variably-modified types in blocks; they're difficult to deal with.
13212 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
Faisal Valiad090d82013-10-07 05:13:48 +000013213 if (Diagnose) {
Alexey Bataev39c81e22014-08-28 04:28:19 +000013214 S.Diag(Loc, diag::err_ref_vm_type);
Faisal Valiad090d82013-10-07 05:13:48 +000013215 S.Diag(Var->getLocation(), diag::note_previous_decl)
13216 << Var->getDeclName();
13217 }
13218 return false;
13219 }
13220 // Prohibit structs with flexible array members too.
13221 // We cannot capture what is in the tail end of the struct.
13222 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13223 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13224 if (Diagnose) {
13225 if (IsBlock)
13226 S.Diag(Loc, diag::err_ref_flexarray_type);
13227 else
13228 S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13229 << Var->getDeclName();
13230 S.Diag(Var->getLocation(), diag::note_previous_decl)
13231 << Var->getDeclName();
13232 }
13233 return false;
13234 }
13235 }
13236 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13237 // Lambdas and captured statements are not allowed to capture __block
13238 // variables; they don't support the expected semantics.
13239 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13240 if (Diagnose) {
13241 S.Diag(Loc, diag::err_capture_block_variable)
13242 << Var->getDeclName() << !IsLambda;
13243 S.Diag(Var->getLocation(), diag::note_previous_decl)
13244 << Var->getDeclName();
13245 }
13246 return false;
13247 }
13248
13249 return true;
13250}
13251
13252// Returns true if the capture by block was successful.
13253static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
13254 SourceLocation Loc,
13255 const bool BuildAndDiagnose,
13256 QualType &CaptureType,
13257 QualType &DeclRefType,
13258 const bool Nested,
13259 Sema &S) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013260 Expr *CopyExpr = nullptr;
Faisal Valiad090d82013-10-07 05:13:48 +000013261 bool ByRef = false;
13262
13263 // Blocks are not allowed to capture arrays.
13264 if (CaptureType->isArrayType()) {
13265 if (BuildAndDiagnose) {
13266 S.Diag(Loc, diag::err_ref_array_type);
13267 S.Diag(Var->getLocation(), diag::note_previous_decl)
13268 << Var->getDeclName();
13269 }
13270 return false;
13271 }
13272
13273 // Forbid the block-capture of autoreleasing variables.
13274 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13275 if (BuildAndDiagnose) {
13276 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13277 << /*block*/ 0;
13278 S.Diag(Var->getLocation(), diag::note_previous_decl)
13279 << Var->getDeclName();
13280 }
13281 return false;
13282 }
13283 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13284 if (HasBlocksAttr || CaptureType->isReferenceType()) {
13285 // Block capture by reference does not change the capture or
13286 // declaration reference types.
13287 ByRef = true;
13288 } else {
13289 // Block capture by copy introduces 'const'.
13290 CaptureType = CaptureType.getNonReferenceType().withConst();
13291 DeclRefType = CaptureType;
13292
13293 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13294 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13295 // The capture logic needs the destructor, so make sure we mark it.
13296 // Usually this is unnecessary because most local variables have
13297 // their destructors marked at declaration time, but parameters are
13298 // an exception because it's technically only the call site that
13299 // actually requires the destructor.
13300 if (isa<ParmVarDecl>(Var))
13301 S.FinalizeVarWithDestructor(Var, Record);
13302
13303 // Enter a new evaluation context to insulate the copy
13304 // full-expression.
13305 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
13306
13307 // According to the blocks spec, the capture of a variable from
13308 // the stack requires a const copy constructor. This is not true
13309 // of the copy/move done to move a __block variable to the heap.
13310 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13311 DeclRefType.withConst(),
13312 VK_LValue, Loc);
13313
13314 ExprResult Result
13315 = S.PerformCopyInitialization(
13316 InitializedEntity::InitializeBlock(Var->getLocation(),
13317 CaptureType, false),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013318 Loc, DeclRef);
Faisal Valiad090d82013-10-07 05:13:48 +000013319
13320 // Build a full-expression copy expression if initialization
13321 // succeeded and used a non-trivial constructor. Recover from
13322 // errors by pretending that the copy isn't necessary.
13323 if (!Result.isInvalid() &&
13324 !cast<CXXConstructExpr>(Result.get())->getConstructor()
13325 ->isTrivial()) {
13326 Result = S.MaybeCreateExprWithCleanups(Result);
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013327 CopyExpr = Result.get();
Faisal Valiad090d82013-10-07 05:13:48 +000013328 }
13329 }
13330 }
13331 }
13332
13333 // Actually capture the variable.
13334 if (BuildAndDiagnose)
13335 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
13336 SourceLocation(), CaptureType, CopyExpr);
13337
13338 return true;
13339
13340}
13341
13342
13343/// \brief Capture the given variable in the captured region.
13344static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13345 VarDecl *Var,
13346 SourceLocation Loc,
13347 const bool BuildAndDiagnose,
13348 QualType &CaptureType,
13349 QualType &DeclRefType,
Alexey Bataev07649fb2014-12-16 08:01:48 +000013350 const bool RefersToCapturedVariable,
Faisal Valiad090d82013-10-07 05:13:48 +000013351 Sema &S) {
13352
13353 // By default, capture variables by reference.
13354 bool ByRef = true;
13355 // Using an LValue reference type is consistent with Lambdas (see below).
Samuel Antao4af1b7b2015-12-02 17:44:43 +000013356 if (S.getLangOpts().OpenMP) {
13357 ByRef = S.IsOpenMPCapturedByRef(Var, RSI);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000013358 if (S.IsOpenMPCapturedDecl(Var))
Samuel Antao4af1b7b2015-12-02 17:44:43 +000013359 DeclRefType = DeclRefType.getUnqualifiedType();
13360 }
13361
13362 if (ByRef)
13363 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13364 else
13365 CaptureType = DeclRefType;
13366
Craig Topperc3ec1492014-05-26 06:22:03 +000013367 Expr *CopyExpr = nullptr;
Faisal Valiad090d82013-10-07 05:13:48 +000013368 if (BuildAndDiagnose) {
13369 // The current implementation assumes that all variables are captured
Nico Weber83ea0122014-05-03 21:57:40 +000013370 // by references. Since there is no capture by copy, no expression
13371 // evaluation will be needed.
Faisal Valiad090d82013-10-07 05:13:48 +000013372 RecordDecl *RD = RSI->TheRecordDecl;
13373
13374 FieldDecl *Field
Craig Topperc3ec1492014-05-26 06:22:03 +000013375 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
Faisal Valiad090d82013-10-07 05:13:48 +000013376 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
Craig Topperc3ec1492014-05-26 06:22:03 +000013377 nullptr, false, ICIS_NoInit);
Faisal Valiad090d82013-10-07 05:13:48 +000013378 Field->setImplicit(true);
13379 Field->setAccess(AS_private);
13380 RD->addDecl(Field);
13381
Alexey Bataev07649fb2014-12-16 08:01:48 +000013382 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
Faisal Valiad090d82013-10-07 05:13:48 +000013383 DeclRefType, VK_LValue, Loc);
13384 Var->setReferenced(true);
13385 Var->markUsed(S.Context);
13386 }
13387
13388 // Actually capture the variable.
13389 if (BuildAndDiagnose)
Alexey Bataev07649fb2014-12-16 08:01:48 +000013390 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
Faisal Valiad090d82013-10-07 05:13:48 +000013391 SourceLocation(), CaptureType, CopyExpr);
13392
13393
13394 return true;
13395}
13396
13397/// \brief Create a field within the lambda class for the variable
Richard Smithc38498f2015-04-27 21:27:54 +000013398/// being captured.
Faisal Vali084c9122016-03-23 17:39:51 +000013399static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
Richard Smithc38498f2015-04-27 21:27:54 +000013400 QualType FieldType, QualType DeclRefType,
13401 SourceLocation Loc,
13402 bool RefersToCapturedVariable) {
Douglas Gregor81495f32012-02-12 18:42:33 +000013403 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregor81495f32012-02-12 18:42:33 +000013404
Douglas Gregorabecb9c2012-02-09 01:56:40 +000013405 // Build the non-static data member.
13406 FieldDecl *Field
Craig Topperc3ec1492014-05-26 06:22:03 +000013407 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
Douglas Gregorabecb9c2012-02-09 01:56:40 +000013408 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Craig Topperc3ec1492014-05-26 06:22:03 +000013409 nullptr, false, ICIS_NoInit);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000013410 Field->setImplicit(true);
13411 Field->setAccess(AS_private);
Douglas Gregor3d23f7882012-02-09 02:12:34 +000013412 Lambda->addDecl(Field);
Douglas Gregor199cec72012-02-09 02:45:47 +000013413}
Douglas Gregorabecb9c2012-02-09 01:56:40 +000013414
Faisal Valiad090d82013-10-07 05:13:48 +000013415/// \brief Capture the given variable in the lambda.
13416static bool captureInLambda(LambdaScopeInfo *LSI,
13417 VarDecl *Var,
13418 SourceLocation Loc,
13419 const bool BuildAndDiagnose,
13420 QualType &CaptureType,
13421 QualType &DeclRefType,
Alexey Bataev07649fb2014-12-16 08:01:48 +000013422 const bool RefersToCapturedVariable,
Faisal Valiad090d82013-10-07 05:13:48 +000013423 const Sema::TryCaptureKind Kind,
13424 SourceLocation EllipsisLoc,
13425 const bool IsTopScope,
13426 Sema &S) {
13427
13428 // Determine whether we are capturing by reference or by value.
13429 bool ByRef = false;
13430 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13431 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13432 } else {
13433 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13434 }
13435
13436 // Compute the type of the field that will capture this variable.
13437 if (ByRef) {
13438 // C++11 [expr.prim.lambda]p15:
13439 // An entity is captured by reference if it is implicitly or
13440 // explicitly captured but not captured by copy. It is
13441 // unspecified whether additional unnamed non-static data
13442 // members are declared in the closure type for entities
13443 // captured by reference.
13444 //
13445 // FIXME: It is not clear whether we want to build an lvalue reference
13446 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13447 // to do the former, while EDG does the latter. Core issue 1249 will
13448 // clarify, but for now we follow GCC because it's a more permissive and
13449 // easily defensible position.
13450 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13451 } else {
13452 // C++11 [expr.prim.lambda]p14:
13453 // For each entity captured by copy, an unnamed non-static
13454 // data member is declared in the closure type. The
13455 // declaration order of these members is unspecified. The type
13456 // of such a data member is the type of the corresponding
13457 // captured entity if the entity is not a reference to an
13458 // object, or the referenced type otherwise. [Note: If the
13459 // captured entity is a reference to a function, the
13460 // corresponding data member is also a reference to a
13461 // function. - end note ]
13462 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13463 if (!RefType->getPointeeType()->isFunctionType())
13464 CaptureType = RefType->getPointeeType();
13465 }
13466
13467 // Forbid the lambda copy-capture of autoreleasing variables.
13468 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13469 if (BuildAndDiagnose) {
13470 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13471 S.Diag(Var->getLocation(), diag::note_previous_decl)
13472 << Var->getDeclName();
13473 }
13474 return false;
13475 }
Douglas Gregor71fe0e82013-10-11 04:25:21 +000013476
Richard Smith111d3482014-01-21 23:27:46 +000013477 // Make sure that by-copy captures are of a complete and non-abstract type.
13478 if (BuildAndDiagnose) {
13479 if (!CaptureType->isDependentType() &&
13480 S.RequireCompleteType(Loc, CaptureType,
13481 diag::err_capture_of_incomplete_type,
13482 Var->getDeclName()))
13483 return false;
13484
13485 if (S.RequireNonAbstractType(Loc, CaptureType,
13486 diag::err_capture_of_abstract_type))
13487 return false;
13488 }
Faisal Valiad090d82013-10-07 05:13:48 +000013489 }
13490
13491 // Capture this variable in the lambda.
Richard Smithc38498f2015-04-27 21:27:54 +000013492 if (BuildAndDiagnose)
Faisal Vali084c9122016-03-23 17:39:51 +000013493 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
Richard Smithc38498f2015-04-27 21:27:54 +000013494 RefersToCapturedVariable);
Faisal Valiad090d82013-10-07 05:13:48 +000013495
13496 // Compute the type of a reference to this captured variable.
13497 if (ByRef)
13498 DeclRefType = CaptureType.getNonReferenceType();
13499 else {
13500 // C++ [expr.prim.lambda]p5:
13501 // The closure type for a lambda-expression has a public inline
13502 // function call operator [...]. This function call operator is
13503 // declared const (9.3.1) if and only if the lambda-expression’s
13504 // parameter-declaration-clause is not followed by mutable.
13505 DeclRefType = CaptureType.getNonReferenceType();
13506 if (!LSI->Mutable && !CaptureType->isReferenceType())
13507 DeclRefType.addConst();
13508 }
13509
13510 // Add the capture.
13511 if (BuildAndDiagnose)
Alexey Bataev07649fb2014-12-16 08:01:48 +000013512 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
Richard Smithc38498f2015-04-27 21:27:54 +000013513 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
Faisal Valiad090d82013-10-07 05:13:48 +000013514
13515 return true;
13516}
13517
Richard Smithc38498f2015-04-27 21:27:54 +000013518bool Sema::tryCaptureVariable(
13519 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13520 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13521 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13522 // An init-capture is notionally from the context surrounding its
13523 // declaration, but its parent DC is the lambda class.
13524 DeclContext *VarDC = Var->getDeclContext();
13525 if (Var->isInitCapture())
13526 VarDC = VarDC->getParent();
Douglas Gregor81495f32012-02-12 18:42:33 +000013527
Eli Friedman24af8502012-02-03 22:47:37 +000013528 DeclContext *DC = CurContext;
Faisal Valia17d19f2013-11-07 05:17:06 +000013529 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
13530 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
13531 // We need to sync up the Declaration Context with the
13532 // FunctionScopeIndexToStopAt
13533 if (FunctionScopeIndexToStopAt) {
13534 unsigned FSIndex = FunctionScopes.size() - 1;
13535 while (FSIndex != MaxFunctionScopesIndex) {
13536 DC = getLambdaAwareParentOfDeclContext(DC);
13537 --FSIndex;
13538 }
13539 }
Faisal Valiad090d82013-10-07 05:13:48 +000013540
Faisal Valia17d19f2013-11-07 05:17:06 +000013541
Richard Smithc38498f2015-04-27 21:27:54 +000013542 // If the variable is declared in the current context, there is no need to
13543 // capture it.
13544 if (VarDC == DC) return true;
Alexey Bataevf841bd92014-12-16 07:00:22 +000013545
13546 // Capture global variables if it is required to use private copy of this
13547 // variable.
13548 bool IsGlobal = !Var->hasLocalStorage();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000013549 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
Alexey Bataevf841bd92014-12-16 07:00:22 +000013550 return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000013551
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013552 // Walk up the stack to determine whether we can capture the variable,
13553 // performing the "simple" checks that don't depend on type. We stop when
13554 // we've either hit the declared scope of the variable or find an existing
Faisal Valiad090d82013-10-07 05:13:48 +000013555 // capture of that variable. We start from the innermost capturing-entity
13556 // (the DC) and ensure that all intervening capturing-entities
13557 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
13558 // declcontext can either capture the variable or have already captured
13559 // the variable.
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013560 CaptureType = Var->getType();
13561 DeclRefType = CaptureType.getNonReferenceType();
Richard Smithc38498f2015-04-27 21:27:54 +000013562 bool Nested = false;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013563 bool Explicit = (Kind != TryCapture_Implicit);
Faisal Valiad090d82013-10-07 05:13:48 +000013564 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
Alexey Bataevaac108a2015-06-23 04:51:00 +000013565 unsigned OpenMPLevel = 0;
Eli Friedman9bb33f52012-02-03 02:04:35 +000013566 do {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000013567 // Only block literals, captured statements, and lambda expressions can
13568 // capture; other scopes don't work.
Faisal Valiad090d82013-10-07 05:13:48 +000013569 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
13570 ExprLoc,
13571 BuildAndDiagnose,
13572 *this);
Alexey Bataevf841bd92014-12-16 07:00:22 +000013573 // We need to check for the parent *first* because, if we *have*
13574 // private-captured a global variable, we need to recursively capture it in
13575 // intermediate blocks, lambdas, etc.
13576 if (!ParentDC) {
13577 if (IsGlobal) {
13578 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
13579 break;
13580 }
13581 return true;
13582 }
13583
Faisal Valiad090d82013-10-07 05:13:48 +000013584 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
13585 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
Eli Friedman9bb33f52012-02-03 02:04:35 +000013586
Eli Friedman9bb33f52012-02-03 02:04:35 +000013587
Eli Friedman24af8502012-02-03 22:47:37 +000013588 // Check whether we've already captured it.
Faisal Valiad090d82013-10-07 05:13:48 +000013589 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
13590 DeclRefType))
Eli Friedman9bb33f52012-02-03 02:04:35 +000013591 break;
Faisal Valia17d19f2013-11-07 05:17:06 +000013592 // If we are instantiating a generic lambda call operator body,
13593 // we do not want to capture new variables. What was captured
13594 // during either a lambdas transformation or initial parsing
13595 // should be used.
13596 if (isGenericLambdaCallOperatorSpecialization(DC)) {
13597 if (BuildAndDiagnose) {
13598 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13599 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
13600 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13601 Diag(Var->getLocation(), diag::note_previous_decl)
13602 << Var->getDeclName();
13603 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
13604 } else
13605 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
13606 }
13607 return true;
13608 }
Faisal Valiad090d82013-10-07 05:13:48 +000013609 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13610 // certain types of variables (unnamed, variably modified types etc.)
13611 // so check for eligibility.
13612 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
Alexey Bataevaca7fcf2014-06-30 02:55:54 +000013613 return true;
13614
13615 // Try to capture variable-length arrays types.
13616 if (Var->getType()->isVariablyModifiedType()) {
13617 // We're going to walk down into the type and look for VLA
13618 // expressions.
13619 QualType QTy = Var->getType();
13620 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
13621 QTy = PVD->getOriginalType();
Alexey Bataev93a546a2016-01-21 12:54:48 +000013622 captureVariablyModifiedType(Context, QTy, CSI);
Alexey Bataevaca7fcf2014-06-30 02:55:54 +000013623 }
13624
Alexey Bataevb5001012015-09-03 10:21:46 +000013625 if (getLangOpts().OpenMP) {
13626 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13627 // OpenMP private variables should not be captured in outer scope, so
Samuel Antao4be30e92015-10-02 17:14:03 +000013628 // just break here. Similarly, global variables that are captured in a
13629 // target region should not be captured outside the scope of the region.
Alexey Bataevb5001012015-09-03 10:21:46 +000013630 if (RSI->CapRegionKind == CR_OpenMP) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000013631 auto isTargetCap = isOpenMPTargetCapturedDecl(Var, OpenMPLevel);
Samuel Antao4be30e92015-10-02 17:14:03 +000013632 // When we detect target captures we are looking from inside the
13633 // target region, therefore we need to propagate the capture from the
13634 // enclosing region. Therefore, the capture is not initially nested.
13635 if (isTargetCap)
13636 FunctionScopesIndex--;
13637
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000013638 if (isTargetCap || isOpenMPPrivateDecl(Var, OpenMPLevel)) {
Samuel Antao4be30e92015-10-02 17:14:03 +000013639 Nested = !isTargetCap;
Alexey Bataevb5001012015-09-03 10:21:46 +000013640 DeclRefType = DeclRefType.getUnqualifiedType();
13641 CaptureType = Context.getLValueReferenceType(DeclRefType);
13642 break;
13643 }
13644 ++OpenMPLevel;
13645 }
13646 }
13647 }
Douglas Gregor81495f32012-02-12 18:42:33 +000013648 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
Faisal Valiad090d82013-10-07 05:13:48 +000013649 // No capture-default, and this is not an explicit capture
13650 // so cannot capture this variable.
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013651 if (BuildAndDiagnose) {
Faisal Valiad090d82013-10-07 05:13:48 +000013652 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
Douglas Gregor81495f32012-02-12 18:42:33 +000013653 Diag(Var->getLocation(), diag::note_previous_decl)
13654 << Var->getDeclName();
Richard Trieu2334a302016-03-05 04:04:57 +000013655 if (cast<LambdaScopeInfo>(CSI)->Lambda)
13656 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
13657 diag::note_lambda_decl);
Faisal Valia17d19f2013-11-07 05:17:06 +000013658 // FIXME: If we error out because an outer lambda can not implicitly
13659 // capture a variable that an inner lambda explicitly captures, we
13660 // should have the inner lambda do the explicit capture - because
13661 // it makes for cleaner diagnostics later. This would purely be done
13662 // so that the diagnostic does not misleadingly claim that a variable
13663 // can not be captured by a lambda implicitly even though it is captured
13664 // explicitly. Suggestion:
13665 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
13666 // at the function head
13667 // - cache the StartingDeclContext - this must be a lambda
13668 // - captureInLambda in the innermost lambda the variable.
Douglas Gregor81495f32012-02-12 18:42:33 +000013669 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013670 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000013671 }
13672
13673 FunctionScopesIndex--;
13674 DC = ParentDC;
13675 Explicit = false;
Richard Smithc38498f2015-04-27 21:27:54 +000013676 } while (!VarDC->Equals(DC));
Douglas Gregor81495f32012-02-12 18:42:33 +000013677
Faisal Valiad090d82013-10-07 05:13:48 +000013678 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
13679 // computing the type of the capture at each step, checking type-specific
13680 // requirements, and adding captures if requested.
13681 // If the variable had already been captured previously, we start capturing
13682 // at the lambda nested within that one.
13683 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013684 ++I) {
13685 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor812d8f62012-02-18 05:51:20 +000013686
Faisal Valiad090d82013-10-07 05:13:48 +000013687 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
13688 if (!captureInBlock(BSI, Var, ExprLoc,
13689 BuildAndDiagnose, CaptureType,
13690 DeclRefType, Nested, *this))
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013691 return true;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013692 Nested = true;
Faisal Valiad090d82013-10-07 05:13:48 +000013693 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13694 if (!captureInCapturedRegion(RSI, Var, ExprLoc,
13695 BuildAndDiagnose, CaptureType,
13696 DeclRefType, Nested, *this))
John McCall67cd5e02012-03-30 05:23:48 +000013697 return true;
Faisal Valiad090d82013-10-07 05:13:48 +000013698 Nested = true;
13699 } else {
13700 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13701 if (!captureInLambda(LSI, Var, ExprLoc,
13702 BuildAndDiagnose, CaptureType,
13703 DeclRefType, Nested, Kind, EllipsisLoc,
13704 /*IsTopScope*/I == N - 1, *this))
13705 return true;
13706 Nested = true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000013707 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000013708 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013709 return false;
13710}
13711
13712bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
13713 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
13714 QualType CaptureType;
13715 QualType DeclRefType;
13716 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
13717 /*BuildAndDiagnose=*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +000013718 DeclRefType, nullptr);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013719}
13720
Alexey Bataevf841bd92014-12-16 07:00:22 +000013721bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
13722 QualType CaptureType;
13723 QualType DeclRefType;
13724 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13725 /*BuildAndDiagnose=*/false, CaptureType,
13726 DeclRefType, nullptr);
13727}
13728
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013729QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
13730 QualType CaptureType;
13731 QualType DeclRefType;
13732
13733 // Determine whether we can capture this variable.
13734 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
Faisal Valia17d19f2013-11-07 05:17:06 +000013735 /*BuildAndDiagnose=*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +000013736 DeclRefType, nullptr))
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013737 return QualType();
13738
13739 return DeclRefType;
Eli Friedman9bb33f52012-02-03 02:04:35 +000013740}
13741
Eli Friedman3bda6b12012-02-02 23:15:15 +000013742
Eli Friedman9bb33f52012-02-03 02:04:35 +000013743
Faisal Valia17d19f2013-11-07 05:17:06 +000013744// If either the type of the variable or the initializer is dependent,
13745// return false. Otherwise, determine whether the variable is a constant
13746// expression. Use this if you need to know if a variable that might or
13747// might not be dependent is truly a constant expression.
13748static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
13749 ASTContext &Context) {
13750
13751 if (Var->getType()->isDependentType())
13752 return false;
Craig Topperc3ec1492014-05-26 06:22:03 +000013753 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +000013754 Var->getAnyInitializer(DefVD);
13755 if (!DefVD)
13756 return false;
13757 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
13758 Expr *Init = cast<Expr>(Eval->Value);
13759 if (Init->isValueDependent())
13760 return false;
13761 return IsVariableAConstantExpression(Var, Context);
Eli Friedman3bda6b12012-02-02 23:15:15 +000013762}
13763
Faisal Valia17d19f2013-11-07 05:17:06 +000013764
Eli Friedman3bda6b12012-02-02 23:15:15 +000013765void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
13766 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
13767 // an object that satisfies the requirements for appearing in a
13768 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
13769 // is immediately applied." This function handles the lvalue-to-rvalue
13770 // conversion part.
13771 MaybeODRUseExprs.erase(E->IgnoreParens());
Faisal Valia17d19f2013-11-07 05:17:06 +000013772
13773 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
13774 // to a variable that is a constant expression, and if so, identify it as
13775 // a reference to a variable that does not involve an odr-use of that
13776 // variable.
13777 if (LambdaScopeInfo *LSI = getCurLambda()) {
13778 Expr *SansParensExpr = E->IgnoreParens();
Craig Topperc3ec1492014-05-26 06:22:03 +000013779 VarDecl *Var = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +000013780 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
13781 Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
13782 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
13783 Var = dyn_cast<VarDecl>(ME->getMemberDecl());
13784
13785 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
13786 LSI->markVariableExprAsNonODRUsed(SansParensExpr);
13787 }
Eli Friedman3bda6b12012-02-02 23:15:15 +000013788}
13789
Eli Friedmanc6237c62012-02-29 03:16:56 +000013790ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
Kaelyn Takatab16e6322014-11-20 22:06:40 +000013791 Res = CorrectDelayedTyposInExpr(Res);
13792
Eli Friedmanc6237c62012-02-29 03:16:56 +000013793 if (!Res.isUsable())
13794 return Res;
13795
13796 // If a constant-expression is a reference to a variable where we delay
13797 // deciding whether it is an odr-use, just assume we will apply the
13798 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
13799 // (a non-type template argument), we have special handling anyway.
13800 UpdateMarkingForLValueToRValue(Res.get());
13801 return Res;
13802}
13803
Eli Friedman3bda6b12012-02-02 23:15:15 +000013804void Sema::CleanupVarDeclMarking() {
Craig Topperdfe29ae2015-12-21 06:35:56 +000013805 for (Expr *E : MaybeODRUseExprs) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000013806 VarDecl *Var;
13807 SourceLocation Loc;
Craig Topperdfe29ae2015-12-21 06:35:56 +000013808 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000013809 Var = cast<VarDecl>(DRE->getDecl());
13810 Loc = DRE->getLocation();
Craig Topperdfe29ae2015-12-21 06:35:56 +000013811 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000013812 Var = cast<VarDecl>(ME->getMemberDecl());
13813 Loc = ME->getMemberLoc();
13814 } else {
Larisse Voufo4e673c92014-07-29 18:45:54 +000013815 llvm_unreachable("Unexpected expression");
Eli Friedman3bda6b12012-02-02 23:15:15 +000013816 }
13817
Craig Topperc3ec1492014-05-26 06:22:03 +000013818 MarkVarDeclODRUsed(Var, Loc, *this,
13819 /*MaxFunctionScopeIndex Pointer*/ nullptr);
Eli Friedman3bda6b12012-02-02 23:15:15 +000013820 }
13821
13822 MaybeODRUseExprs.clear();
13823}
13824
Faisal Valia17d19f2013-11-07 05:17:06 +000013825
Eli Friedman3bda6b12012-02-02 23:15:15 +000013826static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
13827 VarDecl *Var, Expr *E) {
Benjamin Kramercd502b52013-11-07 11:03:53 +000013828 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
13829 "Invalid Expr argument to DoMarkVarDeclReferenced");
Eli Friedmanfa0df832012-02-02 03:46:19 +000013830 Var->setReferenced();
13831
Larisse Voufob6fab262014-07-29 18:44:19 +000013832 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
Larisse Voufof73da982014-07-30 00:49:55 +000013833 bool MarkODRUsed = true;
Larisse Voufob6fab262014-07-29 18:44:19 +000013834
Richard Smith5ef98f72014-02-03 23:22:05 +000013835 // If the context is not potentially evaluated, this is not an odr-use and
13836 // does not trigger instantiation.
Faisal Valia17d19f2013-11-07 05:17:06 +000013837 if (!IsPotentiallyEvaluatedContext(SemaRef)) {
Richard Smith5ef98f72014-02-03 23:22:05 +000013838 if (SemaRef.isUnevaluatedContext())
13839 return;
Faisal Valia17d19f2013-11-07 05:17:06 +000013840
Richard Smith5ef98f72014-02-03 23:22:05 +000013841 // If we don't yet know whether this context is going to end up being an
13842 // evaluated context, and we're referencing a variable from an enclosing
13843 // scope, add a potential capture.
13844 //
13845 // FIXME: Is this necessary? These contexts are only used for default
13846 // arguments, where local variables can't be used.
13847 const bool RefersToEnclosingScope =
13848 (SemaRef.CurContext != Var->getDeclContext() &&
Larisse Voufob6fab262014-07-29 18:44:19 +000013849 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
13850 if (RefersToEnclosingScope) {
13851 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
13852 // If a variable could potentially be odr-used, defer marking it so
13853 // until we finish analyzing the full expression for any
13854 // lvalue-to-rvalue
13855 // or discarded value conversions that would obviate odr-use.
13856 // Add it to the list of potential captures that will be analyzed
13857 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
13858 // unless the variable is a reference that was initialized by a constant
13859 // expression (this will never need to be captured or odr-used).
13860 assert(E && "Capture variable should be used in an expression.");
13861 if (!Var->getType()->isReferenceType() ||
13862 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
13863 LSI->addPotentialCapture(E->IgnoreParens());
13864 }
Richard Smith5ef98f72014-02-03 23:22:05 +000013865 }
Larisse Voufob6fab262014-07-29 18:44:19 +000013866
13867 if (!isTemplateInstantiation(TSK))
Craig Topperbd44cd92015-12-08 04:33:04 +000013868 return;
Larisse Voufof73da982014-07-30 00:49:55 +000013869
13870 // Instantiate, but do not mark as odr-used, variable templates.
13871 MarkODRUsed = false;
Faisal Valia17d19f2013-11-07 05:17:06 +000013872 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000013873
Larisse Voufo39a1e502013-08-06 01:03:05 +000013874 VarTemplateSpecializationDecl *VarSpec =
13875 dyn_cast<VarTemplateSpecializationDecl>(Var);
Richard Smith8809a0c2013-09-27 20:14:12 +000013876 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
13877 "Can't instantiate a partial template specialization.");
Larisse Voufo39a1e502013-08-06 01:03:05 +000013878
Richard Smith6739a102016-05-05 00:56:12 +000013879 // If this might be a member specialization of a static data member, check
13880 // the specialization is visible. We already did the checks for variable
13881 // template specializations when we created them.
13882 if (TSK != TSK_Undeclared && !isa<VarTemplateSpecializationDecl>(Var))
13883 SemaRef.checkSpecializationVisibility(Loc, Var);
13884
Richard Smith5ef98f72014-02-03 23:22:05 +000013885 // Perform implicit instantiation of static data members, static data member
13886 // templates of class templates, and variable template specializations. Delay
13887 // instantiations of variable templates, except for those that could be used
13888 // in a constant expression.
Richard Smith8809a0c2013-09-27 20:14:12 +000013889 if (isTemplateInstantiation(TSK)) {
13890 bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
Larisse Voufo39a1e502013-08-06 01:03:05 +000013891
Richard Smith8809a0c2013-09-27 20:14:12 +000013892 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
13893 if (Var->getPointOfInstantiation().isInvalid()) {
13894 // This is a modification of an existing AST node. Notify listeners.
13895 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
13896 L->StaticDataMemberInstantiated(Var);
13897 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
13898 // Don't bother trying to instantiate it again, unless we might need
13899 // its initializer before we get to the end of the TU.
13900 TryInstantiating = false;
Larisse Voufo39a1e502013-08-06 01:03:05 +000013901 }
13902
Richard Smith8809a0c2013-09-27 20:14:12 +000013903 if (Var->getPointOfInstantiation().isInvalid())
13904 Var->setTemplateSpecializationKind(TSK, Loc);
13905
13906 if (TryInstantiating) {
13907 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
Larisse Voufo39a1e502013-08-06 01:03:05 +000013908 bool InstantiationDependent = false;
13909 bool IsNonDependent =
13910 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
13911 VarSpec->getTemplateArgsInfo(), InstantiationDependent)
13912 : true;
13913
13914 // Do not instantiate specializations that are still type-dependent.
13915 if (IsNonDependent) {
13916 if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
13917 // Do not defer instantiations of variables which could be used in a
13918 // constant expression.
13919 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
13920 } else {
13921 SemaRef.PendingInstantiations
13922 .push_back(std::make_pair(Var, PointOfInstantiation));
13923 }
Richard Smithd3cf2382012-02-15 02:42:50 +000013924 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000013925 }
13926 }
Richard Smith5ef98f72014-02-03 23:22:05 +000013927
Richard Smith6739a102016-05-05 00:56:12 +000013928 if (!MarkODRUsed)
13929 return;
Larisse Voufof73da982014-07-30 00:49:55 +000013930
Richard Smith5a1104b2012-10-20 01:38:33 +000013931 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
13932 // the requirements for appearing in a constant expression (5.19) and, if
13933 // it is an object, the lvalue-to-rvalue conversion (4.1)
Eli Friedman3bda6b12012-02-02 23:15:15 +000013934 // is immediately applied." We check the first part here, and
13935 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
13936 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith5a1104b2012-10-20 01:38:33 +000013937 // C++03 depends on whether we get the C++03 version correct. The second
13938 // part does not apply to references, since they are not objects.
Faisal Valia17d19f2013-11-07 05:17:06 +000013939 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
Richard Smith5ef98f72014-02-03 23:22:05 +000013940 // A reference initialized by a constant expression can never be
Faisal Valia17d19f2013-11-07 05:17:06 +000013941 // odr-used, so simply ignore it.
Richard Smith5a1104b2012-10-20 01:38:33 +000013942 if (!Var->getType()->isReferenceType())
13943 SemaRef.MaybeODRUseExprs.insert(E);
Richard Smith5ef98f72014-02-03 23:22:05 +000013944 } else
Craig Topperc3ec1492014-05-26 06:22:03 +000013945 MarkVarDeclODRUsed(Var, Loc, SemaRef,
13946 /*MaxFunctionScopeIndex ptr*/ nullptr);
Eli Friedman3bda6b12012-02-02 23:15:15 +000013947}
Eli Friedmanfa0df832012-02-02 03:46:19 +000013948
Eli Friedman3bda6b12012-02-02 23:15:15 +000013949/// \brief Mark a variable referenced, and check whether it is odr-used
13950/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
13951/// used directly for normal expressions referring to VarDecl.
13952void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013953 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
Eli Friedmanfa0df832012-02-02 03:46:19 +000013954}
13955
13956static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
Richard Smith0e32c522016-03-25 22:29:27 +000013957 Decl *D, Expr *E, bool MightBeOdrUse) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013958 if (SemaRef.isInOpenMPDeclareTargetContext())
13959 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
13960
Eli Friedman3bda6b12012-02-02 23:15:15 +000013961 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
13962 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
13963 return;
13964 }
13965
Richard Smith0e32c522016-03-25 22:29:27 +000013966 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
Rafael Espindola49e860b2012-06-26 17:45:31 +000013967
13968 // If this is a call to a method via a cast, also mark the method in the
13969 // derived class used in case codegen can devirtualize the call.
13970 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13971 if (!ME)
13972 return;
13973 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
13974 if (!MD)
13975 return;
Reid Kleckner5c553e32014-09-16 22:23:33 +000013976 // Only attempt to devirtualize if this is truly a virtual call.
Davide Italianoccb37382015-07-14 23:36:10 +000013977 bool IsVirtualCall = MD->isVirtual() &&
13978 ME->performsVirtualDispatch(SemaRef.getLangOpts());
Reid Kleckner5c553e32014-09-16 22:23:33 +000013979 if (!IsVirtualCall)
13980 return;
Rafael Espindola49e860b2012-06-26 17:45:31 +000013981 const Expr *Base = ME->getBase();
Rafael Espindolab7f5a9c2012-06-27 18:18:05 +000013982 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Rafael Espindola49e860b2012-06-26 17:45:31 +000013983 if (!MostDerivedClassDecl)
13984 return;
13985 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
Nick Lewyckyb7444cd2013-02-14 00:55:17 +000013986 if (!DM || DM->isPure())
Rafael Espindolaa245edc2012-06-27 17:44:39 +000013987 return;
Richard Smith0e32c522016-03-25 22:29:27 +000013988 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
Douglas Gregord3b672c2012-02-16 01:06:16 +000013989}
Eli Friedmanfa0df832012-02-02 03:46:19 +000013990
Eli Friedmanfa0df832012-02-02 03:46:19 +000013991/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
13992void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
Nick Lewycky45b50522013-02-02 00:25:55 +000013993 // TODO: update this with DR# once a defect report is filed.
13994 // C++11 defect. The address of a pure member should not be an ODR use, even
13995 // if it's a qualified reference.
13996 bool OdrUse = true;
13997 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
Nick Lewycky192542c2013-02-05 06:20:31 +000013998 if (Method->isVirtual())
Nick Lewycky45b50522013-02-02 00:25:55 +000013999 OdrUse = false;
14000 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
Eli Friedmanfa0df832012-02-02 03:46:19 +000014001}
14002
14003/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14004void Sema::MarkMemberReferenced(MemberExpr *E) {
Nick Lewycky60bd4be2013-01-31 03:15:20 +000014005 // C++11 [basic.def.odr]p2:
Nick Lewycky35d23592013-01-31 01:34:31 +000014006 // A non-overloaded function whose name appears as a potentially-evaluated
14007 // expression or a member of a set of candidate functions, if selected by
14008 // overload resolution when referred to from a potentially-evaluated
14009 // expression, is odr-used, unless it is a pure virtual function and its
14010 // name is not explicitly qualified.
Richard Smith0e32c522016-03-25 22:29:27 +000014011 bool MightBeOdrUse = true;
Davide Italianoccb37382015-07-14 23:36:10 +000014012 if (E->performsVirtualDispatch(getLangOpts())) {
Nick Lewycky35d23592013-01-31 01:34:31 +000014013 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14014 if (Method->isPure())
Richard Smith0e32c522016-03-25 22:29:27 +000014015 MightBeOdrUse = false;
Nick Lewycky35d23592013-01-31 01:34:31 +000014016 }
Nick Lewyckya096b142013-02-12 08:08:54 +000014017 SourceLocation Loc = E->getMemberLoc().isValid() ?
14018 E->getMemberLoc() : E->getLocStart();
Richard Smith0e32c522016-03-25 22:29:27 +000014019 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
Eli Friedmanfa0df832012-02-02 03:46:19 +000014020}
14021
Douglas Gregorf02455e2012-02-10 09:26:04 +000014022/// \brief Perform marking for a reference to an arbitrary declaration. It
Nico Weber83ea0122014-05-03 21:57:40 +000014023/// marks the declaration referenced, and performs odr-use checking for
14024/// functions and variables. This method should not be used when building a
14025/// normal expression which refers to a variable.
Richard Smith0e32c522016-03-25 22:29:27 +000014026void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14027 bool MightBeOdrUse) {
14028 if (MightBeOdrUse) {
Nico Weber8bf410f2014-08-27 17:04:39 +000014029 if (auto *VD = dyn_cast<VarDecl>(D)) {
Nick Lewycky45b50522013-02-02 00:25:55 +000014030 MarkVariableReferenced(Loc, VD);
14031 return;
14032 }
Nico Weber8bf410f2014-08-27 17:04:39 +000014033 }
14034 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
Richard Smith0e32c522016-03-25 22:29:27 +000014035 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
Nico Weber8bf410f2014-08-27 17:04:39 +000014036 return;
Nick Lewycky45b50522013-02-02 00:25:55 +000014037 }
14038 D->setReferenced();
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000014039}
Anders Carlsson7f84ed92009-10-09 23:51:55 +000014040
Douglas Gregor5597ab42010-05-07 23:12:07 +000014041namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +000014042 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +000014043 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +000014044 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +000014045 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14046 Sema &S;
14047 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +000014048
Douglas Gregor5597ab42010-05-07 23:12:07 +000014049 public:
14050 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +000014051
Douglas Gregor5597ab42010-05-07 23:12:07 +000014052 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +000014053
14054 bool TraverseTemplateArgument(const TemplateArgument &Arg);
14055 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +000014056 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000014057}
Douglas Gregor5597ab42010-05-07 23:12:07 +000014058
Chandler Carruthaf80f662010-06-09 08:17:30 +000014059bool MarkReferencedDecls::TraverseTemplateArgument(
Nico Weber83ea0122014-05-03 21:57:40 +000014060 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000014061 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +000014062 if (Decl *D = Arg.getAsDecl())
Nick Lewycky45b50522013-02-02 00:25:55 +000014063 S.MarkAnyDeclReferenced(Loc, D, true);
Douglas Gregor5597ab42010-05-07 23:12:07 +000014064 }
Chandler Carruthaf80f662010-06-09 08:17:30 +000014065
14066 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +000014067}
14068
Chandler Carruthaf80f662010-06-09 08:17:30 +000014069bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000014070 if (ClassTemplateSpecializationDecl *Spec
14071 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
14072 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +000014073 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +000014074 }
14075
Chandler Carruthc65667c2010-06-10 10:31:57 +000014076 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +000014077}
14078
14079void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14080 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +000014081 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +000014082}
14083
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014084namespace {
14085 /// \brief Helper class that marks all of the declarations referenced by
14086 /// potentially-evaluated subexpressions as "referenced".
14087 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14088 Sema &S;
Douglas Gregor680e9e02012-02-21 19:11:17 +000014089 bool SkipLocalVariables;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014090
14091 public:
14092 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14093
Douglas Gregor680e9e02012-02-21 19:11:17 +000014094 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
14095 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014096
14097 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregor680e9e02012-02-21 19:11:17 +000014098 // If we were asked not to visit local variables, don't.
14099 if (SkipLocalVariables) {
14100 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14101 if (VD->hasLocalStorage())
14102 return;
14103 }
14104
Eli Friedmanfa0df832012-02-02 03:46:19 +000014105 S.MarkDeclRefReferenced(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014106 }
Nico Weber83ea0122014-05-03 21:57:40 +000014107
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014108 void VisitMemberExpr(MemberExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000014109 S.MarkMemberReferenced(E);
Douglas Gregor32b3de52010-09-11 23:32:50 +000014110 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014111 }
14112
John McCall28fc7092011-11-10 05:35:25 +000014113 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000014114 S.MarkFunctionReferenced(E->getLocStart(),
John McCall28fc7092011-11-10 05:35:25 +000014115 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14116 Visit(E->getSubExpr());
14117 }
14118
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014119 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014120 if (E->getOperatorNew())
Eli Friedmanfa0df832012-02-02 03:46:19 +000014121 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014122 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000014123 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +000014124 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014125 }
Sebastian Redl6047f072012-02-16 12:22:20 +000014126
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014127 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14128 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000014129 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000014130 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14131 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14132 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedmanfa0df832012-02-02 03:46:19 +000014133 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000014134 S.LookupDestructor(Record));
14135 }
14136
Douglas Gregor32b3de52010-09-11 23:32:50 +000014137 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014138 }
14139
14140 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000014141 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +000014142 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014143 }
14144
Douglas Gregorf0873f42010-10-19 17:17:35 +000014145 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14146 Visit(E->getExpr());
14147 }
Eli Friedman3bda6b12012-02-02 23:15:15 +000014148
14149 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14150 Inherited::VisitImplicitCastExpr(E);
14151
14152 if (E->getCastKind() == CK_LValueToRValue)
14153 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14154 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014155 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000014156}
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014157
14158/// \brief Mark any declarations that appear within this expression or any
14159/// potentially-evaluated subexpressions as "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +000014160///
14161/// \param SkipLocalVariables If true, don't mark local variables as
14162/// 'referenced'.
14163void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
14164 bool SkipLocalVariables) {
14165 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014166}
14167
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000014168/// \brief Emit a diagnostic that describes an effect on the run-time behavior
14169/// of the program being compiled.
14170///
14171/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000014172/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000014173/// possibility that the code will actually be executable. Code in sizeof()
14174/// expressions, code used only during overload resolution, etc., are not
14175/// potentially evaluated. This routine will suppress such diagnostics or,
14176/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000014177/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000014178/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000014179///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000014180/// This routine should be used for all diagnostics that describe the run-time
14181/// behavior of a program, such as passing a non-POD value through an ellipsis.
14182/// Failure to do so will likely result in spurious diagnostics or failures
14183/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuba63ce62011-09-09 01:45:06 +000014184bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000014185 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +000014186 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000014187 case Unevaluated:
John McCallf413f5e2013-05-03 00:10:13 +000014188 case UnevaluatedAbstract:
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000014189 // The argument will never be evaluated, so don't complain.
14190 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000014191
Richard Smith764d2fe2011-12-20 02:08:33 +000014192 case ConstantEvaluated:
14193 // Relevant diagnostics should be produced by constant evaluation.
14194 break;
14195
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000014196 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014197 case PotentiallyEvaluatedIfUsed:
Richard Trieuba63ce62011-09-09 01:45:06 +000014198 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +000014199 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuba63ce62011-09-09 01:45:06 +000014200 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek3427fac2011-02-23 01:52:04 +000014201 }
14202 else
14203 Diag(Loc, PD);
14204
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000014205 return true;
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000014206 }
14207
14208 return false;
14209}
14210
Anders Carlsson7f84ed92009-10-09 23:51:55 +000014211bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14212 CallExpr *CE, FunctionDecl *FD) {
14213 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14214 return false;
14215
Richard Smithfd555f62012-02-22 02:04:18 +000014216 // If we're inside a decltype's expression, don't check for a valid return
14217 // type or construct temporaries until we know whether this is the last call.
14218 if (ExprEvalContexts.back().IsDecltype) {
14219 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14220 return false;
14221 }
14222
Douglas Gregora6c5abb2012-05-04 16:48:41 +000014223 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000014224 FunctionDecl *FD;
14225 CallExpr *CE;
14226
14227 public:
14228 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14229 : FD(FD), CE(CE) { }
Craig Toppere14c0f82014-03-12 04:55:44 +000014230
14231 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000014232 if (!FD) {
14233 S.Diag(Loc, diag::err_call_incomplete_return)
14234 << T << CE->getSourceRange();
14235 return;
14236 }
14237
14238 S.Diag(Loc, diag::err_call_function_incomplete_return)
14239 << CE->getSourceRange() << FD->getDeclName() << T;
Alp Toker2afa8782014-05-28 12:20:14 +000014240 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14241 << FD->getDeclName();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000014242 }
14243 } Diagnoser(FD, CE);
14244
14245 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson7f84ed92009-10-09 23:51:55 +000014246 return true;
14247
14248 return false;
14249}
14250
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000014251// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000014252// will prevent this condition from triggering, which is what we want.
14253void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14254 SourceLocation Loc;
14255
John McCall0506e4a2009-11-11 02:41:58 +000014256 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000014257 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000014258
Chandler Carruthf87d6c02011-08-16 22:30:10 +000014259 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000014260 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000014261 return;
14262
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000014263 IsOrAssign = Op->getOpcode() == BO_OrAssign;
14264
John McCallb0e419e2009-11-12 00:06:05 +000014265 // Greylist some idioms by putting them into a warning subcategory.
14266 if (ObjCMessageExpr *ME
14267 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14268 Selector Sel = ME->getSelector();
14269
John McCallb0e419e2009-11-12 00:06:05 +000014270 // self = [<foo> init...]
Jean-Daniel Dupas39655742013-07-17 18:17:14 +000014271 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
John McCallb0e419e2009-11-12 00:06:05 +000014272 diagnostic = diag::warn_condition_is_idiomatic_assignment;
14273
14274 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000014275 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000014276 diagnostic = diag::warn_condition_is_idiomatic_assignment;
14277 }
John McCall0506e4a2009-11-11 02:41:58 +000014278
John McCalld5707ab2009-10-12 21:59:07 +000014279 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +000014280 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000014281 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000014282 return;
14283
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000014284 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000014285 Loc = Op->getOperatorLoc();
Fariborz Jahanianf07bcc52012-08-29 17:17:11 +000014286 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14287 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14288 else {
John McCalld5707ab2009-10-12 21:59:07 +000014289 // Not an assignment.
14290 return;
14291 }
14292
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000014293 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000014294
Daniel Dunbar62ee6412012-03-09 18:35:03 +000014295 SourceLocation Open = E->getLocStart();
Craig Topper07fa1762015-11-15 02:31:46 +000014296 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000014297 Diag(Loc, diag::note_condition_assign_silence)
14298 << FixItHint::CreateInsertion(Open, "(")
14299 << FixItHint::CreateInsertion(Close, ")");
14300
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000014301 if (IsOrAssign)
14302 Diag(Loc, diag::note_condition_or_assign_to_comparison)
14303 << FixItHint::CreateReplacement(Loc, "!=");
14304 else
14305 Diag(Loc, diag::note_condition_assign_to_comparison)
14306 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +000014307}
14308
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000014309/// \brief Redundant parentheses over an equality comparison can indicate
14310/// that the user intended an assignment used as condition.
Richard Trieuba63ce62011-09-09 01:45:06 +000014311void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000014312 // Don't warn if the parens came from a macro.
Richard Trieuba63ce62011-09-09 01:45:06 +000014313 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000014314 if (parenLoc.isInvalid() || parenLoc.isMacroID())
14315 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000014316 // Don't warn for dependent expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +000014317 if (ParenE->isTypeDependent())
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000014318 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000014319
Richard Trieuba63ce62011-09-09 01:45:06 +000014320 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000014321
14322 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000014323 if (opE->getOpcode() == BO_EQ &&
14324 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14325 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000014326 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000014327
Ted Kremenekae022092011-02-02 02:20:30 +000014328 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +000014329 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +000014330 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar62ee6412012-03-09 18:35:03 +000014331 << FixItHint::CreateRemoval(ParenERange.getBegin())
14332 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000014333 Diag(Loc, diag::note_equality_comparison_to_assign)
14334 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000014335 }
14336}
14337
John Wiegley01296292011-04-08 18:41:53 +000014338ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +000014339 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000014340 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14341 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000014342
John McCall0009fcc2011-04-26 20:42:42 +000014343 ExprResult result = CheckPlaceholderExpr(E);
14344 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014345 E = result.get();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000014346
John McCall0009fcc2011-04-26 20:42:42 +000014347 if (!E->isTypeDependent()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000014348 if (getLangOpts().CPlusPlus)
John McCall34376a62010-12-04 03:47:34 +000014349 return CheckCXXBooleanCondition(E); // C++ 6.4p4
14350
John Wiegley01296292011-04-08 18:41:53 +000014351 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14352 if (ERes.isInvalid())
14353 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014354 E = ERes.get();
John McCall29cb2fd2010-12-04 06:09:13 +000014355
14356 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000014357 if (!T->isScalarType()) { // C99 6.8.4.1p1
14358 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14359 << T << E->getSourceRange();
14360 return ExprError();
14361 }
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000014362 CheckBoolLikeConversion(E, Loc);
John McCalld5707ab2009-10-12 21:59:07 +000014363 }
14364
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000014365 return E;
John McCalld5707ab2009-10-12 21:59:07 +000014366}
Douglas Gregore60e41a2010-05-06 17:25:47 +000014367
John McCalldadc5752010-08-24 06:29:42 +000014368ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +000014369 Expr *SubExpr) {
14370 if (!SubExpr)
Douglas Gregore60e41a2010-05-06 17:25:47 +000014371 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000014372
Richard Trieuba63ce62011-09-09 01:45:06 +000014373 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +000014374}
John McCall36e7fe32010-10-12 00:20:44 +000014375
John McCall31996342011-04-07 08:22:57 +000014376namespace {
John McCall2979fe02011-04-12 00:42:48 +000014377 /// A visitor for rebuilding a call to an __unknown_any expression
14378 /// to have an appropriate type.
14379 struct RebuildUnknownAnyFunction
14380 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14381
14382 Sema &S;
14383
14384 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14385
14386 ExprResult VisitStmt(Stmt *S) {
14387 llvm_unreachable("unexpected statement!");
John McCall2979fe02011-04-12 00:42:48 +000014388 }
14389
Richard Trieu10162ab2011-09-09 03:59:41 +000014390 ExprResult VisitExpr(Expr *E) {
14391 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14392 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000014393 return ExprError();
14394 }
14395
14396 /// Rebuild an expression which simply semantically wraps another
14397 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000014398 template <class T> ExprResult rebuildSugarExpr(T *E) {
14399 ExprResult SubResult = Visit(E->getSubExpr());
14400 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000014401
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014402 Expr *SubExpr = SubResult.get();
Richard Trieu10162ab2011-09-09 03:59:41 +000014403 E->setSubExpr(SubExpr);
14404 E->setType(SubExpr->getType());
14405 E->setValueKind(SubExpr->getValueKind());
14406 assert(E->getObjectKind() == OK_Ordinary);
14407 return E;
John McCall2979fe02011-04-12 00:42:48 +000014408 }
14409
Richard Trieu10162ab2011-09-09 03:59:41 +000014410 ExprResult VisitParenExpr(ParenExpr *E) {
14411 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000014412 }
14413
Richard Trieu10162ab2011-09-09 03:59:41 +000014414 ExprResult VisitUnaryExtension(UnaryOperator *E) {
14415 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000014416 }
14417
Richard Trieu10162ab2011-09-09 03:59:41 +000014418 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14419 ExprResult SubResult = Visit(E->getSubExpr());
14420 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000014421
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014422 Expr *SubExpr = SubResult.get();
Richard Trieu10162ab2011-09-09 03:59:41 +000014423 E->setSubExpr(SubExpr);
14424 E->setType(S.Context.getPointerType(SubExpr->getType()));
14425 assert(E->getValueKind() == VK_RValue);
14426 assert(E->getObjectKind() == OK_Ordinary);
14427 return E;
John McCall2979fe02011-04-12 00:42:48 +000014428 }
14429
Richard Trieu10162ab2011-09-09 03:59:41 +000014430 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14431 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000014432
Richard Trieu10162ab2011-09-09 03:59:41 +000014433 E->setType(VD->getType());
John McCall2979fe02011-04-12 00:42:48 +000014434
Richard Trieu10162ab2011-09-09 03:59:41 +000014435 assert(E->getValueKind() == VK_RValue);
David Blaikiebbafb8a2012-03-11 07:00:24 +000014436 if (S.getLangOpts().CPlusPlus &&
Richard Trieu10162ab2011-09-09 03:59:41 +000014437 !(isa<CXXMethodDecl>(VD) &&
14438 cast<CXXMethodDecl>(VD)->isInstance()))
14439 E->setValueKind(VK_LValue);
John McCall2979fe02011-04-12 00:42:48 +000014440
Richard Trieu10162ab2011-09-09 03:59:41 +000014441 return E;
John McCall2979fe02011-04-12 00:42:48 +000014442 }
14443
Richard Trieu10162ab2011-09-09 03:59:41 +000014444 ExprResult VisitMemberExpr(MemberExpr *E) {
14445 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000014446 }
14447
Richard Trieu10162ab2011-09-09 03:59:41 +000014448 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14449 return resolveDecl(E, E->getDecl());
John McCall2979fe02011-04-12 00:42:48 +000014450 }
14451 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000014452}
John McCall2979fe02011-04-12 00:42:48 +000014453
14454/// Given a function expression of unknown-any type, try to rebuild it
14455/// to have a function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000014456static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14457 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14458 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014459 return S.DefaultFunctionArrayConversion(Result.get());
John McCall2979fe02011-04-12 00:42:48 +000014460}
14461
14462namespace {
John McCall2d2e8702011-04-11 07:02:50 +000014463 /// A visitor for rebuilding an expression of type __unknown_anytype
14464 /// into one which resolves the type directly on the referring
14465 /// expression. Strict preservation of the original source
14466 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +000014467 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +000014468 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +000014469
14470 Sema &S;
14471
14472 /// The current destination type.
14473 QualType DestType;
14474
Richard Trieu10162ab2011-09-09 03:59:41 +000014475 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14476 : S(S), DestType(CastType) {}
John McCall31996342011-04-07 08:22:57 +000014477
John McCall39439732011-04-09 22:50:59 +000014478 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +000014479 llvm_unreachable("unexpected statement!");
John McCall31996342011-04-07 08:22:57 +000014480 }
14481
Richard Trieu10162ab2011-09-09 03:59:41 +000014482 ExprResult VisitExpr(Expr *E) {
14483 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14484 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000014485 return ExprError();
John McCall31996342011-04-07 08:22:57 +000014486 }
14487
Richard Trieu10162ab2011-09-09 03:59:41 +000014488 ExprResult VisitCallExpr(CallExpr *E);
14489 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall2d2e8702011-04-11 07:02:50 +000014490
John McCall39439732011-04-09 22:50:59 +000014491 /// Rebuild an expression which simply semantically wraps another
14492 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000014493 template <class T> ExprResult rebuildSugarExpr(T *E) {
14494 ExprResult SubResult = Visit(E->getSubExpr());
14495 if (SubResult.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014496 Expr *SubExpr = SubResult.get();
Richard Trieu10162ab2011-09-09 03:59:41 +000014497 E->setSubExpr(SubExpr);
14498 E->setType(SubExpr->getType());
14499 E->setValueKind(SubExpr->getValueKind());
14500 assert(E->getObjectKind() == OK_Ordinary);
14501 return E;
John McCall39439732011-04-09 22:50:59 +000014502 }
John McCall31996342011-04-07 08:22:57 +000014503
Richard Trieu10162ab2011-09-09 03:59:41 +000014504 ExprResult VisitParenExpr(ParenExpr *E) {
14505 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000014506 }
14507
Richard Trieu10162ab2011-09-09 03:59:41 +000014508 ExprResult VisitUnaryExtension(UnaryOperator *E) {
14509 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000014510 }
14511
Richard Trieu10162ab2011-09-09 03:59:41 +000014512 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14513 const PointerType *Ptr = DestType->getAs<PointerType>();
14514 if (!Ptr) {
14515 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14516 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000014517 return ExprError();
14518 }
Richard Trieu10162ab2011-09-09 03:59:41 +000014519 assert(E->getValueKind() == VK_RValue);
14520 assert(E->getObjectKind() == OK_Ordinary);
14521 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +000014522
14523 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu10162ab2011-09-09 03:59:41 +000014524 DestType = Ptr->getPointeeType();
14525 ExprResult SubResult = Visit(E->getSubExpr());
14526 if (SubResult.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014527 E->setSubExpr(SubResult.get());
Richard Trieu10162ab2011-09-09 03:59:41 +000014528 return E;
John McCall2979fe02011-04-12 00:42:48 +000014529 }
14530
Richard Trieu10162ab2011-09-09 03:59:41 +000014531 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCall39439732011-04-09 22:50:59 +000014532
Richard Trieu10162ab2011-09-09 03:59:41 +000014533 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCall39439732011-04-09 22:50:59 +000014534
Richard Trieu10162ab2011-09-09 03:59:41 +000014535 ExprResult VisitMemberExpr(MemberExpr *E) {
14536 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000014537 }
John McCall39439732011-04-09 22:50:59 +000014538
Richard Trieu10162ab2011-09-09 03:59:41 +000014539 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14540 return resolveDecl(E, E->getDecl());
John McCall31996342011-04-07 08:22:57 +000014541 }
14542 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000014543}
John McCall31996342011-04-07 08:22:57 +000014544
John McCall2d2e8702011-04-11 07:02:50 +000014545/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu10162ab2011-09-09 03:59:41 +000014546ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
14547 Expr *CalleeExpr = E->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000014548
14549 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +000014550 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +000014551 FK_FunctionPointer,
14552 FK_BlockPointer
14553 };
14554
Richard Trieu10162ab2011-09-09 03:59:41 +000014555 FnKind Kind;
14556 QualType CalleeType = CalleeExpr->getType();
14557 if (CalleeType == S.Context.BoundMemberTy) {
14558 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
14559 Kind = FK_MemberFunction;
14560 CalleeType = Expr::findBoundMemberType(CalleeExpr);
14561 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
14562 CalleeType = Ptr->getPointeeType();
14563 Kind = FK_FunctionPointer;
John McCall2d2e8702011-04-11 07:02:50 +000014564 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000014565 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
14566 Kind = FK_BlockPointer;
John McCall2d2e8702011-04-11 07:02:50 +000014567 }
Richard Trieu10162ab2011-09-09 03:59:41 +000014568 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall2d2e8702011-04-11 07:02:50 +000014569
14570 // Verify that this is a legal result type of a function.
14571 if (DestType->isArrayType() || DestType->isFunctionType()) {
14572 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu10162ab2011-09-09 03:59:41 +000014573 if (Kind == FK_BlockPointer)
John McCall2d2e8702011-04-11 07:02:50 +000014574 diagID = diag::err_block_returning_array_function;
14575
Richard Trieu10162ab2011-09-09 03:59:41 +000014576 S.Diag(E->getExprLoc(), diagID)
John McCall2d2e8702011-04-11 07:02:50 +000014577 << DestType->isFunctionType() << DestType;
14578 return ExprError();
14579 }
14580
14581 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu10162ab2011-09-09 03:59:41 +000014582 E->setType(DestType.getNonLValueExprType(S.Context));
14583 E->setValueKind(Expr::getValueKindForType(DestType));
14584 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000014585
14586 // Rebuild the function type, replacing the result type with DestType.
John McCall611d9b62013-06-27 22:43:24 +000014587 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
14588 if (Proto) {
14589 // __unknown_anytype(...) is a special case used by the debugger when
14590 // it has no idea what a function's signature is.
14591 //
14592 // We want to build this call essentially under the K&R
14593 // unprototyped rules, but making a FunctionNoProtoType in C++
14594 // would foul up all sorts of assumptions. However, we cannot
14595 // simply pass all arguments as variadic arguments, nor can we
14596 // portably just call the function under a non-variadic type; see
14597 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
14598 // However, it turns out that in practice it is generally safe to
14599 // call a function declared as "A foo(B,C,D);" under the prototype
14600 // "A foo(B,C,D,...);". The only known exception is with the
14601 // Windows ABI, where any variadic function is implicitly cdecl
14602 // regardless of its normal CC. Therefore we change the parameter
14603 // types to match the types of the arguments.
14604 //
14605 // This is a hack, but it is far superior to moving the
14606 // corresponding target-specific code from IR-gen to Sema/AST.
14607
Alp Toker9cacbab2014-01-20 20:26:09 +000014608 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
John McCall611d9b62013-06-27 22:43:24 +000014609 SmallVector<QualType, 8> ArgTypes;
14610 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
14611 ArgTypes.reserve(E->getNumArgs());
14612 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
14613 Expr *Arg = E->getArg(i);
14614 QualType ArgType = Arg->getType();
14615 if (E->isLValue()) {
14616 ArgType = S.Context.getLValueReferenceType(ArgType);
14617 } else if (E->isXValue()) {
14618 ArgType = S.Context.getRValueReferenceType(ArgType);
14619 }
14620 ArgTypes.push_back(ArgType);
14621 }
14622 ParamTypes = ArgTypes;
14623 }
14624 DestType = S.Context.getFunctionType(DestType, ParamTypes,
Reid Kleckner896b32f2013-06-10 20:51:09 +000014625 Proto->getExtProtoInfo());
John McCall611d9b62013-06-27 22:43:24 +000014626 } else {
John McCall2d2e8702011-04-11 07:02:50 +000014627 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000014628 FnType->getExtInfo());
John McCall611d9b62013-06-27 22:43:24 +000014629 }
John McCall2d2e8702011-04-11 07:02:50 +000014630
14631 // Rebuild the appropriate pointer-to-function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000014632 switch (Kind) {
John McCall4adb38c2011-04-27 00:36:17 +000014633 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +000014634 // Nothing to do.
14635 break;
14636
14637 case FK_FunctionPointer:
14638 DestType = S.Context.getPointerType(DestType);
14639 break;
14640
14641 case FK_BlockPointer:
14642 DestType = S.Context.getBlockPointerType(DestType);
14643 break;
14644 }
14645
14646 // Finally, we can recurse.
Richard Trieu10162ab2011-09-09 03:59:41 +000014647 ExprResult CalleeResult = Visit(CalleeExpr);
14648 if (!CalleeResult.isUsable()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014649 E->setCallee(CalleeResult.get());
John McCall2d2e8702011-04-11 07:02:50 +000014650
14651 // Bind a temporary if necessary.
Richard Trieu10162ab2011-09-09 03:59:41 +000014652 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000014653}
14654
Richard Trieu10162ab2011-09-09 03:59:41 +000014655ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000014656 // Verify that this is a legal result type of a call.
14657 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu10162ab2011-09-09 03:59:41 +000014658 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall2979fe02011-04-12 00:42:48 +000014659 << DestType->isFunctionType() << DestType;
14660 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000014661 }
14662
John McCall3f4138c2011-07-13 17:56:40 +000014663 // Rewrite the method result type if available.
Richard Trieu10162ab2011-09-09 03:59:41 +000014664 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +000014665 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
14666 Method->setReturnType(DestType);
John McCall3f4138c2011-07-13 17:56:40 +000014667 }
John McCall2979fe02011-04-12 00:42:48 +000014668
John McCall2d2e8702011-04-11 07:02:50 +000014669 // Change the type of the message.
Richard Trieu10162ab2011-09-09 03:59:41 +000014670 E->setType(DestType.getNonReferenceType());
14671 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000014672
Richard Trieu10162ab2011-09-09 03:59:41 +000014673 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000014674}
14675
Richard Trieu10162ab2011-09-09 03:59:41 +000014676ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000014677 // The only case we should ever see here is a function-to-pointer decay.
Sean Callanan2db103c2012-03-06 23:12:57 +000014678 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanan12495112012-03-06 21:34:12 +000014679 assert(E->getValueKind() == VK_RValue);
14680 assert(E->getObjectKind() == OK_Ordinary);
14681
14682 E->setType(DestType);
14683
14684 // Rebuild the sub-expression as the pointee (function) type.
14685 DestType = DestType->castAs<PointerType>()->getPointeeType();
14686
14687 ExprResult Result = Visit(E->getSubExpr());
14688 if (!Result.isUsable()) return ExprError();
14689
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014690 E->setSubExpr(Result.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000014691 return E;
Sean Callanan2db103c2012-03-06 23:12:57 +000014692 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanan12495112012-03-06 21:34:12 +000014693 assert(E->getValueKind() == VK_RValue);
14694 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000014695
Sean Callanan12495112012-03-06 21:34:12 +000014696 assert(isa<BlockPointerType>(E->getType()));
John McCall2979fe02011-04-12 00:42:48 +000014697
Sean Callanan12495112012-03-06 21:34:12 +000014698 E->setType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000014699
Sean Callanan12495112012-03-06 21:34:12 +000014700 // The sub-expression has to be a lvalue reference, so rebuild it as such.
14701 DestType = S.Context.getLValueReferenceType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000014702
Sean Callanan12495112012-03-06 21:34:12 +000014703 ExprResult Result = Visit(E->getSubExpr());
14704 if (!Result.isUsable()) return ExprError();
14705
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014706 E->setSubExpr(Result.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000014707 return E;
Sean Callanan2db103c2012-03-06 23:12:57 +000014708 } else {
Sean Callanan12495112012-03-06 21:34:12 +000014709 llvm_unreachable("Unhandled cast type!");
14710 }
John McCall2d2e8702011-04-11 07:02:50 +000014711}
14712
Richard Trieu10162ab2011-09-09 03:59:41 +000014713ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
14714 ExprValueKind ValueKind = VK_LValue;
14715 QualType Type = DestType;
John McCall2d2e8702011-04-11 07:02:50 +000014716
14717 // We know how to make this work for certain kinds of decls:
14718
14719 // - functions
Richard Trieu10162ab2011-09-09 03:59:41 +000014720 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
14721 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
14722 DestType = Ptr->getPointeeType();
14723 ExprResult Result = resolveDecl(E, VD);
14724 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014725 return S.ImpCastExprToType(Result.get(), Type,
John McCall9a877fe2011-08-10 04:12:23 +000014726 CK_FunctionToPointerDecay, VK_RValue);
14727 }
14728
Richard Trieu10162ab2011-09-09 03:59:41 +000014729 if (!Type->isFunctionType()) {
14730 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
14731 << VD << E->getSourceRange();
John McCall9a877fe2011-08-10 04:12:23 +000014732 return ExprError();
14733 }
Fariborz Jahaniana29986c2014-11-11 16:56:21 +000014734 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
14735 // We must match the FunctionDecl's type to the hack introduced in
14736 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
14737 // type. See the lengthy commentary in that routine.
14738 QualType FDT = FD->getType();
14739 const FunctionType *FnType = FDT->castAs<FunctionType>();
14740 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
14741 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14742 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
14743 SourceLocation Loc = FD->getLocation();
14744 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
14745 FD->getDeclContext(),
14746 Loc, Loc, FD->getNameInfo().getName(),
14747 DestType, FD->getTypeSourceInfo(),
14748 SC_None, false/*isInlineSpecified*/,
14749 FD->hasPrototype(),
14750 false/*isConstexprSpecified*/);
14751
14752 if (FD->getQualifier())
14753 NewFD->setQualifierInfo(FD->getQualifierLoc());
14754
14755 SmallVector<ParmVarDecl*, 16> Params;
14756 for (const auto &AI : FT->param_types()) {
14757 ParmVarDecl *Param =
14758 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
14759 Param->setScopeInfo(0, Params.size());
14760 Params.push_back(Param);
14761 }
14762 NewFD->setParams(Params);
14763 DRE->setDecl(NewFD);
14764 VD = DRE->getDecl();
14765 }
14766 }
John McCall2d2e8702011-04-11 07:02:50 +000014767
Richard Trieu10162ab2011-09-09 03:59:41 +000014768 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
14769 if (MD->isInstance()) {
14770 ValueKind = VK_RValue;
14771 Type = S.Context.BoundMemberTy;
John McCall4adb38c2011-04-27 00:36:17 +000014772 }
14773
John McCall2d2e8702011-04-11 07:02:50 +000014774 // Function references aren't l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000014775 if (!S.getLangOpts().CPlusPlus)
Richard Trieu10162ab2011-09-09 03:59:41 +000014776 ValueKind = VK_RValue;
John McCall2d2e8702011-04-11 07:02:50 +000014777
14778 // - variables
Richard Trieu10162ab2011-09-09 03:59:41 +000014779 } else if (isa<VarDecl>(VD)) {
14780 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
14781 Type = RefTy->getPointeeType();
14782 } else if (Type->isFunctionType()) {
14783 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
14784 << VD << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000014785 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000014786 }
14787
14788 // - nothing else
14789 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000014790 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
14791 << VD << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000014792 return ExprError();
14793 }
14794
John McCall611d9b62013-06-27 22:43:24 +000014795 // Modifying the declaration like this is friendly to IR-gen but
14796 // also really dangerous.
Richard Trieu10162ab2011-09-09 03:59:41 +000014797 VD->setType(DestType);
14798 E->setType(Type);
14799 E->setValueKind(ValueKind);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000014800 return E;
John McCall2d2e8702011-04-11 07:02:50 +000014801}
14802
John McCall31996342011-04-07 08:22:57 +000014803/// Check a cast of an unknown-any type. We intentionally only
14804/// trigger this for C-style casts.
Richard Trieuba63ce62011-09-09 01:45:06 +000014805ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
14806 Expr *CastExpr, CastKind &CastKind,
14807 ExprValueKind &VK, CXXCastPath &Path) {
Douglas Gregor0fc3a002016-02-03 19:13:08 +000014808 // The type we're casting to must be either void or complete.
14809 if (!CastType->isVoidType() &&
14810 RequireCompleteType(TypeRange.getBegin(), CastType,
14811 diag::err_typecheck_cast_to_incomplete))
14812 return ExprError();
14813
John McCall31996342011-04-07 08:22:57 +000014814 // Rewrite the casted expression from scratch.
Richard Trieuba63ce62011-09-09 01:45:06 +000014815 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCall39439732011-04-09 22:50:59 +000014816 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000014817
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014818 CastExpr = result.get();
Richard Trieuba63ce62011-09-09 01:45:06 +000014819 VK = CastExpr->getValueKind();
14820 CastKind = CK_NoOp;
John McCall39439732011-04-09 22:50:59 +000014821
Richard Trieuba63ce62011-09-09 01:45:06 +000014822 return CastExpr;
John McCall31996342011-04-07 08:22:57 +000014823}
14824
Douglas Gregord8fb1e32011-12-01 01:37:36 +000014825ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
14826 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
14827}
14828
John McCallcc5788c2013-03-04 07:34:02 +000014829ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
14830 Expr *arg, QualType &paramType) {
14831 // If the syntactic form of the argument is not an explicit cast of
14832 // any sort, just do default argument promotion.
14833 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
14834 if (!castArg) {
14835 ExprResult result = DefaultArgumentPromotion(arg);
14836 if (result.isInvalid()) return ExprError();
14837 paramType = result.get()->getType();
14838 return result;
John McCallea0a39e2012-11-14 00:49:39 +000014839 }
14840
John McCallcc5788c2013-03-04 07:34:02 +000014841 // Otherwise, use the type that was written in the explicit cast.
14842 assert(!arg->hasPlaceholderType());
14843 paramType = castArg->getTypeAsWritten();
14844
14845 // Copy-initialize a parameter of that type.
14846 InitializedEntity entity =
14847 InitializedEntity::InitializeParameter(Context, paramType,
14848 /*consumed*/ false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000014849 return PerformCopyInitialization(entity, callLoc, arg);
John McCallea0a39e2012-11-14 00:49:39 +000014850}
14851
Richard Trieuba63ce62011-09-09 01:45:06 +000014852static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
14853 Expr *orig = E;
John McCall2d2e8702011-04-11 07:02:50 +000014854 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000014855 while (true) {
Richard Trieuba63ce62011-09-09 01:45:06 +000014856 E = E->IgnoreParenImpCasts();
14857 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
14858 E = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000014859 diagID = diag::err_uncasted_call_of_unknown_any;
14860 } else {
John McCall31996342011-04-07 08:22:57 +000014861 break;
John McCall2d2e8702011-04-11 07:02:50 +000014862 }
John McCall31996342011-04-07 08:22:57 +000014863 }
14864
John McCall2d2e8702011-04-11 07:02:50 +000014865 SourceLocation loc;
14866 NamedDecl *d;
Richard Trieuba63ce62011-09-09 01:45:06 +000014867 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000014868 loc = ref->getLocation();
14869 d = ref->getDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000014870 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000014871 loc = mem->getMemberLoc();
14872 d = mem->getMemberDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000014873 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000014874 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidisa6011e22011-10-03 06:36:51 +000014875 loc = msg->getSelectorStartLoc();
John McCall2d2e8702011-04-11 07:02:50 +000014876 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000014877 if (!d) {
14878 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
14879 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
14880 << orig->getSourceRange();
14881 return ExprError();
14882 }
John McCall2d2e8702011-04-11 07:02:50 +000014883 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +000014884 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14885 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000014886 return ExprError();
14887 }
14888
14889 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000014890
14891 // Never recoverable.
14892 return ExprError();
14893}
14894
John McCall36e7fe32010-10-12 00:20:44 +000014895/// Check for operands with placeholder types and complain if found.
14896/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000014897ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
Kaelyn Takata15867822014-11-21 18:48:04 +000014898 if (!getLangOpts().CPlusPlus) {
14899 // C cannot handle TypoExpr nodes on either side of a binop because it
14900 // doesn't handle dependent types properly, so make sure any TypoExprs have
14901 // been dealt with before checking the operands.
14902 ExprResult Result = CorrectDelayedTyposInExpr(E);
14903 if (!Result.isUsable()) return ExprError();
14904 E = Result.get();
14905 }
14906
John McCall4124c492011-10-17 18:40:02 +000014907 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000014908 if (!placeholderType) return E;
John McCall4124c492011-10-17 18:40:02 +000014909
14910 switch (placeholderType->getKind()) {
John McCall36e7fe32010-10-12 00:20:44 +000014911
John McCall31996342011-04-07 08:22:57 +000014912 // Overloaded expressions.
John McCall4124c492011-10-17 18:40:02 +000014913 case BuiltinType::Overload: {
John McCall50a2c2c2011-10-11 23:14:30 +000014914 // Try to resolve a single function template specialization.
14915 // This is obligatory.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000014916 ExprResult result = E;
John McCall50a2c2c2011-10-11 23:14:30 +000014917 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
14918 return result;
14919
14920 // If that failed, try to recover with a call.
14921 } else {
14922 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
14923 /*complain*/ true);
14924 return result;
14925 }
14926 }
John McCall31996342011-04-07 08:22:57 +000014927
John McCall0009fcc2011-04-26 20:42:42 +000014928 // Bound member functions.
John McCall4124c492011-10-17 18:40:02 +000014929 case BuiltinType::BoundMember: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000014930 ExprResult result = E;
David Majnemerced8bdf2015-02-25 17:36:15 +000014931 const Expr *BME = E->IgnoreParens();
14932 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
14933 // Try to give a nicer diagnostic if it is a bound member that we recognize.
14934 if (isa<CXXPseudoDestructorExpr>(BME)) {
14935 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
14936 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
14937 if (ME->getMemberNameInfo().getName().getNameKind() ==
14938 DeclarationName::CXXDestructorName)
14939 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
14940 }
14941 tryToRecoverWithCall(result, PD,
John McCall50a2c2c2011-10-11 23:14:30 +000014942 /*complain*/ true);
14943 return result;
John McCall4124c492011-10-17 18:40:02 +000014944 }
14945
14946 // ARC unbridged casts.
14947 case BuiltinType::ARCUnbridgedCast: {
14948 Expr *realCast = stripARCUnbridgedCast(E);
14949 diagnoseARCUnbridgedCast(realCast);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000014950 return realCast;
John McCall4124c492011-10-17 18:40:02 +000014951 }
John McCall0009fcc2011-04-26 20:42:42 +000014952
John McCall31996342011-04-07 08:22:57 +000014953 // Expressions of unknown type.
John McCall4124c492011-10-17 18:40:02 +000014954 case BuiltinType::UnknownAny:
John McCall31996342011-04-07 08:22:57 +000014955 return diagnoseUnknownAnyExpr(*this, E);
14956
John McCall526ab472011-10-25 17:37:35 +000014957 // Pseudo-objects.
14958 case BuiltinType::PseudoObject:
14959 return checkPseudoObjectRValue(E);
14960
Reid Klecknerf392ec62014-07-11 23:54:29 +000014961 case BuiltinType::BuiltinFn: {
14962 // Accept __noop without parens by implicitly converting it to a call expr.
14963 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
14964 if (DRE) {
14965 auto *FD = cast<FunctionDecl>(DRE->getDecl());
14966 if (FD->getBuiltinID() == Builtin::BI__noop) {
14967 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
14968 CK_BuiltinFnToFnPtr).get();
14969 return new (Context) CallExpr(Context, E, None, Context.IntTy,
14970 VK_RValue, SourceLocation());
14971 }
14972 }
14973
Eli Friedman34866c72012-08-31 00:14:07 +000014974 Diag(E->getLocStart(), diag::err_builtin_fn_use);
14975 return ExprError();
Reid Klecknerf392ec62014-07-11 23:54:29 +000014976 }
Eli Friedman34866c72012-08-31 00:14:07 +000014977
Alexey Bataev1a3320e2015-08-25 14:24:04 +000014978 // Expressions of unknown type.
14979 case BuiltinType::OMPArraySection:
14980 Diag(E->getLocStart(), diag::err_omp_array_section_use);
14981 return ExprError();
14982
John McCalle314e272011-10-18 21:02:43 +000014983 // Everything else should be impossible.
Alexey Bader954ba212016-04-08 13:40:33 +000014984#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
John McCalle314e272011-10-18 21:02:43 +000014985 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +000014986#include "clang/Basic/OpenCLImageTypes.def"
Alexey Bader954ba212016-04-08 13:40:33 +000014987#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
John McCalle314e272011-10-18 21:02:43 +000014988#define PLACEHOLDER_TYPE(Id, SingletonId)
14989#include "clang/AST/BuiltinTypes.def"
John McCall4124c492011-10-17 18:40:02 +000014990 break;
14991 }
14992
14993 llvm_unreachable("invalid placeholder type!");
John McCall36e7fe32010-10-12 00:20:44 +000014994}
Richard Trieu2c850c02011-04-21 21:44:26 +000014995
Richard Trieuba63ce62011-09-09 01:45:06 +000014996bool Sema::CheckCaseExpression(Expr *E) {
14997 if (E->isTypeDependent())
Richard Trieu2c850c02011-04-21 21:44:26 +000014998 return true;
Richard Trieuba63ce62011-09-09 01:45:06 +000014999 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15000 return E->getType()->isIntegralOrEnumerationType();
Richard Trieu2c850c02011-04-21 21:44:26 +000015001 return false;
15002}
Ted Kremeneke65b0862012-03-06 20:05:56 +000015003
15004/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15005ExprResult
15006Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15007 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15008 "Unknown Objective-C Boolean value!");
Fariborz Jahanianf2578572012-08-30 18:49:41 +000015009 QualType BoolT = Context.ObjCBuiltinBoolTy;
15010 if (!Context.getBOOLDecl()) {
Fariborz Jahanianeab17302012-10-16 17:08:11 +000015011 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
Fariborz Jahanianf2578572012-08-30 18:49:41 +000015012 Sema::LookupOrdinaryName);
Fariborz Jahanian379e5362012-10-16 16:21:20 +000015013 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
Fariborz Jahanianf2578572012-08-30 18:49:41 +000015014 NamedDecl *ND = Result.getFoundDecl();
15015 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
15016 Context.setBOOLDecl(TD);
15017 }
15018 }
15019 if (Context.getBOOLDecl())
15020 BoolT = Context.getBOOLType();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000015021 return new (Context)
15022 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
Ted Kremeneke65b0862012-03-06 20:05:56 +000015023}