blob: 1509b22a9e5a67945b157035482d2cadb5f9d3fc [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
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "TreeTransform.h"
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000015#include "clang/AST/ASTConsumer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/ASTContext.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000017#include "clang/AST/ASTLambda.h"
Sebastian Redl2ac2c722011-04-29 08:19:30 +000018#include "clang/AST/ASTMutationListener.h"
Douglas Gregord1702062010-04-29 00:18:15 +000019#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000023#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000024#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000025#include "clang/AST/ExprObjC.h"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000026#include "clang/AST/ExprOpenMP.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000027#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000028#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000029#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000030#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000031#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000032#include "clang/Lex/LiteralSupport.h"
33#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000034#include "clang/Sema/AnalysisBasedWarnings.h"
John McCall8b0666c2010-08-20 18:27:03 +000035#include "clang/Sema/DeclSpec.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000036#include "clang/Sema/DelayedDiagnostic.h"
John McCall8b0666c2010-08-20 18:27:03 +000037#include "clang/Sema/Designator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "clang/Sema/Initialization.h"
39#include "clang/Sema/Lookup.h"
40#include "clang/Sema/ParsedTemplate.h"
John McCall8b0666c2010-08-20 18:27:03 +000041#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000042#include "clang/Sema/ScopeInfo.h"
Anna Zaks3b402712011-07-28 19:51:27 +000043#include "clang/Sema/SemaFixItUtils.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000044#include "clang/Sema/SemaInternal.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
Erik Pilkingtonf35114c2016-10-25 19:05:50 +0000106AvailabilityResult
107Sema::ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D, std::string *Message) {
108 AvailabilityResult Result = D->getAvailability(Message);
Ted Kremenekc004b4d2015-05-14 22:07:25 +0000109
110 // For typedefs, if the typedef declaration appears available look
111 // to the underlying type to see if it is more restrictive.
David Blaikief0f00dc2015-05-14 22:47:19 +0000112 while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Ted Kremenekc004b4d2015-05-14 22:07:25 +0000113 if (Result == AR_Available) {
114 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
115 D = TT->getDecl();
Erik Pilkingtonf35114c2016-10-25 19:05:50 +0000116 Result = D->getAvailability(Message);
Ted Kremenekc004b4d2015-05-14 22:07:25 +0000117 continue;
118 }
119 }
120 break;
121 }
Erik Pilkington796a3e22016-08-05 22:59:03 +0000122
Fariborz Jahanian285b6b62014-06-18 17:58:27 +0000123 // Forward class declarations get their attributes from their definition.
124 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
Ted Kremenekc004b4d2015-05-14 22:07:25 +0000125 if (IDecl->getDefinition()) {
Fariborz Jahanian285b6b62014-06-18 17:58:27 +0000126 D = IDecl->getDefinition();
Erik Pilkingtonf35114c2016-10-25 19:05:50 +0000127 Result = D->getAvailability(Message);
Ted Kremenekc004b4d2015-05-14 22:07:25 +0000128 }
Fariborz Jahanian285b6b62014-06-18 17:58:27 +0000129 }
Ted Kremenekc004b4d2015-05-14 22:07:25 +0000130
Fariborz Jahanian25d09c22011-11-28 19:45:58 +0000131 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
132 if (Result == AR_Available) {
133 const DeclContext *DC = ECD->getDeclContext();
134 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
Erik Pilkingtonf35114c2016-10-25 19:05:50 +0000135 Result = TheEnumDecl->getAvailability(Message);
Fariborz Jahanian25d09c22011-11-28 19:45:58 +0000136 }
Jordan Rose2bd991a2012-10-10 16:42:54 +0000137
Erik Pilkingtonf35114c2016-10-25 19:05:50 +0000138 if (Result == AR_NotYetIntroduced) {
Erik Pilkington796a3e22016-08-05 22:59:03 +0000139 // Don't do this for enums, they can't be redeclared.
140 if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
141 return AR_Available;
142
143 bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
144 // Objective-C method declarations in categories are not modelled as
145 // redeclarations, so manually look for a redeclaration in a category
146 // if necessary.
147 if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
148 Warn = false;
149 // In general, D will point to the most recent redeclaration. However,
150 // for `@class A;` decls, this isn't true -- manually go through the
151 // redecl chain in that case.
152 if (Warn && isa<ObjCInterfaceDecl>(D))
153 for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
154 Redecl = Redecl->getPreviousDecl())
155 if (!Redecl->hasAttr<AvailabilityAttr>() ||
156 Redecl->getAttr<AvailabilityAttr>()->isInherited())
157 Warn = false;
158
159 return Warn ? AR_NotYetIntroduced : AR_Available;
160 }
Erik Pilkingtonf35114c2016-10-25 19:05:50 +0000161
162 return Result;
Erik Pilkington796a3e22016-08-05 22:59:03 +0000163}
164
165static void
166DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
167 const ObjCInterfaceDecl *UnknownObjCClass,
168 bool ObjCPropertyAccess) {
Erik Pilkington796a3e22016-08-05 22:59:03 +0000169 std::string Message;
Erik Pilkingtonf35114c2016-10-25 19:05:50 +0000170 // See if this declaration is unavailable, deprecated, or partial.
Erik Pilkington796a3e22016-08-05 22:59:03 +0000171 if (AvailabilityResult Result =
Erik Pilkingtonf35114c2016-10-25 19:05:50 +0000172 S.ShouldDiagnoseAvailabilityOfDecl(D, &Message)) {
Erik Pilkington796a3e22016-08-05 22:59:03 +0000173
Erik Pilkington5cd57172016-08-16 17:44:11 +0000174 if (Result == AR_NotYetIntroduced && S.getCurFunctionOrMethodDecl()) {
175 S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
176 return;
177 }
178
Erik Pilkington796a3e22016-08-05 22:59:03 +0000179 const ObjCPropertyDecl *ObjCPDecl = nullptr;
Jordan Rose2bd991a2012-10-10 16:42:54 +0000180 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
181 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
Erik Pilkingtonf35114c2016-10-25 19:05:50 +0000182 AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
Jordan Rose2bd991a2012-10-10 16:42:54 +0000183 if (PDeclResult == Result)
184 ObjCPDecl = PD;
185 }
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000186 }
Erik Pilkington796a3e22016-08-05 22:59:03 +0000187
188 S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass,
189 ObjCPDecl, ObjCPropertyAccess);
Jordan Rose2bd991a2012-10-10 16:42:54 +0000190 }
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000191}
192
Eli Friedmanebea0f22013-07-18 23:29:14 +0000193/// \brief Emit a note explaining that this function is deleted.
Richard Smith852265f2012-03-30 20:53:28 +0000194void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
Eli Friedmanebea0f22013-07-18 23:29:14 +0000195 assert(Decl->isDeleted());
196
Richard Smith852265f2012-03-30 20:53:28 +0000197 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
198
Eli Friedmanebea0f22013-07-18 23:29:14 +0000199 if (Method && Method->isDeleted() && Method->isDefaulted()) {
Richard Smith6f1e2c62012-04-02 20:59:25 +0000200 // If the method was explicitly defaulted, point at that declaration.
201 if (!Method->isImplicit())
202 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
203
204 // Try to diagnose why this special member function was implicitly
205 // deleted. This might fail, if that reason no longer applies.
Richard Smith852265f2012-03-30 20:53:28 +0000206 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +0000207 if (CSM != CXXInvalid)
Richard Smith80a47022016-06-29 01:10:27 +0000208 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
Richard Smith6f1e2c62012-04-02 20:59:25 +0000209
210 return;
Richard Smith852265f2012-03-30 20:53:28 +0000211 }
212
Richard Smith80a47022016-06-29 01:10:27 +0000213 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
214 if (Ctor && Ctor->isInheritingConstructor())
215 return NoteDeletedInheritingConstructor(Ctor);
216
Ted Kremenekb79ee572013-12-18 23:30:06 +0000217 Diag(Decl->getLocation(), diag::note_availability_specified_here)
218 << Decl << true;
Richard Smith852265f2012-03-30 20:53:28 +0000219}
220
Jordan Rose28cd12f2012-06-18 22:09:19 +0000221/// \brief Determine whether a FunctionDecl was ever declared with an
222/// explicit storage class.
223static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
Aaron Ballman86c93902014-03-06 23:45:36 +0000224 for (auto I : D->redecls()) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000225 if (I->getStorageClass() != SC_None)
Jordan Rose28cd12f2012-06-18 22:09:19 +0000226 return true;
227 }
228 return false;
229}
230
231/// \brief Check whether we're in an extern inline function and referring to a
Jordan Rosede9e9762012-06-20 18:50:06 +0000232/// variable or function with internal linkage (C11 6.7.4p3).
Jordan Rose28cd12f2012-06-18 22:09:19 +0000233///
Jordan Rose28cd12f2012-06-18 22:09:19 +0000234/// This is only a warning because we used to silently accept this code, but
Jordan Rosede9e9762012-06-20 18:50:06 +0000235/// in many cases it will not behave correctly. This is not enabled in C++ mode
236/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
237/// and so while there may still be user mistakes, most of the time we can't
238/// prove that there are errors.
Jordan Rose28cd12f2012-06-18 22:09:19 +0000239static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
240 const NamedDecl *D,
241 SourceLocation Loc) {
Jordan Rosede9e9762012-06-20 18:50:06 +0000242 // This is disabled under C++; there are too many ways for this to fire in
243 // contexts where the warning is a false positive, or where it is technically
244 // correct but benign.
245 if (S.getLangOpts().CPlusPlus)
246 return;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000247
248 // Check if this is an inlined function or method.
249 FunctionDecl *Current = S.getCurFunctionDecl();
250 if (!Current)
251 return;
252 if (!Current->isInlined())
253 return;
Rafael Espindola3ae00052013-05-13 00:12:11 +0000254 if (!Current->isExternallyVisible())
Jordan Rose28cd12f2012-06-18 22:09:19 +0000255 return;
Rafael Espindola3ae00052013-05-13 00:12:11 +0000256
Jordan Rose28cd12f2012-06-18 22:09:19 +0000257 // Check if the decl has internal linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +0000258 if (D->getFormalLinkage() != InternalLinkage)
Jordan Rose28cd12f2012-06-18 22:09:19 +0000259 return;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000260
Jordan Rose815fe262012-06-21 05:54:50 +0000261 // Downgrade from ExtWarn to Extension if
262 // (1) the supposedly external inline function is in the main file,
263 // and probably won't be included anywhere else.
264 // (2) the thing we're referencing is a pure function.
265 // (3) the thing we're referencing is another inline function.
266 // This last can give us false negatives, but it's better than warning on
267 // wrappers for simple C library functions.
268 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
Eli Friedman5ba37d52013-08-22 00:27:10 +0000269 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
Jordan Rose815fe262012-06-21 05:54:50 +0000270 if (!DowngradeWarning && UsedFn)
271 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
272
Richard Smith1b98ccc2014-07-19 01:39:17 +0000273 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
274 : diag::ext_internal_in_extern_inline)
Jordan Rose815fe262012-06-21 05:54:50 +0000275 << /*IsVar=*/!UsedFn << D;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000276
John McCallc87d9722013-04-02 02:48:58 +0000277 S.MaybeSuggestAddingStaticToDecl(Current);
Jordan Rose28cd12f2012-06-18 22:09:19 +0000278
Alp Toker2afa8782014-05-28 12:20:14 +0000279 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
280 << D;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000281}
282
John McCallc87d9722013-04-02 02:48:58 +0000283void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
Rafael Espindola8db352d2013-10-17 15:37:26 +0000284 const FunctionDecl *First = Cur->getFirstDecl();
John McCallc87d9722013-04-02 02:48:58 +0000285
286 // Suggest "static" on the function, if possible.
287 if (!hasAnyExplicitStorageClass(First)) {
288 SourceLocation DeclBegin = First->getSourceRange().getBegin();
289 Diag(DeclBegin, diag::note_convert_inline_to_static)
290 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
291 }
292}
293
Douglas Gregor171c45a2009-02-18 21:56:37 +0000294/// \brief Determine whether the use of this declaration is valid, and
295/// emit any corresponding diagnostics.
296///
297/// This routine diagnoses various problems with referencing
298/// declarations that can occur when using a declaration. For example,
299/// it might warn if a deprecated or unavailable declaration is being
300/// used, or produce an error (and return true) if a C++0x deleted
301/// function is being used.
302///
303/// \returns true if there was an error (this declaration cannot be
304/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +0000305///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +0000306bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian89ea9612014-06-16 17:25:41 +0000307 const ObjCInterfaceDecl *UnknownObjCClass,
308 bool ObjCPropertyAccess) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000309 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000310 // If there were any diagnostics suppressed by template argument deduction,
311 // emit them now.
Craig Topperdfe29ae2015-12-21 06:35:56 +0000312 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000313 if (Pos != SuppressedDiagnostics.end()) {
Craig Topperdfe29ae2015-12-21 06:35:56 +0000314 for (const PartialDiagnosticAt &Suppressed : Pos->second)
315 Diag(Suppressed.first, Suppressed.second);
Richard Smithb63b6ee2014-01-22 01:43:19 +0000316
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000317 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000318 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000319 // entry from the table, because we want to avoid ever emitting these
320 // diagnostics again.
Craig Topperdfe29ae2015-12-21 06:35:56 +0000321 Pos->second.clear();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000322 }
Richard Smithb63b6ee2014-01-22 01:43:19 +0000323
324 // C++ [basic.start.main]p3:
325 // The function 'main' shall not be used within a program.
326 if (cast<FunctionDecl>(D)->isMain())
327 Diag(Loc, diag::ext_main_used);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000328 }
329
Richard Smith30482bc2011-02-20 03:19:35 +0000330 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +0000331 if (ParsingInitForAutoVars.count(D)) {
Richard Smithbdb84f32016-07-22 23:36:59 +0000332 if (isa<BindingDecl>(D)) {
333 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
334 << D->getDeclName();
335 } else {
336 const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType();
Richard Smithe301ba22015-11-11 02:02:15 +0000337
Richard Smithbdb84f32016-07-22 23:36:59 +0000338 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
339 << D->getDeclName() << (unsigned)AT->getKeyword();
340 }
Richard Smithb2bc2e62011-02-21 20:05:19 +0000341 return true;
Richard Smith30482bc2011-02-20 03:19:35 +0000342 }
343
Douglas Gregor171c45a2009-02-18 21:56:37 +0000344 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +0000345 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +0000346 if (FD->isDeleted()) {
Richard Smith80a47022016-06-29 01:10:27 +0000347 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
348 if (Ctor && Ctor->isInheritingConstructor())
349 Diag(Loc, diag::err_deleted_inherited_ctor_use)
350 << Ctor->getParent()
351 << Ctor->getInheritedConstructor().getConstructor()->getParent();
352 else
353 Diag(Loc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +0000354 NoteDeletedFunction(FD);
Douglas Gregor171c45a2009-02-18 21:56:37 +0000355 return true;
356 }
Richard Smith2a7d4812013-05-04 07:00:32 +0000357
358 // If the function has a deduced return type, and we can't deduce it,
359 // then we can't use it either.
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000360 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +0000361 DeduceReturnType(FD, Loc))
362 return true;
Justin Lebar9fdb46e2016-10-08 01:07:11 +0000363
364 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
365 return true;
Douglas Gregorde681d42009-02-24 04:26:15 +0000366 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000367
368 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
369 // Only the variables omp_in and omp_out are allowed in the combiner.
370 // Only the variables omp_priv and omp_orig are allowed in the
371 // initializer-clause.
372 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
373 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
374 isa<VarDecl>(D)) {
375 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
376 << getCurFunction()->HasOMPDeclareReductionCombiner;
377 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
378 return true;
379 }
Nico Weber0055a192015-03-19 19:18:22 +0000380 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
381 ObjCPropertyAccess);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000382
Fariborz Jahanian66c93f42012-09-06 16:43:18 +0000383 DiagnoseUnusedOfDecl(*this, D, Loc);
Jordan Rose2684c682012-06-15 18:19:48 +0000384
Jordan Rose28cd12f2012-06-18 22:09:19 +0000385 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
Jordan Rose2684c682012-06-15 18:19:48 +0000386
Douglas Gregor171c45a2009-02-18 21:56:37 +0000387 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000388}
389
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000390/// \brief Retrieve the message suffix that should be added to a
391/// diagnostic complaining about the given function being deleted or
392/// unavailable.
393std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000394 std::string Message;
395 if (FD->getAvailability(&Message))
396 return ": " + Message;
397
398 return std::string();
399}
400
John McCallb46f2872011-09-09 07:56:05 +0000401/// DiagnoseSentinelCalls - This routine checks whether a call or
402/// message-send is to a declaration with the sentinel attribute, and
403/// if so, it checks that the requirements of the sentinel are
404/// satisfied.
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000405void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000406 ArrayRef<Expr *> Args) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000407 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000408 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000409 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000410
John McCallb46f2872011-09-09 07:56:05 +0000411 // The number of formal parameters of the declaration.
412 unsigned numFormalParams;
Mike Stump11289f42009-09-09 15:08:12 +0000413
John McCallb46f2872011-09-09 07:56:05 +0000414 // The kind of declaration. This is also an index into a %select in
415 // the diagnostic.
416 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
417
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000418 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000419 numFormalParams = MD->param_size();
420 calleeType = CT_Method;
Mike Stump12b8ce12009-08-04 21:02:39 +0000421 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000422 numFormalParams = FD->param_size();
423 calleeType = CT_Function;
424 } else if (isa<VarDecl>(D)) {
425 QualType type = cast<ValueDecl>(D)->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +0000426 const FunctionType *fn = nullptr;
John McCallb46f2872011-09-09 07:56:05 +0000427 if (const PointerType *ptr = type->getAs<PointerType>()) {
428 fn = ptr->getPointeeType()->getAs<FunctionType>();
429 if (!fn) return;
430 calleeType = CT_Function;
431 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
432 fn = ptr->getPointeeType()->castAs<FunctionType>();
433 calleeType = CT_Block;
434 } else {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000435 return;
John McCallb46f2872011-09-09 07:56:05 +0000436 }
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000437
John McCallb46f2872011-09-09 07:56:05 +0000438 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000439 numFormalParams = proto->getNumParams();
John McCallb46f2872011-09-09 07:56:05 +0000440 } else {
441 numFormalParams = 0;
442 }
443 } else {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000444 return;
445 }
John McCallb46f2872011-09-09 07:56:05 +0000446
447 // "nullPos" is the number of formal parameters at the end which
448 // effectively count as part of the variadic arguments. This is
449 // useful if you would prefer to not have *any* formal parameters,
450 // but the language forces you to have at least one.
451 unsigned nullPos = attr->getNullPos();
452 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
453 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
454
455 // The number of arguments which should follow the sentinel.
456 unsigned numArgsAfterSentinel = attr->getSentinel();
457
458 // If there aren't enough arguments for all the formal parameters,
459 // the sentinel, and the args after the sentinel, complain.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000460 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000461 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000462 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000463 return;
464 }
John McCallb46f2872011-09-09 07:56:05 +0000465
466 // Otherwise, find the sentinel expression.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000467 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
John McCall7ddbcf42010-05-06 23:53:00 +0000468 if (!sentinelExpr) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000469 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +0000470 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000471
Reid Kleckner92493e52014-11-13 23:19:36 +0000472 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
473 // or 'NULL' if those are actually defined in the context. Only use
John McCallb46f2872011-09-09 07:56:05 +0000474 // 'nil' for ObjC methods, where it's much more likely that the
475 // variadic arguments form a list of object pointers.
476 SourceLocation MissingNilLoc
Craig Topper07fa1762015-11-15 02:31:46 +0000477 = getLocForEndOfToken(sentinelExpr->getLocEnd());
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000478 std::string NullValue;
Richard Smith20e883e2015-04-29 23:20:19 +0000479 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000480 NullValue = "nil";
Reid Kleckner92493e52014-11-13 23:19:36 +0000481 else if (getLangOpts().CPlusPlus11)
482 NullValue = "nullptr";
Richard Smith20e883e2015-04-29 23:20:19 +0000483 else if (PP.isMacroDefined("NULL"))
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000484 NullValue = "NULL";
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000485 else
John McCallb46f2872011-09-09 07:56:05 +0000486 NullValue = "(void*) 0";
Eli Friedman9ab36372011-09-27 23:46:37 +0000487
488 if (MissingNilLoc.isInvalid())
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000489 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
Eli Friedman9ab36372011-09-27 23:46:37 +0000490 else
491 Diag(MissingNilLoc, diag::warn_missing_sentinel)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000492 << int(calleeType)
Eli Friedman9ab36372011-09-27 23:46:37 +0000493 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000494 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000495}
496
Richard Trieuba63ce62011-09-09 01:45:06 +0000497SourceRange Sema::getExprRange(Expr *E) const {
498 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor87f95b02009-02-26 21:00:50 +0000499}
500
Chris Lattner513165e2008-07-25 21:10:04 +0000501//===----------------------------------------------------------------------===//
502// Standard Promotions and Conversions
503//===----------------------------------------------------------------------===//
504
Chris Lattner513165e2008-07-25 21:10:04 +0000505/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000506ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
John McCall50a2c2c2011-10-11 23:14:30 +0000507 // Handle any placeholder expressions which made it here.
508 if (E->getType()->isPlaceholderType()) {
509 ExprResult result = CheckPlaceholderExpr(E);
510 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000511 E = result.get();
John McCall50a2c2c2011-10-11 23:14:30 +0000512 }
513
Chris Lattner513165e2008-07-25 21:10:04 +0000514 QualType Ty = E->getType();
515 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
516
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +0000517 if (Ty->isFunctionType()) {
518 // If we are here, we are not calling a function but taking
519 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
520 if (getLangOpts().OpenCL) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000521 if (Diagnose)
522 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +0000523 return ExprError();
524 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000525
526 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
527 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
528 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
529 return ExprError();
530
John Wiegley01296292011-04-08 18:41:53 +0000531 E = ImpCastExprToType(E, Context.getPointerType(Ty),
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000532 CK_FunctionToPointerDecay).get();
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +0000533 } else if (Ty->isArrayType()) {
Chris Lattner61f60a02008-07-25 21:33:13 +0000534 // In C90 mode, arrays only promote to pointers if the array expression is
535 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
536 // type 'array of type' is converted to an expression that has type 'pointer
537 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
538 // that has type 'array of type' ...". The relevant change is "an lvalue"
539 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000540 //
541 // C++ 4.2p1:
542 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
543 // T" can be converted to an rvalue of type "pointer to T".
544 //
David Blaikiebbafb8a2012-03-11 07:00:24 +0000545 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000546 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000547 CK_ArrayToPointerDecay).get();
Chris Lattner61f60a02008-07-25 21:33:13 +0000548 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000549 return E;
Chris Lattner513165e2008-07-25 21:10:04 +0000550}
551
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000552static void CheckForNullPointerDereference(Sema &S, Expr *E) {
553 // Check to see if we are dereferencing a null pointer. If so,
554 // and if not volatile-qualified, this is undefined behavior that the
555 // optimizer will delete, so warn about it. People sometimes try to use this
556 // to get a deterministic trap and are surprised by clang's behavior. This
557 // only handles the pattern "*null", which is a very syntactic check.
558 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
559 if (UO->getOpcode() == UO_Deref &&
560 UO->getSubExpr()->IgnoreParenCasts()->
561 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
562 !UO->getType().isVolatileQualified()) {
563 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
564 S.PDiag(diag::warn_indirection_through_null)
565 << UO->getSubExpr()->getSourceRange());
566 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
567 S.PDiag(diag::note_indirection_through_null));
568 }
569}
570
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +0000571static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +0000572 SourceLocation AssignLoc,
573 const Expr* RHS) {
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +0000574 const ObjCIvarDecl *IV = OIRE->getDecl();
575 if (!IV)
576 return;
577
578 DeclarationName MemberName = IV->getDeclName();
579 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
580 if (!Member || !Member->isStr("isa"))
581 return;
582
583 const Expr *Base = OIRE->getBase();
584 QualType BaseType = Base->getType();
585 if (OIRE->isArrow())
586 BaseType = BaseType->getPointeeType();
587 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
588 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000589 ObjCInterfaceDecl *ClassDeclared = nullptr;
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +0000590 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
591 if (!ClassDeclared->getSuperClass()
592 && (*ClassDeclared->ivar_begin()) == IV) {
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +0000593 if (RHS) {
594 NamedDecl *ObjectSetClass =
595 S.LookupSingleName(S.TUScope,
596 &S.Context.Idents.get("object_setClass"),
597 SourceLocation(), S.LookupOrdinaryName);
598 if (ObjectSetClass) {
Craig Topper07fa1762015-11-15 02:31:46 +0000599 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +0000600 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
601 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
602 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
603 AssignLoc), ",") <<
604 FixItHint::CreateInsertion(RHSLocEnd, ")");
605 }
606 else
607 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
608 } else {
609 NamedDecl *ObjectGetClass =
610 S.LookupSingleName(S.TUScope,
611 &S.Context.Idents.get("object_getClass"),
612 SourceLocation(), S.LookupOrdinaryName);
613 if (ObjectGetClass)
614 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
615 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
616 FixItHint::CreateReplacement(
617 SourceRange(OIRE->getOpLoc(),
618 OIRE->getLocEnd()), ")");
619 else
620 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
621 }
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +0000622 S.Diag(IV->getLocation(), diag::note_ivar_decl);
623 }
624 }
625}
626
John Wiegley01296292011-04-08 18:41:53 +0000627ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000628 // Handle any placeholder expressions which made it here.
629 if (E->getType()->isPlaceholderType()) {
630 ExprResult result = CheckPlaceholderExpr(E);
631 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000632 E = result.get();
John McCall50a2c2c2011-10-11 23:14:30 +0000633 }
634
John McCallf3735e02010-12-01 04:43:34 +0000635 // C++ [conv.lval]p1:
636 // A glvalue of a non-function, non-array type T can be
637 // converted to a prvalue.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000638 if (!E->isGLValue()) return E;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +0000639
John McCall27584242010-12-06 20:48:59 +0000640 QualType T = E->getType();
641 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000642
John McCall27584242010-12-06 20:48:59 +0000643 // We don't want to throw lvalue-to-rvalue casts on top of
644 // expressions of certain types in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000645 if (getLangOpts().CPlusPlus &&
John McCall27584242010-12-06 20:48:59 +0000646 (E->getType() == Context.OverloadTy ||
647 T->isDependentType() ||
648 T->isRecordType()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000649 return E;
John McCall27584242010-12-06 20:48:59 +0000650
651 // The C standard is actually really unclear on this point, and
652 // DR106 tells us what the result should be but not why. It's
653 // generally best to say that void types just doesn't undergo
654 // lvalue-to-rvalue at all. Note that expressions of unqualified
655 // 'void' type are never l-values, but qualified void can be.
656 if (T->isVoidType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000657 return E;
John McCall27584242010-12-06 20:48:59 +0000658
John McCall6ced97a2013-02-12 01:29:43 +0000659 // OpenCL usually rejects direct accesses to values of 'half' type.
Yaxun Liu5b746652016-12-18 05:18:55 +0000660 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
John McCall6ced97a2013-02-12 01:29:43 +0000661 T->isHalfType()) {
662 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
663 << 0 << T;
664 return ExprError();
665 }
666
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000667 CheckForNullPointerDereference(*this, E);
Fariborz Jahanian06bb7f72013-03-28 19:50:55 +0000668 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
669 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
670 &Context.Idents.get("object_getClass"),
671 SourceLocation(), LookupOrdinaryName);
672 if (ObjectGetClass)
673 Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
674 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
675 FixItHint::CreateReplacement(
676 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
677 else
678 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
679 }
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +0000680 else if (const ObjCIvarRefExpr *OIRE =
681 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
Craig Topperc3ec1492014-05-26 06:22:03 +0000682 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
683
John McCall27584242010-12-06 20:48:59 +0000684 // C++ [conv.lval]p1:
685 // [...] If T is a non-class type, the type of the prvalue is the
686 // cv-unqualified version of T. Otherwise, the type of the
687 // rvalue is T.
688 //
689 // C99 6.3.2.1p2:
690 // If the lvalue has qualified type, the value has the unqualified
691 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000692 // type of the lvalue.
John McCall27584242010-12-06 20:48:59 +0000693 if (T.hasQualifiers())
694 T = T.getUnqualifiedType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000695
Richard Smithdb0ac552015-12-18 22:40:25 +0000696 // Under the MS ABI, lock down the inheritance model now.
David Majnemercca07d72015-09-10 07:20:05 +0000697 if (T->isMemberPointerType() &&
698 Context.getTargetInfo().getCXXABI().isMicrosoft())
Richard Smithdb0ac552015-12-18 22:40:25 +0000699 (void)isCompleteType(E->getExprLoc(), T);
David Majnemercca07d72015-09-10 07:20:05 +0000700
Eli Friedman3bda6b12012-02-02 23:15:15 +0000701 UpdateMarkingForLValueToRValue(E);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +0000702
703 // Loading a __weak object implicitly retains the value, so we need a cleanup to
704 // balance that.
705 if (getLangOpts().ObjCAutoRefCount &&
706 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
Tim Shen4a05bb82016-06-21 20:29:17 +0000707 Cleanup.setExprNeedsCleanups(true);
Eli Friedman3bda6b12012-02-02 23:15:15 +0000708
Renato Golin6a051ba2016-11-14 12:19:18 +0000709 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
710 nullptr, VK_RValue);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000711
Douglas Gregorc79862f2012-04-12 17:51:55 +0000712 // C11 6.3.2.1p2:
713 // ... if the lvalue has atomic type, the value has the non-atomic version
714 // of the type of the lvalue ...
715 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
716 T = Atomic->getValueType().getUnqualifiedType();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000717 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
718 nullptr, VK_RValue);
Douglas Gregorc79862f2012-04-12 17:51:55 +0000719 }
720
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000721 return Res;
John McCall27584242010-12-06 20:48:59 +0000722}
723
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000724ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
725 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
John Wiegley01296292011-04-08 18:41:53 +0000726 if (Res.isInvalid())
727 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000728 Res = DefaultLvalueConversion(Res.get());
John Wiegley01296292011-04-08 18:41:53 +0000729 if (Res.isInvalid())
730 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000731 return Res;
Douglas Gregorb92a1562010-02-03 00:27:59 +0000732}
733
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +0000734/// CallExprUnaryConversions - a special case of an unary conversion
735/// performed on a function designator of a call expression.
736ExprResult Sema::CallExprUnaryConversions(Expr *E) {
737 QualType Ty = E->getType();
738 ExprResult Res = E;
739 // Only do implicit cast for a function type, but not for a pointer
740 // to function type.
741 if (Ty->isFunctionType()) {
742 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000743 CK_FunctionToPointerDecay).get();
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +0000744 if (Res.isInvalid())
745 return ExprError();
746 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000747 Res = DefaultLvalueConversion(Res.get());
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +0000748 if (Res.isInvalid())
749 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000750 return Res.get();
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +0000751}
Douglas Gregorb92a1562010-02-03 00:27:59 +0000752
Chris Lattner513165e2008-07-25 21:10:04 +0000753/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000754/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000755/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000756/// apply if the array is an argument to the sizeof or address (&) operators.
757/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000758ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000759 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000760 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
761 if (Res.isInvalid())
Fariborz Jahanian47ef4662013-03-06 00:37:40 +0000762 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000763 E = Res.get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000764
John McCallf3735e02010-12-01 04:43:34 +0000765 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000766 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000767
Joey Goulydd7f4562013-01-23 11:56:20 +0000768 // Half FP have to be promoted to float unless it is natively supported
769 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000770 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000771
John McCallf3735e02010-12-01 04:43:34 +0000772 // Try to perform integral promotions if the object has a theoretically
773 // promotable type.
774 if (Ty->isIntegralOrUnscopedEnumerationType()) {
775 // C99 6.3.1.1p2:
776 //
777 // The following may be used in an expression wherever an int or
778 // unsigned int may be used:
779 // - an object or expression with an integer type whose integer
780 // conversion rank is less than or equal to the rank of int
781 // and unsigned int.
782 // - A bit-field of type _Bool, int, signed int, or unsigned int.
783 //
784 // If an int can represent all values of the original type, the
785 // value is converted to an int; otherwise, it is converted to an
786 // unsigned int. These are called the integer promotions. All
787 // other types are unchanged by the integer promotions.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000788
John McCallf3735e02010-12-01 04:43:34 +0000789 QualType PTy = Context.isPromotableBitField(E);
790 if (!PTy.isNull()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000791 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000792 return E;
John McCallf3735e02010-12-01 04:43:34 +0000793 }
794 if (Ty->isPromotableIntegerType()) {
795 QualType PT = Context.getPromotedIntegerType(Ty);
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000796 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000797 return E;
John McCallf3735e02010-12-01 04:43:34 +0000798 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000799 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000800 return E;
Chris Lattner513165e2008-07-25 21:10:04 +0000801}
802
Chris Lattner2ce500f2008-07-25 22:25:12 +0000803/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Tim Northoverda165072013-01-30 09:46:55 +0000804/// do not have a prototype. Arguments that have type float or __fp16
805/// are promoted to double. All other argument types are converted by
806/// UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000807ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
808 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000809 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000810
John Wiegley01296292011-04-08 18:41:53 +0000811 ExprResult Res = UsualUnaryConversions(E);
812 if (Res.isInvalid())
Fariborz Jahanian47ef4662013-03-06 00:37:40 +0000813 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000814 E = Res.get();
John McCall9bc26772010-12-06 18:36:11 +0000815
Tim Northoverda165072013-01-30 09:46:55 +0000816 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
817 // double.
818 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
819 if (BTy && (BTy->getKind() == BuiltinType::Half ||
Neil Hickey88c0fac2016-12-13 16:22:50 +0000820 BTy->getKind() == BuiltinType::Float)) {
821 if (getLangOpts().OpenCL &&
Yaxun Liu5b746652016-12-18 05:18:55 +0000822 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
Neil Hickey88c0fac2016-12-13 16:22:50 +0000823 if (BTy->getKind() == BuiltinType::Half) {
824 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
825 }
826 } else {
827 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
828 }
829 }
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) !=
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001197 &llvm::APFloat::IEEEdouble());
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001198}
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) {
Alexey Bataev07649fb2014-12-16 08:01:48 +00001743 bool RefersToCapturedVariable =
Alexey Bataevf841bd92014-12-16 07:00:22 +00001744 isa<VarDecl>(D) &&
1745 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
John McCall113bee02012-03-10 09:33:50 +00001746
Larisse Voufo39a1e502013-08-06 01:03:05 +00001747 DeclRefExpr *E;
1748 if (isa<VarTemplateSpecializationDecl>(D)) {
1749 VarTemplateSpecializationDecl *VarSpec =
1750 cast<VarTemplateSpecializationDecl>(D);
1751
Alexey Bataev19acc3d2015-01-12 10:17:46 +00001752 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1753 : NestedNameSpecifierLoc(),
1754 VarSpec->getTemplateKeywordLoc(), D,
1755 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1756 FoundD, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001757 } else {
1758 assert(!TemplateArgs && "No template arguments for non-variable"
Alp Tokerf6a24ce2013-12-05 16:25:25 +00001759 " template specialization references");
Alexey Bataev07649fb2014-12-16 08:01:48 +00001760 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1761 : NestedNameSpecifierLoc(),
1762 SourceLocation(), D, RefersToCapturedVariable,
1763 NameInfo, Ty, VK, FoundD);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001764 }
Mike Stump11289f42009-09-09 15:08:12 +00001765
Eli Friedmanfa0df832012-02-02 03:46:19 +00001766 MarkDeclRefReferenced(E);
John McCall086a4642010-11-24 05:12:34 +00001767
John McCall460ce582015-10-22 18:38:17 +00001768 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001769 Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1770 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
Fariborz Jahanian6f829e32013-05-21 21:20:26 +00001771 recordUseOfEvaluatedWeak(E);
Jordan Rose657b5f42012-09-28 22:21:35 +00001772
Olivier Goffart63a20832016-05-09 07:09:51 +00001773 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1774 UnusedPrivateFields.remove(FD);
1775 // Just in case we're building an illegal pointer-to-member.
1776 if (FD->isBitField())
1777 E->setObjectKind(OK_BitField);
1778 }
John McCall086a4642010-11-24 05:12:34 +00001779
Richard Smith7873de02016-08-11 22:25:46 +00001780 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1781 // designates a bit-field.
1782 if (auto *BD = dyn_cast<BindingDecl>(D))
1783 if (auto *BE = BD->getBinding())
1784 E->setObjectKind(BE->getObjectKind());
1785
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001786 return E;
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001787}
1788
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001789/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001790/// possibly a list of template arguments.
1791///
1792/// If this produces template arguments, it is permitted to call
1793/// DecomposeTemplateName.
1794///
1795/// This actually loses a lot of source location information for
1796/// non-standard name kinds; we should consider preserving that in
1797/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001798void
1799Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1800 TemplateArgumentListInfo &Buffer,
1801 DeclarationNameInfo &NameInfo,
1802 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001803 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1804 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1805 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1806
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001807 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
John McCall10eae182009-11-30 22:42:35 +00001808 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001809 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001810
John McCall3e56fd42010-08-23 07:28:44 +00001811 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001812 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001813 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001814 TemplateArgs = &Buffer;
1815 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001816 NameInfo = GetNameFromUnqualifiedId(Id);
Craig Topperc3ec1492014-05-26 06:22:03 +00001817 TemplateArgs = nullptr;
John McCall10eae182009-11-30 22:42:35 +00001818 }
1819}
1820
Kaelyn Takatab16e6322014-11-20 22:06:40 +00001821static void emitEmptyLookupTypoDiagnostic(
1822 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1823 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1824 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1825 DeclContext *Ctx =
1826 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1827 if (!TC) {
1828 // Emit a special diagnostic for failed member lookups.
1829 // FIXME: computing the declaration context might fail here (?)
1830 if (Ctx)
1831 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1832 << SS.getRange();
1833 else
1834 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1835 return;
1836 }
1837
1838 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1839 bool DroppedSpecifier =
1840 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
Richard Smithde6d6c42015-12-29 19:43:10 +00001841 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1842 ? diag::note_implicit_param_decl
1843 : diag::note_previous_decl;
Kaelyn Takatab16e6322014-11-20 22:06:40 +00001844 if (!Ctx)
1845 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1846 SemaRef.PDiag(NoteID));
1847 else
1848 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1849 << Typo << Ctx << DroppedSpecifier
1850 << SS.getRange(),
1851 SemaRef.PDiag(NoteID));
1852}
1853
John McCalld681c392009-12-16 08:11:27 +00001854/// Diagnose an empty lookup.
1855///
1856/// \return false if new lookup candidates were found
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001857bool
1858Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1859 std::unique_ptr<CorrectionCandidateCallback> CCC,
1860 TemplateArgumentListInfo *ExplicitTemplateArgs,
Kaelyn Takatab16e6322014-11-20 22:06:40 +00001861 ArrayRef<Expr *> Args, TypoExpr **Out) {
John McCalld681c392009-12-16 08:11:27 +00001862 DeclarationName Name = R.getLookupName();
1863
John McCalld681c392009-12-16 08:11:27 +00001864 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001865 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001866 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1867 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001868 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001869 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001870 diagnostic_suggest = diag::err_undeclared_use_suggest;
1871 }
John McCalld681c392009-12-16 08:11:27 +00001872
Douglas Gregor598b08f2009-12-31 05:20:13 +00001873 // If the original lookup was an unqualified lookup, fake an
1874 // unqualified lookup. This is useful when (for example) the
1875 // original lookup would not have found something because it was a
1876 // dependent name.
Richard Smith42fd9ef2015-10-05 20:05:21 +00001877 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
Francois Pichetde232cb2011-11-25 01:10:54 +00001878 while (DC) {
John McCalld681c392009-12-16 08:11:27 +00001879 if (isa<CXXRecordDecl>(DC)) {
1880 LookupQualifiedName(R, DC);
1881
1882 if (!R.empty()) {
1883 // Don't give errors about ambiguities in this lookup.
1884 R.suppressDiagnostics();
1885
Francois Pichet857f9d62011-11-17 03:44:24 +00001886 // During a default argument instantiation the CurContext points
1887 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1888 // function parameter list, hence add an explicit check.
1889 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1890 ActiveTemplateInstantiations.back().Kind ==
1891 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCalld681c392009-12-16 08:11:27 +00001892 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1893 bool isInstance = CurMethod &&
1894 CurMethod->isInstance() &&
Francois Pichet857f9d62011-11-17 03:44:24 +00001895 DC == CurMethod->getParent() && !isDefaultArgument;
John McCalld681c392009-12-16 08:11:27 +00001896
1897 // Give a code modification hint to insert 'this->'.
1898 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1899 // Actually quite difficult!
Alp Tokerbfa39342014-01-14 12:51:41 +00001900 if (getLangOpts().MSVCCompat)
Reid Kleckner10ca24c2014-06-11 00:01:28 +00001901 diagnostic = diag::ext_found_via_dependent_bases_lookup;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001902 if (isInstance) {
Nico Weber3c10fb12012-06-22 16:39:39 +00001903 Diag(R.getNameLoc(), diagnostic) << Name
1904 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
Nico Weber3c10fb12012-06-22 16:39:39 +00001905 CheckCXXThisCapture(R.getNameLoc());
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001906 } else {
John McCalld681c392009-12-16 08:11:27 +00001907 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001908 }
John McCalld681c392009-12-16 08:11:27 +00001909
1910 // Do we really want to note all of these?
Craig Topperdfe29ae2015-12-21 06:35:56 +00001911 for (NamedDecl *D : R)
1912 Diag(D->getLocation(), diag::note_dependent_var_use);
John McCalld681c392009-12-16 08:11:27 +00001913
Francois Pichet857f9d62011-11-17 03:44:24 +00001914 // Return true if we are inside a default argument instantiation
1915 // and the found name refers to an instance member function, otherwise
1916 // the function calling DiagnoseEmptyLookup will try to create an
1917 // implicit member call and this is wrong for default argument.
1918 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1919 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1920 return true;
1921 }
1922
John McCalld681c392009-12-16 08:11:27 +00001923 // Tell the callee to try to recover.
1924 return false;
1925 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001926
1927 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001928 }
Francois Pichetde232cb2011-11-25 01:10:54 +00001929
1930 // In Microsoft mode, if we are performing lookup from within a friend
1931 // function definition declared at class scope then we must set
1932 // DC to the lexical parent to be able to search into the parent
1933 // class.
Alp Tokerbfa39342014-01-14 12:51:41 +00001934 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
Francois Pichetde232cb2011-11-25 01:10:54 +00001935 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1936 DC->getLexicalParent()->isRecord())
1937 DC = DC->getLexicalParent();
1938 else
1939 DC = DC->getParent();
John McCalld681c392009-12-16 08:11:27 +00001940 }
1941
Douglas Gregor598b08f2009-12-31 05:20:13 +00001942 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001943 TypoCorrection Corrected;
Kaelyn Takatab16e6322014-11-20 22:06:40 +00001944 if (S && Out) {
1945 SourceLocation TypoLoc = R.getNameLoc();
1946 assert(!ExplicitTemplateArgs &&
1947 "Diagnosing an empty lookup with explicit template args!");
1948 *Out = CorrectTypoDelayed(
1949 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1950 [=](const TypoCorrection &TC) {
1951 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1952 diagnostic, diagnostic_suggest);
1953 },
1954 nullptr, CTK_ErrorRecovery);
1955 if (*Out)
1956 return true;
1957 } else if (S && (Corrected =
1958 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1959 &SS, std::move(CCC), CTK_ErrorRecovery))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001960 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
Richard Smithf9b15102013-08-17 00:46:16 +00001961 bool DroppedSpecifier =
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00001962 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001963 R.setLookupName(Corrected.getCorrection());
1964
Richard Smithf9b15102013-08-17 00:46:16 +00001965 bool AcceptableWithRecovery = false;
1966 bool AcceptableWithoutRecovery = false;
Richard Smithde6d6c42015-12-29 19:43:10 +00001967 NamedDecl *ND = Corrected.getFoundDecl();
Richard Smithf9b15102013-08-17 00:46:16 +00001968 if (ND) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001969 if (Corrected.isOverloaded()) {
Richard Smith100b24a2014-04-17 01:52:14 +00001970 OverloadCandidateSet OCS(R.getNameLoc(),
1971 OverloadCandidateSet::CSK_Normal);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001972 OverloadCandidateSet::iterator Best;
Craig Topperdfe29ae2015-12-21 06:35:56 +00001973 for (NamedDecl *CD : Corrected) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001974 if (FunctionTemplateDecl *FTD =
Craig Topperdfe29ae2015-12-21 06:35:56 +00001975 dyn_cast<FunctionTemplateDecl>(CD))
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001976 AddTemplateOverloadCandidate(
1977 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001978 Args, OCS);
Craig Topperdfe29ae2015-12-21 06:35:56 +00001979 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001980 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1981 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001982 Args, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001983 }
1984 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001985 case OR_Success:
Richard Smithde6d6c42015-12-29 19:43:10 +00001986 ND = Best->FoundDecl;
Richard Smithf9b15102013-08-17 00:46:16 +00001987 Corrected.setCorrectionDecl(ND);
1988 break;
1989 default:
1990 // FIXME: Arbitrarily pick the first declaration for the note.
1991 Corrected.setCorrectionDecl(ND);
1992 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001993 }
1994 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001995 R.addDecl(ND);
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00001996 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1997 CXXRecordDecl *Record = nullptr;
1998 if (Corrected.getCorrectionSpecifier()) {
1999 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2000 Record = Ty->getAsCXXRecordDecl();
2001 }
2002 if (!Record)
2003 Record = cast<CXXRecordDecl>(
2004 ND->getDeclContext()->getRedeclContext());
2005 R.setNamingClass(Record);
2006 }
Ted Kremenekc6ebda12013-02-21 21:40:44 +00002007
Richard Smithde6d6c42015-12-29 19:43:10 +00002008 auto *UnderlyingND = ND->getUnderlyingDecl();
2009 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2010 isa<FunctionTemplateDecl>(UnderlyingND);
Richard Smithf9b15102013-08-17 00:46:16 +00002011 // FIXME: If we ended up with a typo for a type name or
2012 // Objective-C class name, we're in trouble because the parser
2013 // is in the wrong place to recover. Suggest the typo
2014 // correction, but don't make it a fix-it since we're not going
2015 // to recover well anyway.
2016 AcceptableWithoutRecovery =
Richard Smithde6d6c42015-12-29 19:43:10 +00002017 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002018 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00002019 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002020 // because we aren't able to recover.
Richard Smithf9b15102013-08-17 00:46:16 +00002021 AcceptableWithoutRecovery = true;
2022 }
2023
2024 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
Richard Smithde6d6c42015-12-29 19:43:10 +00002025 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
Richard Smithf9b15102013-08-17 00:46:16 +00002026 ? diag::note_implicit_param_decl
2027 : diag::note_previous_decl;
Douglas Gregor25363982010-01-01 00:15:04 +00002028 if (SS.isEmpty())
Richard Smithf9b15102013-08-17 00:46:16 +00002029 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2030 PDiag(NoteID), AcceptableWithRecovery);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002031 else
Richard Smithf9b15102013-08-17 00:46:16 +00002032 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2033 << Name << computeDeclContext(SS, false)
2034 << DroppedSpecifier << SS.getRange(),
2035 PDiag(NoteID), AcceptableWithRecovery);
2036
2037 // Tell the callee whether to try to recover.
2038 return !AcceptableWithRecovery;
Douglas Gregor25363982010-01-01 00:15:04 +00002039 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00002040 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002041 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00002042
2043 // Emit a special diagnostic for failed member lookups.
2044 // FIXME: computing the declaration context might fail here (?)
2045 if (!SS.isEmpty()) {
2046 Diag(R.getNameLoc(), diag::err_no_member)
2047 << Name << computeDeclContext(SS, false)
2048 << SS.getRange();
2049 return true;
2050 }
2051
John McCalld681c392009-12-16 08:11:27 +00002052 // Give up, we can't recover.
2053 Diag(R.getNameLoc(), diagnostic) << Name;
2054 return true;
2055}
2056
Reid Kleckner10ca24c2014-06-11 00:01:28 +00002057/// In Microsoft mode, if we are inside a template class whose parent class has
2058/// dependent base classes, and we can't resolve an unqualified identifier, then
2059/// assume the identifier is a member of a dependent base class. We can only
2060/// recover successfully in static methods, instance methods, and other contexts
2061/// where 'this' is available. This doesn't precisely match MSVC's
2062/// instantiation model, but it's close enough.
2063static Expr *
2064recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2065 DeclarationNameInfo &NameInfo,
2066 SourceLocation TemplateKWLoc,
2067 const TemplateArgumentListInfo *TemplateArgs) {
2068 // Only try to recover from lookup into dependent bases in static methods or
2069 // contexts where 'this' is available.
2070 QualType ThisType = S.getCurrentThisType();
2071 const CXXRecordDecl *RD = nullptr;
2072 if (!ThisType.isNull())
2073 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2074 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2075 RD = MD->getParent();
2076 if (!RD || !RD->hasAnyDependentBases())
2077 return nullptr;
2078
2079 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2080 // is available, suggest inserting 'this->' as a fixit.
2081 SourceLocation Loc = NameInfo.getLoc();
Reid Kleckner13a97992014-06-11 21:57:15 +00002082 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2083 DB << NameInfo.getName() << RD;
Reid Kleckner10ca24c2014-06-11 00:01:28 +00002084
2085 if (!ThisType.isNull()) {
2086 DB << FixItHint::CreateInsertion(Loc, "this->");
2087 return CXXDependentScopeMemberExpr::Create(
2088 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2089 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2090 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2091 }
2092
2093 // Synthesize a fake NNS that points to the derived class. This will
2094 // perform name lookup during template instantiation.
2095 CXXScopeSpec SS;
2096 auto *NNS =
2097 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2098 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2099 return DependentScopeDeclRefExpr::Create(
2100 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2101 TemplateArgs);
2102}
2103
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002104ExprResult
2105Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2106 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2107 bool HasTrailingLParen, bool IsAddressOfOperand,
2108 std::unique_ptr<CorrectionCandidateCallback> CCC,
Kaelyn Takatab16e6322014-11-20 22:06:40 +00002109 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002110 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCalle66edc12009-11-24 19:00:30 +00002111 "cannot be direct & operand and have a trailing lparen");
John McCalle66edc12009-11-24 19:00:30 +00002112 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00002113 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00002114
John McCall10eae182009-11-30 22:42:35 +00002115 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00002116
2117 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002118 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00002119 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00002120 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00002121
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002122 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00002123 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002124 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002125
John McCalle66edc12009-11-24 19:00:30 +00002126 // C++ [temp.dep.expr]p3:
2127 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00002128 // -- an identifier that was declared with a dependent type,
2129 // (note: handled after lookup)
2130 // -- a template-id that is dependent,
2131 // (note: handled in BuildTemplateIdExpr)
2132 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00002133 // -- a nested-name-specifier that contains a class-name that
2134 // names a dependent type.
2135 // Determine whether this is a member of an unknown specialization;
2136 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00002137 bool DependentID = false;
2138 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2139 Name.getCXXNameType()->isDependentType()) {
2140 DependentID = true;
2141 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002142 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00002143 if (RequireCompleteDeclContext(SS, DC))
2144 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00002145 } else {
2146 DependentID = true;
2147 }
2148 }
2149
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002150 if (DependentID)
Abramo Bagnara7945c982012-01-27 09:46:47 +00002151 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2152 IsAddressOfOperand, TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00002153
John McCalle66edc12009-11-24 19:00:30 +00002154 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00002155 LookupResult R(*this, NameInfo,
2156 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2157 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00002158 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00002159 // Lookup the template name again to correctly establish the context in
2160 // which it was found. This is really unfortunate as we already did the
2161 // lookup to determine that it was a template name in the first place. If
2162 // this becomes a performance hit, we can work harder to preserve those
2163 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00002164 bool MemberOfUnknownSpecialization;
2165 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2166 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00002167
2168 if (MemberOfUnknownSpecialization ||
2169 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnara7945c982012-01-27 09:46:47 +00002170 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2171 IsAddressOfOperand, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00002172 } else {
Benjamin Kramer46921442012-01-20 14:57:34 +00002173 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002174 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00002175
Douglas Gregora5226932011-02-04 13:35:07 +00002176 // If the result might be in a dependent base class, this is a dependent
2177 // id-expression.
2178 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnara7945c982012-01-27 09:46:47 +00002179 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2180 IsAddressOfOperand, TemplateArgs);
2181
John McCalle66edc12009-11-24 19:00:30 +00002182 // If this reference is in an Objective-C method, then we need to do
2183 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002184 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00002185 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00002186 if (E.isInvalid())
2187 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002188
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002189 if (Expr *Ex = E.getAs<Expr>())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002190 return Ex;
Steve Naroffebf4cb42008-06-02 23:03:37 +00002191 }
Chris Lattner59a25942008-03-31 00:36:02 +00002192 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00002193
John McCalle66edc12009-11-24 19:00:30 +00002194 if (R.isAmbiguous())
2195 return ExprError();
2196
Reid Kleckner59148b32014-06-09 23:16:24 +00002197 // This could be an implicitly declared function reference (legal in C90,
2198 // extension in C99, forbidden in C++).
2199 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2200 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2201 if (D) R.addDecl(D);
2202 }
2203
Douglas Gregor171c45a2009-02-18 21:56:37 +00002204 // Determine whether this name might be a candidate for
2205 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00002206 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00002207
John McCalle66edc12009-11-24 19:00:30 +00002208 if (R.empty() && !ADL) {
Alexey Bataev61deb4d2016-06-15 11:24:54 +00002209 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2210 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2211 TemplateKWLoc, TemplateArgs))
2212 return E;
2213 }
John McCalle66edc12009-11-24 19:00:30 +00002214
Nikola Smiljanic1c125682014-07-09 05:42:35 +00002215 // Don't diagnose an empty lookup for inline assembly.
Reid Kleckner59148b32014-06-09 23:16:24 +00002216 if (IsInlineAsmIdentifier)
2217 return ExprError();
2218
John McCalle66edc12009-11-24 19:00:30 +00002219 // If this name wasn't predeclared and if this is not a function
2220 // call, diagnose the problem.
Kaelyn Takatab16e6322014-11-20 22:06:40 +00002221 TypoExpr *TE = nullptr;
2222 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2223 II, SS.isValid() ? SS.getScopeRep() : nullptr);
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002224 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
Nick Lewycky9ea8efa2014-06-23 22:57:51 +00002225 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2226 "Typo correction callback misconfigured");
Kaelyn Takatab16e6322014-11-20 22:06:40 +00002227 if (CCC) {
2228 // Make sure the callback knows what the typo being diagnosed is.
2229 CCC->setTypoName(II);
2230 if (SS.isValid())
2231 CCC->setTypoNNS(SS.getScopeRep());
2232 }
Kaelyn Takata15867822014-11-21 18:48:04 +00002233 if (DiagnoseEmptyLookup(S, SS, R,
2234 CCC ? std::move(CCC) : std::move(DefaultValidator),
2235 nullptr, None, &TE)) {
Kaelyn Takatab16e6322014-11-20 22:06:40 +00002236 if (TE && KeywordReplacement) {
2237 auto &State = getTypoExprState(TE);
2238 auto BestTC = State.Consumer->getNextCorrection();
2239 if (BestTC.isKeyword()) {
2240 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2241 if (State.DiagHandler)
2242 State.DiagHandler(BestTC);
2243 KeywordReplacement->startToken();
2244 KeywordReplacement->setKind(II->getTokenID());
2245 KeywordReplacement->setIdentifierInfo(II);
2246 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2247 // Clean up the state associated with the TypoExpr, since it has
2248 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2249 clearDelayedTypo(TE);
2250 // Signal that a correction to a keyword was performed by returning a
2251 // valid-but-null ExprResult.
2252 return (Expr*)nullptr;
2253 }
2254 State.Consumer->resetCorrectionStream();
2255 }
2256 return TE ? TE : ExprError();
2257 }
Francois Pichetd8e4e412011-09-24 10:38:05 +00002258
Reid Kleckner59148b32014-06-09 23:16:24 +00002259 assert(!R.empty() &&
2260 "DiagnoseEmptyLookup returned false but added no results");
2261
2262 // If we found an Objective-C instance variable, let
2263 // LookupInObjCMethod build the appropriate expression to
2264 // reference the ivar.
2265 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2266 R.clear();
2267 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2268 // In a hopelessly buggy code, Objective-C instance variable
2269 // lookup fails and no expression will be built to reference it.
2270 if (!E.isInvalid() && !E.get())
Chad Rosierb9aff1e2013-05-24 18:32:55 +00002271 return ExprError();
Reid Kleckner59148b32014-06-09 23:16:24 +00002272 return E;
Steve Naroff92e30f82007-04-02 22:35:25 +00002273 }
Chris Lattner17ed4872006-11-20 04:58:19 +00002274 }
Mike Stump11289f42009-09-09 15:08:12 +00002275
John McCalle66edc12009-11-24 19:00:30 +00002276 // This is guaranteed from this point on.
2277 assert(!R.empty() || ADL);
2278
John McCall2d74de92009-12-01 22:10:20 +00002279 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00002280 // C++ [class.mfct.non-static]p3:
2281 // When an id-expression that is not part of a class member access
2282 // syntax and not used to form a pointer to member is used in the
2283 // body of a non-static member function of class X, if name lookup
2284 // resolves the name in the id-expression to a non-static non-type
2285 // member of some class C, the id-expression is transformed into a
2286 // class member access expression using (*this) as the
2287 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00002288 //
2289 // But we don't actually need to do this for '&' operands if R
2290 // resolved to a function or overloaded function set, because the
2291 // expression is ill-formed if it actually works out to be a
2292 // non-static member function:
2293 //
2294 // C++ [expr.ref]p4:
2295 // Otherwise, if E1.E2 refers to a non-static member function. . .
2296 // [t]he expression can be used only as the left-hand operand of a
2297 // member function call.
2298 //
2299 // There are other safeguards against such uses, but it's important
2300 // to get this right here so that we don't end up making a
2301 // spuriously dependent expression if we're inside a dependent
2302 // instance method.
John McCall57500772009-12-16 12:17:52 +00002303 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00002304 bool MightBeImplicitMember;
Richard Trieuba63ce62011-09-09 01:45:06 +00002305 if (!IsAddressOfOperand)
John McCall8d08b9b2010-08-27 09:08:28 +00002306 MightBeImplicitMember = true;
2307 else if (!SS.isEmpty())
2308 MightBeImplicitMember = false;
2309 else if (R.isOverloadedResult())
2310 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00002311 else if (R.isUnresolvableResult())
2312 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00002313 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00002314 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
Reid Kleckner0a0c8892013-06-19 16:37:23 +00002315 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2316 isa<MSPropertyDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00002317
2318 if (MightBeImplicitMember)
Abramo Bagnara7945c982012-01-27 09:46:47 +00002319 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00002320 R, TemplateArgs, S);
John McCallb53bbd42009-11-22 01:44:31 +00002321 }
2322
Larisse Voufo39a1e502013-08-06 01:03:05 +00002323 if (TemplateArgs || TemplateKWLoc.isValid()) {
2324
2325 // In C++1y, if this is a variable template id, then check it
2326 // in BuildTemplateIdExpr().
2327 // The single lookup result must be a variable template declaration.
2328 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2329 Id.TemplateId->Kind == TNK_Var_template) {
2330 assert(R.getAsSingle<VarTemplateDecl>() &&
2331 "There should only be one declaration found.");
2332 }
2333
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002334 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002335 }
John McCallb53bbd42009-11-22 01:44:31 +00002336
John McCalle66edc12009-11-24 19:00:30 +00002337 return BuildDeclarationNameExpr(SS, R, ADL);
2338}
2339
John McCall10eae182009-11-30 22:42:35 +00002340/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2341/// declaration name, generally during template instantiation.
2342/// There's a large number of things which don't need to be done along
2343/// this path.
Aaron Ballman6924dcd2015-09-01 14:49:24 +00002344ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2345 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2346 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
Richard Smith40c180d2012-10-23 19:56:01 +00002347 DeclContext *DC = computeDeclContext(SS, false);
2348 if (!DC)
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002349 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002350 NameInfo, /*TemplateArgs=*/nullptr);
John McCalle66edc12009-11-24 19:00:30 +00002351
John McCall0b66eb32010-05-01 00:40:08 +00002352 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00002353 return ExprError();
2354
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002355 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00002356 LookupQualifiedName(R, DC);
2357
2358 if (R.isAmbiguous())
2359 return ExprError();
2360
Richard Smith40c180d2012-10-23 19:56:01 +00002361 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2362 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002363 NameInfo, /*TemplateArgs=*/nullptr);
Richard Smith40c180d2012-10-23 19:56:01 +00002364
John McCalle66edc12009-11-24 19:00:30 +00002365 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002366 Diag(NameInfo.getLoc(), diag::err_no_member)
2367 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002368 return ExprError();
2369 }
2370
Reid Kleckner32506ed2014-06-12 23:03:48 +00002371 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2372 // Diagnose a missing typename if this resolved unambiguously to a type in
2373 // a dependent context. If we can recover with a type, downgrade this to
2374 // a warning in Microsoft compatibility mode.
2375 unsigned DiagID = diag::err_typename_missing;
2376 if (RecoveryTSI && getLangOpts().MSVCCompat)
2377 DiagID = diag::ext_typename_missing;
2378 SourceLocation Loc = SS.getBeginLoc();
2379 auto D = Diag(Loc, DiagID);
2380 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2381 << SourceRange(Loc, NameInfo.getEndLoc());
2382
2383 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2384 // context.
2385 if (!RecoveryTSI)
2386 return ExprError();
2387
2388 // Only issue the fixit if we're prepared to recover.
2389 D << FixItHint::CreateInsertion(Loc, "typename ");
2390
2391 // Recover by pretending this was an elaborated type.
2392 QualType Ty = Context.getTypeDeclType(TD);
2393 TypeLocBuilder TLB;
2394 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2395
2396 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2397 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2398 QTL.setElaboratedKeywordLoc(SourceLocation());
2399 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2400
2401 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2402
2403 return ExprEmpty();
Reid Kleckner377c1592014-06-10 23:29:48 +00002404 }
2405
Richard Smithdb2630f2012-10-21 03:28:35 +00002406 // Defend against this resolving to an implicit member access. We usually
2407 // won't get here if this might be a legitimate a class member (we end up in
2408 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2409 // a pointer-to-member or in an unevaluated context in C++11.
2410 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2411 return BuildPossibleImplicitMemberExpr(SS,
2412 /*TemplateKWLoc=*/SourceLocation(),
Aaron Ballman6924dcd2015-09-01 14:49:24 +00002413 R, /*TemplateArgs=*/nullptr, S);
Richard Smithdb2630f2012-10-21 03:28:35 +00002414
2415 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
John McCalle66edc12009-11-24 19:00:30 +00002416}
2417
2418/// LookupInObjCMethod - The parser has read a name in, and Sema has
2419/// detected that we're currently inside an ObjC method. Perform some
2420/// additional lookup.
2421///
2422/// Ideally, most of this would be done by lookup, but there's
2423/// actually quite a lot of extra work involved.
2424///
2425/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00002426ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002427Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00002428 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00002429 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00002430 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Fariborz Jahanian223ca5c2013-02-18 17:22:23 +00002431
2432 // Check for error condition which is already reported.
2433 if (!CurMethod)
2434 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002435
John McCalle66edc12009-11-24 19:00:30 +00002436 // There are two cases to handle here. 1) scoped lookup could have failed,
2437 // in which case we should look for an ivar. 2) scoped lookup could have
2438 // found a decl, but that decl is outside the current instance method (i.e.
2439 // a global variable). In these two cases, we do a lookup for an ivar with
2440 // this name, if the lookup sucedes, we replace it our current decl.
2441
2442 // If we're in a class method, we don't normally want to look for
2443 // ivars. But if we don't find anything else, and there's an
2444 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00002445 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00002446
2447 bool LookForIvars;
2448 if (Lookup.empty())
2449 LookForIvars = true;
2450 else if (IsClassMethod)
2451 LookForIvars = false;
2452 else
2453 LookForIvars = (Lookup.isSingleResult() &&
2454 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Craig Topperc3ec1492014-05-26 06:22:03 +00002455 ObjCInterfaceDecl *IFace = nullptr;
John McCalle66edc12009-11-24 19:00:30 +00002456 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00002457 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00002458 ObjCInterfaceDecl *ClassDeclared;
Craig Topperc3ec1492014-05-26 06:22:03 +00002459 ObjCIvarDecl *IV = nullptr;
Argyrios Kyrtzidis4e8b1362011-10-19 02:25:16 +00002460 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCalle66edc12009-11-24 19:00:30 +00002461 // Diagnose using an ivar in a class method.
2462 if (IsClassMethod)
Richard Smithf8812672016-12-02 22:38:31 +00002463 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
John McCalle66edc12009-11-24 19:00:30 +00002464 << IV->getDeclName());
2465
2466 // If we're referencing an invalid decl, just return this as a silent
2467 // error node. The error diagnostic was already emitted on the decl.
2468 if (IV->isInvalidDecl())
2469 return ExprError();
2470
2471 // Check if referencing a field with __attribute__((deprecated)).
2472 if (DiagnoseUseOfDecl(IV, Loc))
2473 return ExprError();
2474
2475 // Diagnose the use of an ivar outside of the declaring class.
2476 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00002477 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002478 !getLangOpts().DebuggerSupport)
Richard Smithf8812672016-12-02 22:38:31 +00002479 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
John McCalle66edc12009-11-24 19:00:30 +00002480
2481 // FIXME: This should use a new expr for a direct reference, don't
2482 // turn this into Self->ivar, just return a BareIVarExpr or something.
2483 IdentifierInfo &II = Context.Idents.get("self");
2484 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002485 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00002486 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00002487 CXXScopeSpec SelfScopeSpec;
Abramo Bagnara7945c982012-01-27 09:46:47 +00002488 SourceLocation TemplateKWLoc;
2489 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00002490 SelfName, false, false);
2491 if (SelfExpr.isInvalid())
2492 return ExprError();
2493
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002494 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00002495 if (SelfExpr.isInvalid())
2496 return ExprError();
John McCall27584242010-12-06 20:48:59 +00002497
Nick Lewycky45b50522013-02-02 00:25:55 +00002498 MarkAnyDeclReferenced(Loc, IV, true);
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00002499
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00002500 ObjCMethodFamily MF = CurMethod->getMethodFamily();
Fariborz Jahaniana934a022013-02-14 19:07:19 +00002501 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2502 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00002503 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
Jordan Rose657b5f42012-09-28 22:21:35 +00002504
Nico Weber21ad7e52014-07-27 04:09:29 +00002505 ObjCIvarRefExpr *Result = new (Context)
Douglas Gregore83b9562015-07-07 03:57:53 +00002506 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2507 IV->getLocation(), SelfExpr.get(), true, true);
Jordan Rose657b5f42012-09-28 22:21:35 +00002508
2509 if (getLangOpts().ObjCAutoRefCount) {
2510 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002511 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Fariborz Jahanian6f829e32013-05-21 21:20:26 +00002512 recordUseOfEvaluatedWeak(Result);
Jordan Rose657b5f42012-09-28 22:21:35 +00002513 }
Fariborz Jahanian4a675082012-10-03 17:55:29 +00002514 if (CurContext->isClosure())
2515 Diag(Loc, diag::warn_implicitly_retains_self)
2516 << FixItHint::CreateInsertion(Loc, "self->");
Jordan Rose657b5f42012-09-28 22:21:35 +00002517 }
2518
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002519 return Result;
John McCalle66edc12009-11-24 19:00:30 +00002520 }
Chris Lattner87313662010-04-12 05:10:17 +00002521 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00002522 // We should warn if a local variable hides an ivar.
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00002523 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2524 ObjCInterfaceDecl *ClassDeclared;
2525 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2526 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor0b144e12011-12-15 00:29:59 +00002527 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00002528 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2529 }
John McCalle66edc12009-11-24 19:00:30 +00002530 }
Fariborz Jahanian028b9e12011-12-20 22:21:08 +00002531 } else if (Lookup.isSingleResult() &&
2532 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2533 // If accessing a stand-alone ivar in a class method, this is an error.
2534 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
Richard Smithf8812672016-12-02 22:38:31 +00002535 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
Fariborz Jahanian028b9e12011-12-20 22:21:08 +00002536 << IV->getDeclName());
John McCalle66edc12009-11-24 19:00:30 +00002537 }
2538
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002539 if (Lookup.empty() && II && AllowBuiltinCreation) {
2540 // FIXME. Consolidate this with similar code in LookupName.
2541 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002542 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002543 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2544 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2545 S, Lookup.isForRedeclaration(),
2546 Lookup.getNameLoc());
2547 if (D) Lookup.addDecl(D);
2548 }
2549 }
2550 }
John McCalle66edc12009-11-24 19:00:30 +00002551 // Sentinel value saying that we didn't do anything special.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002552 return ExprResult((Expr *)nullptr);
Douglas Gregor3256d042009-06-30 15:47:41 +00002553}
John McCalld14a8642009-11-21 08:51:07 +00002554
John McCall16df1e52010-03-30 21:47:33 +00002555/// \brief Cast a base object to a member's actual type.
2556///
2557/// Logically this happens in three phases:
2558///
2559/// * First we cast from the base type to the naming class.
2560/// The naming class is the class into which we were looking
2561/// when we found the member; it's the qualifier type if a
2562/// qualifier was provided, and otherwise it's the base type.
2563///
2564/// * Next we cast from the naming class to the declaring class.
2565/// If the member we found was brought into a class's scope by
2566/// a using declaration, this is that class; otherwise it's
2567/// the class declaring the member.
2568///
2569/// * Finally we cast from the declaring class to the "true"
2570/// declaring class of the member. This conversion does not
2571/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00002572ExprResult
2573Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002574 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002575 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002576 NamedDecl *Member) {
2577 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2578 if (!RD)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002579 return From;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002580
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002581 QualType DestRecordType;
2582 QualType DestType;
2583 QualType FromRecordType;
2584 QualType FromType = From->getType();
2585 bool PointerConversions = false;
2586 if (isa<FieldDecl>(Member)) {
2587 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002588
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002589 if (FromType->getAs<PointerType>()) {
2590 DestType = Context.getPointerType(DestRecordType);
2591 FromRecordType = FromType->getPointeeType();
2592 PointerConversions = true;
2593 } else {
2594 DestType = DestRecordType;
2595 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002596 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002597 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2598 if (Method->isStatic())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002599 return From;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002600
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002601 DestType = Method->getThisType(Context);
2602 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002603
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002604 if (FromType->getAs<PointerType>()) {
2605 FromRecordType = FromType->getPointeeType();
2606 PointerConversions = true;
2607 } else {
2608 FromRecordType = FromType;
2609 DestType = DestRecordType;
2610 }
2611 } else {
2612 // No conversion necessary.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002613 return From;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002614 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002615
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002616 if (DestType->isDependentType() || FromType->isDependentType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002617 return From;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002618
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002619 // If the unqualified types are the same, no conversion is necessary.
2620 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002621 return From;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002622
John McCall16df1e52010-03-30 21:47:33 +00002623 SourceRange FromRange = From->getSourceRange();
2624 SourceLocation FromLoc = FromRange.getBegin();
2625
Eli Friedmanbe4b3632011-09-27 21:58:52 +00002626 ExprValueKind VK = From->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002627
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002628 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002629 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002630 // class name.
2631 //
2632 // If the member was a qualified name and the qualified referred to a
2633 // specific base subobject type, we'll cast to that intermediate type
2634 // first and then to the object in which the member is declared. That allows
2635 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2636 //
2637 // class Base { public: int x; };
2638 // class Derived1 : public Base { };
2639 // class Derived2 : public Base { };
2640 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2641 //
2642 // void VeryDerived::f() {
2643 // x = 17; // error: ambiguous base subobjects
2644 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2645 // }
David Majnemer13657812013-08-05 04:53:41 +00002646 if (Qualifier && Qualifier->getAsType()) {
John McCall16df1e52010-03-30 21:47:33 +00002647 QualType QType = QualType(Qualifier->getAsType(), 0);
John McCall16df1e52010-03-30 21:47:33 +00002648 assert(QType->isRecordType() && "lookup done with non-record type");
2649
2650 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2651
2652 // In C++98, the qualifier type doesn't actually have to be a base
2653 // type of the object type, in which case we just ignore it.
2654 // Otherwise build the appropriate casts.
Richard Smith0f59cb32015-12-18 21:45:41 +00002655 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002656 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002657 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002658 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002659 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002660
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002661 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002662 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002663 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002664 VK, &BasePath).get();
John McCall16df1e52010-03-30 21:47:33 +00002665
2666 FromType = QType;
2667 FromRecordType = QRecordType;
2668
2669 // If the qualifier type was the same as the destination type,
2670 // we're done.
2671 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002672 return From;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002673 }
2674 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002675
John McCall16df1e52010-03-30 21:47:33 +00002676 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002677
John McCall16df1e52010-03-30 21:47:33 +00002678 // If we actually found the member through a using declaration, cast
2679 // down to the using declaration's type.
2680 //
2681 // Pointer equality is fine here because only one declaration of a
2682 // class ever has member declarations.
2683 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2684 assert(isa<UsingShadowDecl>(FoundDecl));
2685 QualType URecordType = Context.getTypeDeclType(
2686 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2687
2688 // We only need to do this if the naming-class to declaring-class
2689 // conversion is non-trivial.
2690 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
Richard Smith0f59cb32015-12-18 21:45:41 +00002691 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002692 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002693 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002694 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002695 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002696
John McCall16df1e52010-03-30 21:47:33 +00002697 QualType UType = URecordType;
2698 if (PointerConversions)
2699 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002700 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002701 VK, &BasePath).get();
John McCall16df1e52010-03-30 21:47:33 +00002702 FromType = UType;
2703 FromRecordType = URecordType;
2704 }
2705
2706 // We don't do access control for the conversion from the
2707 // declaring class to the true declaring class.
2708 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002709 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002710
John McCallcf142162010-08-07 06:22:56 +00002711 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002712 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2713 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002714 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002715 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002716
John Wiegley01296292011-04-08 18:41:53 +00002717 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2718 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002719}
Douglas Gregor3256d042009-06-30 15:47:41 +00002720
John McCalle66edc12009-11-24 19:00:30 +00002721bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002722 const LookupResult &R,
2723 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002724 // Only when used directly as the postfix-expression of a call.
2725 if (!HasTrailingLParen)
2726 return false;
2727
2728 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002729 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002730 return false;
2731
2732 // Only in C++ or ObjC++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002733 if (!getLangOpts().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002734 return false;
2735
2736 // Turn off ADL when we find certain kinds of declarations during
2737 // normal lookup:
Craig Topperdfe29ae2015-12-21 06:35:56 +00002738 for (NamedDecl *D : R) {
John McCalld14a8642009-11-21 08:51:07 +00002739 // C++0x [basic.lookup.argdep]p3:
2740 // -- a declaration of a class member
2741 // Since using decls preserve this property, we check this on the
2742 // original decl.
John McCall57500772009-12-16 12:17:52 +00002743 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002744 return false;
2745
2746 // C++0x [basic.lookup.argdep]p3:
2747 // -- a block-scope function declaration that is not a
2748 // using-declaration
2749 // NOTE: we also trigger this for function templates (in fact, we
2750 // don't check the decl type at all, since all other decl types
2751 // turn off ADL anyway).
2752 if (isa<UsingShadowDecl>(D))
2753 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Richard Smith541b38b2013-09-20 01:15:31 +00002754 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
John McCalld14a8642009-11-21 08:51:07 +00002755 return false;
2756
2757 // C++0x [basic.lookup.argdep]p3:
2758 // -- a declaration that is neither a function or a function
2759 // template
2760 // And also for builtin functions.
2761 if (isa<FunctionDecl>(D)) {
2762 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2763
2764 // But also builtin functions.
2765 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2766 return false;
2767 } else if (!isa<FunctionTemplateDecl>(D))
2768 return false;
2769 }
2770
2771 return true;
2772}
2773
2774
John McCalld14a8642009-11-21 08:51:07 +00002775/// Diagnoses obvious problems with the use of the given declaration
2776/// as an expression. This is only actually called for lookups that
2777/// were not overloaded, and it doesn't promise that the declaration
2778/// will in fact be used.
2779static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith1cf45412017-01-04 23:14:16 +00002780 if (D->isInvalidDecl())
2781 return true;
2782
Richard Smithdda56e42011-04-15 14:24:37 +00002783 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002784 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2785 return true;
2786 }
2787
2788 if (isa<ObjCInterfaceDecl>(D)) {
2789 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2790 return true;
2791 }
2792
2793 if (isa<NamespaceDecl>(D)) {
2794 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2795 return true;
2796 }
2797
2798 return false;
2799}
2800
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00002801ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2802 LookupResult &R, bool NeedsADL,
2803 bool AcceptInvalidDecl) {
John McCall3a60c872009-12-08 22:45:53 +00002804 // If this is a single, fully-resolved result and we don't need ADL,
2805 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002806 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Daniel Jasper689ae012013-03-22 10:01:35 +00002807 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00002808 R.getRepresentativeDecl(), nullptr,
2809 AcceptInvalidDecl);
John McCalld14a8642009-11-21 08:51:07 +00002810
2811 // We only need to check the declaration if there's exactly one
2812 // result, because in the overloaded case the results can only be
2813 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002814 if (R.isSingleResult() &&
2815 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002816 return ExprError();
2817
John McCall58cc69d2010-01-27 01:50:18 +00002818 // Otherwise, just build an unresolved lookup expression. Suppress
2819 // any lookup-related diagnostics; we'll hash these out later, when
2820 // we've picked a target.
2821 R.suppressDiagnostics();
2822
John McCalld14a8642009-11-21 08:51:07 +00002823 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002824 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002825 SS.getWithLocInContext(Context),
2826 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002827 NeedsADL, R.isOverloadedResult(),
2828 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002829
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002830 return ULE;
John McCalld14a8642009-11-21 08:51:07 +00002831}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002832
Richard Smith1879f102016-08-15 02:34:23 +00002833static void
2834diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2835 ValueDecl *var, DeclContext *DC);
2836
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();
Richard Smith84a0b6d2016-10-18 23:39:12 +00002889 if (auto *FPT = type->getAs<FunctionProtoType>()) {
2890 // C++ [except.spec]p17:
2891 // An exception-specification is considered to be needed when:
2892 // - in an expression, the function is the unique lookup result or
2893 // the selected member of a set of overloaded functions.
2894 ResolveExceptionSpec(Loc, FPT);
2895 type = VD->getType();
2896 }
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002897 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002898
2899 switch (D->getKind()) {
2900 // Ignore all the non-ValueDecl kinds.
2901#define ABSTRACT_DECL(kind)
2902#define VALUE(type, base)
2903#define DECL(type, base) \
2904 case Decl::type:
2905#include "clang/AST/DeclNodes.inc"
2906 llvm_unreachable("invalid value decl kind");
John McCallf4cd4f92011-02-09 01:13:10 +00002907
2908 // These shouldn't make it here.
2909 case Decl::ObjCAtDefsField:
2910 case Decl::ObjCIvar:
2911 llvm_unreachable("forming non-member reference to ivar?");
John McCallf4cd4f92011-02-09 01:13:10 +00002912
2913 // Enum constants are always r-values and never references.
2914 // Unresolved using declarations are dependent.
2915 case Decl::EnumConstant:
2916 case Decl::UnresolvedUsingValue:
Alexey Bataevc5b1d322016-03-04 09:22:22 +00002917 case Decl::OMPDeclareReduction:
John McCallf4cd4f92011-02-09 01:13:10 +00002918 valueKind = VK_RValue;
2919 break;
2920
2921 // Fields and indirect fields that got here must be for
2922 // pointer-to-member expressions; we just call them l-values for
2923 // internal consistency, because this subexpression doesn't really
2924 // exist in the high-level semantics.
2925 case Decl::Field:
2926 case Decl::IndirectField:
David Blaikiebbafb8a2012-03-11 07:00:24 +00002927 assert(getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002928 "building reference to field in C?");
2929
2930 // These can't have reference type in well-formed programs, but
2931 // for internal consistency we do this anyway.
2932 type = type.getNonReferenceType();
2933 valueKind = VK_LValue;
2934 break;
2935
2936 // Non-type template parameters are either l-values or r-values
2937 // depending on the type.
2938 case Decl::NonTypeTemplateParm: {
2939 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2940 type = reftype->getPointeeType();
2941 valueKind = VK_LValue; // even if the parameter is an r-value reference
2942 break;
2943 }
2944
2945 // For non-references, we need to strip qualifiers just in case
2946 // the template parameter was declared as 'const int' or whatever.
2947 valueKind = VK_RValue;
2948 type = type.getUnqualifiedType();
2949 break;
2950 }
2951
2952 case Decl::Var:
Larisse Voufo39a1e502013-08-06 01:03:05 +00002953 case Decl::VarTemplateSpecialization:
2954 case Decl::VarTemplatePartialSpecialization:
Richard Smithbdb84f32016-07-22 23:36:59 +00002955 case Decl::Decomposition:
Alexey Bataev4244be22016-02-11 05:35:55 +00002956 case Decl::OMPCapturedExpr:
John McCallf4cd4f92011-02-09 01:13:10 +00002957 // In C, "extern void blah;" is valid and is an r-value.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002958 if (!getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002959 !type.hasQualifiers() &&
2960 type->isVoidType()) {
2961 valueKind = VK_RValue;
2962 break;
2963 }
2964 // fallthrough
2965
2966 case Decl::ImplicitParam:
Douglas Gregor812d8f62012-02-18 05:51:20 +00002967 case Decl::ParmVar: {
John McCallf4cd4f92011-02-09 01:13:10 +00002968 // These are always l-values.
2969 valueKind = VK_LValue;
2970 type = type.getNonReferenceType();
Eli Friedman9bb33f52012-02-03 02:04:35 +00002971
Douglas Gregor812d8f62012-02-18 05:51:20 +00002972 // FIXME: Does the addition of const really only apply in
2973 // potentially-evaluated contexts? Since the variable isn't actually
2974 // captured in an unevaluated context, it seems that the answer is no.
David Blaikie131fcb42012-08-06 22:47:24 +00002975 if (!isUnevaluatedContext()) {
Douglas Gregor812d8f62012-02-18 05:51:20 +00002976 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2977 if (!CapturedType.isNull())
2978 type = CapturedType;
2979 }
2980
John McCallf4cd4f92011-02-09 01:13:10 +00002981 break;
Douglas Gregor812d8f62012-02-18 05:51:20 +00002982 }
Richard Smith7873de02016-08-11 22:25:46 +00002983
2984 case Decl::Binding: {
2985 // These are always lvalues.
2986 valueKind = VK_LValue;
2987 type = type.getNonReferenceType();
Richard Smith1879f102016-08-15 02:34:23 +00002988 // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2989 // decides how that's supposed to work.
2990 auto *BD = cast<BindingDecl>(VD);
2991 if (BD->getDeclContext()->isFunctionOrMethod() &&
2992 BD->getDeclContext() != CurContext)
2993 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
Richard Smith7873de02016-08-11 22:25:46 +00002994 break;
2995 }
Douglas Gregor812d8f62012-02-18 05:51:20 +00002996
John McCallf4cd4f92011-02-09 01:13:10 +00002997 case Decl::Function: {
Eli Friedman34866c72012-08-31 00:14:07 +00002998 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2999 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3000 type = Context.BuiltinFnTy;
3001 valueKind = VK_RValue;
3002 break;
3003 }
3004 }
3005
John McCall2979fe02011-04-12 00:42:48 +00003006 const FunctionType *fty = type->castAs<FunctionType>();
3007
3008 // If we're referring to a function with an __unknown_anytype
3009 // result type, make the entire expression __unknown_anytype.
Alp Toker314cc812014-01-25 16:55:45 +00003010 if (fty->getReturnType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003011 type = Context.UnknownAnyTy;
3012 valueKind = VK_RValue;
3013 break;
3014 }
3015
John McCallf4cd4f92011-02-09 01:13:10 +00003016 // Functions are l-values in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003017 if (getLangOpts().CPlusPlus) {
John McCallf4cd4f92011-02-09 01:13:10 +00003018 valueKind = VK_LValue;
3019 break;
3020 }
3021
3022 // C99 DR 316 says that, if a function type comes from a
3023 // function definition (without a prototype), that type is only
3024 // used for checking compatibility. Therefore, when referencing
3025 // the function, we pretend that we don't have the full function
3026 // type.
John McCall2979fe02011-04-12 00:42:48 +00003027 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3028 isa<FunctionProtoType>(fty))
Alp Toker314cc812014-01-25 16:55:45 +00003029 type = Context.getFunctionNoProtoType(fty->getReturnType(),
John McCall2979fe02011-04-12 00:42:48 +00003030 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00003031
3032 // Functions are r-values in C.
3033 valueKind = VK_RValue;
3034 break;
3035 }
3036
John McCall5e77d762013-04-16 07:28:30 +00003037 case Decl::MSProperty:
3038 valueKind = VK_LValue;
3039 break;
3040
John McCallf4cd4f92011-02-09 01:13:10 +00003041 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00003042 // If we're referring to a method with an __unknown_anytype
3043 // result type, make the entire expression __unknown_anytype.
3044 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00003045 if (const FunctionProtoType *proto
3046 = dyn_cast<FunctionProtoType>(VD->getType()))
Alp Toker314cc812014-01-25 16:55:45 +00003047 if (proto->getReturnType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003048 type = Context.UnknownAnyTy;
3049 valueKind = VK_RValue;
3050 break;
3051 }
3052
John McCallf4cd4f92011-02-09 01:13:10 +00003053 // C++ methods are l-values if static, r-values if non-static.
3054 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3055 valueKind = VK_LValue;
3056 break;
3057 }
3058 // fallthrough
3059
3060 case Decl::CXXConversion:
3061 case Decl::CXXDestructor:
3062 case Decl::CXXConstructor:
3063 valueKind = VK_RValue;
3064 break;
3065 }
3066
Larisse Voufo39a1e502013-08-06 01:03:05 +00003067 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3068 TemplateArgs);
John McCallf4cd4f92011-02-09 01:13:10 +00003069 }
Chris Lattner17ed4872006-11-20 04:58:19 +00003070}
Chris Lattnere168f762006-11-10 05:29:30 +00003071
Alexey Bataevec474782014-10-09 08:45:04 +00003072static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3073 SmallString<32> &Target) {
3074 Target.resize(CharByteWidth * (Source.size() + 1));
3075 char *ResultPtr = &Target[0];
Justin Lebar90910552016-09-30 00:38:45 +00003076 const llvm::UTF8 *ErrorPtr;
3077 bool success =
3078 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
Alexey Bataevec474782014-10-09 08:45:04 +00003079 (void)success;
3080 assert(success);
3081 Target.resize(ResultPtr - &Target[0]);
3082}
3083
Wei Panc354d212013-09-16 13:57:27 +00003084ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3085 PredefinedExpr::IdentType IT) {
3086 // Pick the current block, lambda, captured statement or function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003087 Decl *currentDecl = nullptr;
Benjamin Kramer90f54222013-08-21 11:45:27 +00003088 if (const BlockScopeInfo *BSI = getCurBlock())
3089 currentDecl = BSI->TheDecl;
3090 else if (const LambdaScopeInfo *LSI = getCurLambda())
3091 currentDecl = LSI->CallOperator;
Wei Pan8d6b19a2013-08-26 14:27:34 +00003092 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3093 currentDecl = CSI->TheCapturedDecl;
Benjamin Kramer90f54222013-08-21 11:45:27 +00003094 else
3095 currentDecl = getCurFunctionOrMethodDecl();
Benjamin Kramer6928cf72012-12-06 15:42:21 +00003096
Anders Carlsson2fb08242009-09-08 18:24:21 +00003097 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00003098 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00003099 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00003100 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003101
Anders Carlsson0b209a82009-09-11 01:22:35 +00003102 QualType ResTy;
Alexey Bataevec474782014-10-09 08:45:04 +00003103 StringLiteral *SL = nullptr;
Wei Panc354d212013-09-16 13:57:27 +00003104 if (cast<DeclContext>(currentDecl)->isDependentContext())
Anders Carlsson0b209a82009-09-11 01:22:35 +00003105 ResTy = Context.DependentTy;
Wei Panc354d212013-09-16 13:57:27 +00003106 else {
3107 // Pre-defined identifiers are of type char[x], where x is the length of
3108 // the string.
Alexey Bataevec474782014-10-09 08:45:04 +00003109 auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3110 unsigned Length = Str.length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003111
Anders Carlsson0b209a82009-09-11 01:22:35 +00003112 llvm::APInt LengthI(32, Length + 1);
Alexey Bataevec474782014-10-09 08:45:04 +00003113 if (IT == PredefinedExpr::LFunction) {
Hans Wennborg0d81e012013-05-10 10:08:40 +00003114 ResTy = Context.WideCharTy.withConst();
Alexey Bataevec474782014-10-09 08:45:04 +00003115 SmallString<32> RawChars;
3116 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3117 Str, RawChars);
3118 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3119 /*IndexTypeQuals*/ 0);
3120 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3121 /*Pascal*/ false, ResTy, Loc);
3122 } else {
Nico Weber3a691a32012-06-23 02:07:59 +00003123 ResTy = Context.CharTy.withConst();
Alexey Bataevec474782014-10-09 08:45:04 +00003124 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3125 /*IndexTypeQuals*/ 0);
3126 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3127 /*Pascal*/ false, ResTy, Loc);
3128 }
Anders Carlsson0b209a82009-09-11 01:22:35 +00003129 }
Wei Panc354d212013-09-16 13:57:27 +00003130
Alexey Bataevec474782014-10-09 08:45:04 +00003131 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
Chris Lattnere168f762006-11-10 05:29:30 +00003132}
3133
Wei Panc354d212013-09-16 13:57:27 +00003134ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3135 PredefinedExpr::IdentType IT;
3136
3137 switch (Kind) {
3138 default: llvm_unreachable("Unknown simple primary expr!");
3139 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3140 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
David Majnemerbed356a2013-11-06 23:31:56 +00003141 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
Reid Kleckner52eddda2014-04-08 18:13:24 +00003142 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
Wei Panc354d212013-09-16 13:57:27 +00003143 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3144 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3145 }
3146
3147 return BuildPredefinedExpr(Loc, IT);
3148}
3149
Richard Smithbcc22fc2012-03-09 08:00:36 +00003150ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003151 SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00003152 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003153 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00003154 if (Invalid)
3155 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003156
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00003157 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00003158 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00003159 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00003160 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00003161
Chris Lattnerc3847ba2009-12-30 21:19:39 +00003162 QualType Ty;
Seth Cantrell02f86052012-01-18 12:27:06 +00003163 if (Literal.isWide())
Hans Wennborg0d81e012013-05-10 10:08:40 +00003164 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00003165 else if (Literal.isUTF16())
Seth Cantrell02f86052012-01-18 12:27:06 +00003166 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregorfb65e592011-07-27 05:40:30 +00003167 else if (Literal.isUTF32())
Seth Cantrell02f86052012-01-18 12:27:06 +00003168 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003169 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell02f86052012-01-18 12:27:06 +00003170 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00003171 else
3172 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00003173
Douglas Gregorfb65e592011-07-27 05:40:30 +00003174 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3175 if (Literal.isWide())
3176 Kind = CharacterLiteral::Wide;
3177 else if (Literal.isUTF16())
3178 Kind = CharacterLiteral::UTF16;
3179 else if (Literal.isUTF32())
3180 Kind = CharacterLiteral::UTF32;
Aaron Ballman9a17c852016-01-07 20:59:26 +00003181 else if (Literal.isUTF8())
3182 Kind = CharacterLiteral::UTF8;
Douglas Gregorfb65e592011-07-27 05:40:30 +00003183
Richard Smith75b67d62012-03-08 01:34:56 +00003184 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3185 Tok.getLocation());
3186
3187 if (Literal.getUDSuffix().empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003188 return Lit;
Richard Smith75b67d62012-03-08 01:34:56 +00003189
3190 // We're building a user-defined literal.
3191 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3192 SourceLocation UDSuffixLoc =
3193 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3194
Richard Smithbcc22fc2012-03-09 08:00:36 +00003195 // Make sure we're allowed user-defined literals here.
3196 if (!UDLScope)
3197 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3198
Richard Smith75b67d62012-03-08 01:34:56 +00003199 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3200 // operator "" X (ch)
Richard Smithbcc22fc2012-03-09 08:00:36 +00003201 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003202 Lit, Tok.getLocation());
Steve Naroffae4143e2007-04-26 20:39:23 +00003203}
3204
Ted Kremeneke65b0862012-03-06 20:05:56 +00003205ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3206 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003207 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3208 Context.IntTy, Loc);
Ted Kremeneke65b0862012-03-06 20:05:56 +00003209}
3210
Richard Smith39570d002012-03-08 08:45:32 +00003211static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3212 QualType Ty, SourceLocation Loc) {
3213 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3214
3215 using llvm::APFloat;
3216 APFloat Val(Format);
3217
3218 APFloat::opStatus result = Literal.GetFloatValue(Val);
3219
3220 // Overflow is always an error, but underflow is only an error if
3221 // we underflowed to zero (APFloat reports denormals as underflow).
3222 if ((result & APFloat::opOverflow) ||
3223 ((result & APFloat::opUnderflow) && Val.isZero())) {
3224 unsigned diagnostic;
3225 SmallString<20> buffer;
3226 if (result & APFloat::opOverflow) {
3227 diagnostic = diag::warn_float_overflow;
3228 APFloat::getLargest(Format).toString(buffer);
3229 } else {
3230 diagnostic = diag::warn_float_underflow;
3231 APFloat::getSmallest(Format).toString(buffer);
3232 }
3233
3234 S.Diag(Loc, diagnostic)
3235 << Ty
3236 << StringRef(buffer.data(), buffer.size());
3237 }
3238
3239 bool isExact = (result == APFloat::opOK);
3240 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3241}
3242
Tyler Nowickic724a83e2014-10-12 20:46:07 +00003243bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3244 assert(E && "Invalid expression");
3245
3246 if (E->isValueDependent())
3247 return false;
3248
3249 QualType QT = E->getType();
3250 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3251 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3252 return true;
3253 }
3254
3255 llvm::APSInt ValueAPS;
3256 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3257
3258 if (R.isInvalid())
3259 return true;
3260
3261 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3262 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3263 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3264 << ValueAPS.toString(10) << ValueIsPositive;
3265 return true;
3266 }
3267
3268 return false;
3269}
3270
Richard Smithbcc22fc2012-03-09 08:00:36 +00003271ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00003272 // Fast path for a single digit (which is quite common). A single digit
Richard Smithbcc22fc2012-03-09 08:00:36 +00003273 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Steve Narofff2fb89e2007-03-13 20:29:44 +00003274 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00003275 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremeneke65b0862012-03-06 20:05:56 +00003276 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Steve Narofff2fb89e2007-03-13 20:29:44 +00003277 }
Ted Kremeneke9814182009-01-13 23:19:12 +00003278
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00003279 SmallString<128> SpellingBuffer;
3280 // NumericLiteralParser wants to overread by one character. Add padding to
3281 // the buffer in case the token is copied to the buffer. If getSpelling()
3282 // returns a StringRef to the memory buffer, it should have a null char at
3283 // the EOF, so it is also safe.
3284 SpellingBuffer.resize(Tok.getLength() + 1);
Sebastian Redlffbcf962009-01-18 18:53:16 +00003285
Chris Lattner67ca9252007-05-21 01:08:44 +00003286 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00003287 bool Invalid = false;
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00003288 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00003289 if (Invalid)
3290 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003291
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00003292 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00003293 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00003294 return ExprError();
3295
Richard Smith39570d002012-03-08 08:45:32 +00003296 if (Literal.hasUDSuffix()) {
3297 // We're building a user-defined literal.
3298 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3299 SourceLocation UDSuffixLoc =
3300 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3301
Richard Smithbcc22fc2012-03-09 08:00:36 +00003302 // Make sure we're allowed user-defined literals here.
3303 if (!UDLScope)
3304 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smith39570d002012-03-08 08:45:32 +00003305
Richard Smithbcc22fc2012-03-09 08:00:36 +00003306 QualType CookedTy;
Richard Smith39570d002012-03-08 08:45:32 +00003307 if (Literal.isFloatingLiteral()) {
3308 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3309 // long double, the literal is treated as a call of the form
3310 // operator "" X (f L)
Richard Smithbcc22fc2012-03-09 08:00:36 +00003311 CookedTy = Context.LongDoubleTy;
Richard Smith39570d002012-03-08 08:45:32 +00003312 } else {
3313 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3314 // unsigned long long, the literal is treated as a call of the form
3315 // operator "" X (n ULL)
Richard Smithbcc22fc2012-03-09 08:00:36 +00003316 CookedTy = Context.UnsignedLongLongTy;
Richard Smith39570d002012-03-08 08:45:32 +00003317 }
3318
Richard Smithbcc22fc2012-03-09 08:00:36 +00003319 DeclarationName OpName =
3320 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3321 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3322 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3323
Richard Smithb8b41d32013-10-07 19:57:58 +00003324 SourceLocation TokLoc = Tok.getLocation();
3325
Richard Smithbcc22fc2012-03-09 08:00:36 +00003326 // Perform literal operator lookup to determine if we're building a raw
3327 // literal or a cooked one.
3328 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003329 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
Richard Smithb8b41d32013-10-07 19:57:58 +00003330 /*AllowRaw*/true, /*AllowTemplate*/true,
3331 /*AllowStringTemplate*/false)) {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003332 case LOLR_Error:
3333 return ExprError();
3334
3335 case LOLR_Cooked: {
3336 Expr *Lit;
3337 if (Literal.isFloatingLiteral()) {
3338 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3339 } else {
3340 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3341 if (Literal.GetIntegerValue(ResultVal))
Aaron Ballman31f42312014-07-24 14:51:23 +00003342 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3343 << /* Unsigned */ 1;
Richard Smithbcc22fc2012-03-09 08:00:36 +00003344 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3345 Tok.getLocation());
3346 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003347 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
Richard Smithbcc22fc2012-03-09 08:00:36 +00003348 }
3349
3350 case LOLR_Raw: {
3351 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3352 // literal is treated as a call of the form
3353 // operator "" X ("n")
Richard Smithbcc22fc2012-03-09 08:00:36 +00003354 unsigned Length = Literal.getUDSuffixOffset();
3355 QualType StrTy = Context.getConstantArrayType(
Richard Smithbe8229c2013-01-23 23:38:20 +00003356 Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
Richard Smithbcc22fc2012-03-09 08:00:36 +00003357 ArrayType::Normal, 0);
3358 Expr *Lit = StringLiteral::Create(
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00003359 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
Richard Smithbcc22fc2012-03-09 08:00:36 +00003360 /*Pascal*/false, StrTy, &TokLoc, 1);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003361 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
Richard Smithbcc22fc2012-03-09 08:00:36 +00003362 }
3363
Richard Smithb8b41d32013-10-07 19:57:58 +00003364 case LOLR_Template: {
Richard Smithbcc22fc2012-03-09 08:00:36 +00003365 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3366 // template), L is treated as a call fo the form
3367 // operator "" X <'c1', 'c2', ... 'ck'>()
3368 // where n is the source character sequence c1 c2 ... ck.
3369 TemplateArgumentListInfo ExplicitArgs;
3370 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3371 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3372 llvm::APSInt Value(CharBits, CharIsUnsigned);
3373 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00003374 Value = TokSpelling[I];
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003375 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smithbcc22fc2012-03-09 08:00:36 +00003376 TemplateArgumentLocInfo ArgInfo;
3377 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3378 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003379 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003380 &ExplicitArgs);
Richard Smithbcc22fc2012-03-09 08:00:36 +00003381 }
Richard Smithb8b41d32013-10-07 19:57:58 +00003382 case LOLR_StringTemplate:
3383 llvm_unreachable("unexpected literal operator lookup result");
3384 }
Richard Smith39570d002012-03-08 08:45:32 +00003385 }
3386
Chris Lattner1c20a172007-08-26 03:42:43 +00003387 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00003388
Chris Lattner1c20a172007-08-26 03:42:43 +00003389 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00003390 QualType Ty;
Anastasia Stulova5c1a2c52016-02-17 11:34:37 +00003391 if (Literal.isHalf){
Yaxun Liu5b746652016-12-18 05:18:55 +00003392 if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
Anastasia Stulova5c1a2c52016-02-17 11:34:37 +00003393 Ty = Context.HalfTy;
3394 else {
3395 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3396 return ExprError();
3397 }
3398 } else if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00003399 Ty = Context.FloatTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003400 else if (Literal.isLong)
Nemanja Ivanovicd7d45bf2016-04-15 18:04:13 +00003401 Ty = Context.LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00003402 else if (Literal.isFloat128)
3403 Ty = Context.Float128Ty;
3404 else
3405 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00003406
Richard Smith39570d002012-03-08 08:45:32 +00003407 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00003408
Peter Collingbournec77f85b2011-03-11 19:24:59 +00003409 if (Ty == Context.DoubleTy) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003410 if (getLangOpts().SinglePrecisionConstants) {
Neil Hickey88c0fac2016-12-13 16:22:50 +00003411 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3412 if (BTy->getKind() != BuiltinType::Float) {
3413 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3414 }
Fraser Cormackcc6e8942015-01-30 10:51:46 +00003415 } else if (getLangOpts().OpenCL &&
Yaxun Liu5b746652016-12-18 05:18:55 +00003416 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
Neil Hickey88c0fac2016-12-13 16:22:50 +00003417 // Impose single-precision float type when cl_khr_fp64 is not enabled.
Peter Collingbournec77f85b2011-03-11 19:24:59 +00003418 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003419 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00003420 }
3421 }
Chris Lattner1c20a172007-08-26 03:42:43 +00003422 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00003423 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00003424 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003425 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00003426
Dmitri Gribenko1cd23052012-09-24 18:19:21 +00003427 // 'long long' is a C99 or C++11 feature.
3428 if (!getLangOpts().C99 && Literal.isLongLong) {
3429 if (getLangOpts().CPlusPlus)
3430 Diag(Tok.getLocation(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003431 getLangOpts().CPlusPlus11 ?
Dmitri Gribenko1cd23052012-09-24 18:19:21 +00003432 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3433 else
3434 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3435 }
Neil Boothac582c52007-08-29 22:00:19 +00003436
Chris Lattner67ca9252007-05-21 01:08:44 +00003437 // Get the value in the widest-possible width.
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00003438 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00003439 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00003440
Chris Lattner67ca9252007-05-21 01:08:44 +00003441 if (Literal.GetIntegerValue(ResultVal)) {
Eli Friedman088d39a2013-07-23 00:25:18 +00003442 // If this value didn't fit into uintmax_t, error and force to ull.
Aaron Ballman31f42312014-07-24 14:51:23 +00003443 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3444 << /* Unsigned */ 1;
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003445 Ty = Context.UnsignedLongLongTy;
3446 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00003447 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00003448 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00003449 // If this value fits into a ULL, try to figure out what else it fits into
3450 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00003451
Chris Lattner67ca9252007-05-21 01:08:44 +00003452 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3453 // be an unsigned int.
3454 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3455
3456 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00003457 unsigned Width = 0;
David Majnemer65a407c2014-06-21 18:46:07 +00003458
3459 // Microsoft specific integer suffixes are explicitly sized.
3460 if (Literal.MicrosoftInteger) {
David Majnemer5055dfc2015-07-26 09:02:26 +00003461 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
David Majnemerbe09e8e2015-03-06 18:04:22 +00003462 Width = 8;
3463 Ty = Context.CharTy;
David Majnemer65a407c2014-06-21 18:46:07 +00003464 } else {
3465 Width = Literal.MicrosoftInteger;
3466 Ty = Context.getIntTypeForBitwidth(Width,
3467 /*Signed=*/!Literal.isUnsigned);
3468 }
3469 }
3470
3471 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
Chris Lattner7b939cf2007-08-23 21:58:08 +00003472 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00003473 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003474
Chris Lattner67ca9252007-05-21 01:08:44 +00003475 // Does it fit in a unsigned int?
3476 if (ResultVal.isIntN(IntSize)) {
3477 // Does it fit in a signed int?
3478 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003479 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00003480 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003481 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00003482 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00003483 }
Chris Lattner67ca9252007-05-21 01:08:44 +00003484 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003485
Chris Lattner67ca9252007-05-21 01:08:44 +00003486 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003487 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003488 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003489
Chris Lattner67ca9252007-05-21 01:08:44 +00003490 // Does it fit in a unsigned long?
3491 if (ResultVal.isIntN(LongSize)) {
3492 // Does it fit in a signed long?
3493 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003494 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00003495 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003496 Ty = Context.UnsignedLongTy;
Hubert Tong13234ae2015-06-08 21:59:59 +00003497 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3498 // is compatible.
3499 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3500 const unsigned LongLongSize =
3501 Context.getTargetInfo().getLongLongWidth();
3502 Diag(Tok.getLocation(),
3503 getLangOpts().CPlusPlus
3504 ? Literal.isLong
3505 ? diag::warn_old_implicitly_unsigned_long_cxx
3506 : /*C++98 UB*/ diag::
3507 ext_old_implicitly_unsigned_long_cxx
3508 : diag::warn_old_implicitly_unsigned_long)
3509 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3510 : /*will be ill-formed*/ 1);
3511 Ty = Context.UnsignedLongTy;
3512 }
Chris Lattner55258cf2008-05-09 05:59:00 +00003513 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00003514 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003515 }
3516
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00003517 // Check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003518 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003519 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003520
Chris Lattner67ca9252007-05-21 01:08:44 +00003521 // Does it fit in a unsigned long long?
3522 if (ResultVal.isIntN(LongLongSize)) {
3523 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00003524 // To be compatible with MSVC, hex integer literals ending with the
3525 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00003526 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
Reid Klecknerd2c0c252016-10-04 15:57:49 +00003527 (getLangOpts().MSVCCompat && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003528 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00003529 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003530 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00003531 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00003532 }
3533 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003534
Chris Lattner67ca9252007-05-21 01:08:44 +00003535 // If we still couldn't decide a type, we probably have something that
3536 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003537 if (Ty.isNull()) {
Aaron Ballman31f42312014-07-24 14:51:23 +00003538 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003539 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00003540 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00003541 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003542
Chris Lattner55258cf2008-05-09 05:59:00 +00003543 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00003544 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00003545 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003546 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00003547 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003548
Chris Lattner1c20a172007-08-26 03:42:43 +00003549 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3550 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00003551 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00003552 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00003553
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003554 return Res;
Chris Lattnere168f762006-11-10 05:29:30 +00003555}
3556
Richard Trieuba63ce62011-09-09 01:45:06 +00003557ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003558 assert(E && "ActOnParenExpr() missing expr");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003559 return new (Context) ParenExpr(L, R, E);
Chris Lattnere168f762006-11-10 05:29:30 +00003560}
3561
Chandler Carruth62da79c2011-05-26 08:53:12 +00003562static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3563 SourceLocation Loc,
3564 SourceRange ArgRange) {
3565 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3566 // scalar or vector data type argument..."
3567 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3568 // type (C99 6.2.5p18) or void.
3569 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3570 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3571 << T << ArgRange;
3572 return true;
3573 }
3574
3575 assert((T->isVoidType() || !T->isIncompleteType()) &&
3576 "Scalar types should always be complete");
3577 return false;
3578}
3579
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003580static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3581 SourceLocation Loc,
3582 SourceRange ArgRange,
3583 UnaryExprOrTypeTrait TraitKind) {
Eli Friedman4e28b262013-08-13 22:26:42 +00003584 // Invalid types must be hard errors for SFINAE in C++.
3585 if (S.LangOpts.CPlusPlus)
3586 return true;
3587
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003588 // C99 6.5.3.4p1:
Richard Smith9cf21ae2013-03-18 23:37:25 +00003589 if (T->isFunctionType() &&
3590 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3591 // sizeof(function)/alignof(function) is allowed as an extension.
3592 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3593 << TraitKind << ArgRange;
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003594 return false;
3595 }
3596
Joey Gouly4ba0f1e2013-12-31 15:47:49 +00003597 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3598 // this is an error (OpenCL v1.1 s6.3.k)
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003599 if (T->isVoidType()) {
Joey Gouly4ba0f1e2013-12-31 15:47:49 +00003600 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3601 : diag::ext_sizeof_alignof_void_type;
3602 S.Diag(Loc, DiagID) << TraitKind << ArgRange;
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003603 return false;
3604 }
3605
3606 return true;
3607}
3608
3609static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3610 SourceLocation Loc,
3611 SourceRange ArgRange,
3612 UnaryExprOrTypeTrait TraitKind) {
John McCallf2538342012-07-31 05:14:30 +00003613 // Reject sizeof(interface) and sizeof(interface<proto>) if the
3614 // runtime doesn't allow it.
3615 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003616 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3617 << T << (TraitKind == UETT_SizeOf)
3618 << ArgRange;
3619 return true;
3620 }
3621
3622 return false;
3623}
3624
Benjamin Kramer054faa52013-03-29 21:43:21 +00003625/// \brief Check whether E is a pointer from a decayed array type (the decayed
3626/// pointer type is equal to T) and emit a warning if it is.
3627static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3628 Expr *E) {
3629 // Don't warn if the operation changed the type.
3630 if (T != E->getType())
3631 return;
3632
3633 // Now look for array decays.
3634 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3635 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3636 return;
3637
3638 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3639 << ICE->getType()
3640 << ICE->getSubExpr()->getType();
3641}
3642
Alp Toker95e7ff22014-01-01 05:57:51 +00003643/// \brief Check the constraints on expression operands to unary type expression
Chandler Carruth14502c22011-05-26 08:53:10 +00003644/// and type traits.
3645///
Chandler Carruth7c430c02011-05-27 01:33:31 +00003646/// Completes any types necessary and validates the constraints on the operand
3647/// expression. The logic mostly mirrors the type-based overload, but may modify
3648/// the expression as it completes the type for that expression through template
3649/// instantiation, etc.
Richard Trieuba63ce62011-09-09 01:45:06 +00003650bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth14502c22011-05-26 08:53:10 +00003651 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003652 QualType ExprTy = E->getType();
John McCall768439e2013-05-06 07:40:34 +00003653 assert(!ExprTy->isReferenceType());
Chandler Carruth7c430c02011-05-27 01:33:31 +00003654
3655 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00003656 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3657 E->getSourceRange());
Chandler Carruth7c430c02011-05-27 01:33:31 +00003658
3659 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00003660 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3661 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00003662 return false;
3663
Richard Smithf6d70302014-06-10 23:34:28 +00003664 // 'alignof' applied to an expression only requires the base element type of
3665 // the expression to be complete. 'sizeof' requires the expression's type to
3666 // be complete (and will attempt to complete it if it's an array of unknown
3667 // bound).
3668 if (ExprKind == UETT_AlignOf) {
3669 if (RequireCompleteType(E->getExprLoc(),
3670 Context.getBaseElementType(E->getType()),
3671 diag::err_sizeof_alignof_incomplete_type, ExprKind,
3672 E->getSourceRange()))
3673 return true;
3674 } else {
3675 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3676 ExprKind, E->getSourceRange()))
3677 return true;
3678 }
Chandler Carruth7c430c02011-05-27 01:33:31 +00003679
John McCall768439e2013-05-06 07:40:34 +00003680 // Completing the expression's type may have changed it.
Richard Trieuba63ce62011-09-09 01:45:06 +00003681 ExprTy = E->getType();
John McCall768439e2013-05-06 07:40:34 +00003682 assert(!ExprTy->isReferenceType());
Chandler Carruth7c430c02011-05-27 01:33:31 +00003683
Eli Friedman4e28b262013-08-13 22:26:42 +00003684 if (ExprTy->isFunctionType()) {
3685 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3686 << ExprKind << E->getSourceRange();
3687 return true;
3688 }
3689
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003690 // The operand for sizeof and alignof is in an unevaluated expression context,
3691 // so side effects could result in unintended consequences.
3692 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3693 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3694 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3695
Richard Trieuba63ce62011-09-09 01:45:06 +00003696 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3697 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00003698 return true;
3699
Nico Weber0870deb2011-06-15 02:47:03 +00003700 if (ExprKind == UETT_SizeOf) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003701 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Weber0870deb2011-06-15 02:47:03 +00003702 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3703 QualType OType = PVD->getOriginalType();
3704 QualType Type = PVD->getType();
3705 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003706 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Weber0870deb2011-06-15 02:47:03 +00003707 << Type << OType;
3708 Diag(PVD->getLocation(), diag::note_declared_at);
3709 }
3710 }
3711 }
Benjamin Kramer054faa52013-03-29 21:43:21 +00003712
3713 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3714 // decays into a pointer and returns an unintended result. This is most
3715 // likely a typo for "sizeof(array) op x".
3716 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3717 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3718 BO->getLHS());
3719 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3720 BO->getRHS());
3721 }
Nico Weber0870deb2011-06-15 02:47:03 +00003722 }
3723
Chandler Carruth7c430c02011-05-27 01:33:31 +00003724 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00003725}
3726
3727/// \brief Check the constraints on operands to unary expression and type
3728/// traits.
3729///
3730/// This will complete any types necessary, and validate the various constraints
3731/// on those operands.
3732///
Steve Naroff71b59a92007-06-04 22:22:31 +00003733/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00003734/// C99 6.3.2.1p[2-4] all state:
3735/// Except when it is the operand of the sizeof operator ...
3736///
3737/// C++ [expr.sizeof]p4
3738/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3739/// standard conversions are not applied to the operand of sizeof.
3740///
3741/// This policy is followed for all of the unary trait expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00003742bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00003743 SourceLocation OpLoc,
3744 SourceRange ExprRange,
3745 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003746 if (ExprType->isDependentType())
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003747 return false;
3748
Richard Smithc3fbf682014-06-10 21:11:26 +00003749 // C++ [expr.sizeof]p2:
3750 // When applied to a reference or a reference type, the result
3751 // is the size of the referenced type.
3752 // C++11 [expr.alignof]p3:
3753 // When alignof is applied to a reference type, the result
3754 // shall be the alignment of the referenced type.
Richard Trieuba63ce62011-09-09 01:45:06 +00003755 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3756 ExprType = Ref->getPointeeType();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003757
Richard Smithc3fbf682014-06-10 21:11:26 +00003758 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3759 // When alignof or _Alignof is applied to an array type, the result
3760 // is the alignment of the element type.
Alexey Bataev00396512015-07-02 03:40:19 +00003761 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
Richard Smithc3fbf682014-06-10 21:11:26 +00003762 ExprType = Context.getBaseElementType(ExprType);
3763
Chandler Carruth62da79c2011-05-26 08:53:12 +00003764 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00003765 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003766
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003767 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00003768 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003769 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00003770 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003771
Richard Trieuba63ce62011-09-09 01:45:06 +00003772 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003773 diag::err_sizeof_alignof_incomplete_type,
3774 ExprKind, ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00003775 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003776
Eli Friedman4e28b262013-08-13 22:26:42 +00003777 if (ExprType->isFunctionType()) {
3778 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3779 << ExprKind << ExprRange;
3780 return true;
3781 }
3782
Richard Trieuba63ce62011-09-09 01:45:06 +00003783 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003784 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00003785 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003786
Chris Lattner62975a72009-04-24 00:30:45 +00003787 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00003788}
3789
Chandler Carruth14502c22011-05-26 08:53:10 +00003790static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00003791 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003792
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003793 // Cannot know anything else if the expression is dependent.
3794 if (E->isTypeDependent())
3795 return false;
3796
John McCall768439e2013-05-06 07:40:34 +00003797 if (E->getObjectKind() == OK_BitField) {
Richard Smithe301ba22015-11-11 02:02:15 +00003798 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
Chandler Carruth14502c22011-05-26 08:53:10 +00003799 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003800 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00003801 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00003802
Craig Topperc3ec1492014-05-26 06:22:03 +00003803 ValueDecl *D = nullptr;
John McCall768439e2013-05-06 07:40:34 +00003804 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3805 D = DRE->getDecl();
3806 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3807 D = ME->getMemberDecl();
3808 }
3809
3810 // If it's a field, require the containing struct to have a
3811 // complete definition so that we can compute the layout.
3812 //
Richard Smithc3fbf682014-06-10 21:11:26 +00003813 // This can happen in C++11 onwards, either by naming the member
3814 // in a way that is not transformed into a member access expression
3815 // (in an unevaluated operand, for instance), or by naming the member
3816 // in a trailing-return-type.
John McCall768439e2013-05-06 07:40:34 +00003817 //
3818 // For the record, since __alignof__ on expressions is a GCC
3819 // extension, GCC seems to permit this but always gives the
3820 // nonsensical answer 0.
3821 //
3822 // We don't really need the layout here --- we could instead just
3823 // directly check for all the appropriate alignment-lowing
3824 // attributes --- but that would require duplicating a lot of
3825 // logic that just isn't worth duplicating for such a marginal
3826 // use-case.
3827 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3828 // Fast path this check, since we at least know the record has a
3829 // definition if we can find a member of it.
3830 if (!FD->getParent()->isCompleteDefinition()) {
3831 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3832 << E->getSourceRange();
3833 return true;
3834 }
3835
3836 // Otherwise, if it's a field, and the field doesn't have
3837 // reference type, then it must have a complete type (or be a
3838 // flexible array member, which we explicitly want to
3839 // white-list anyway), which makes the following checks trivial.
3840 if (!FD->getType()->isReferenceType())
Douglas Gregor71235ec2009-05-02 02:18:30 +00003841 return false;
John McCall768439e2013-05-06 07:40:34 +00003842 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00003843
Chandler Carruth14502c22011-05-26 08:53:10 +00003844 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003845}
3846
Chandler Carruth14502c22011-05-26 08:53:10 +00003847bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00003848 E = E->IgnoreParens();
3849
3850 // Cannot know anything else if the expression is dependent.
3851 if (E->isTypeDependent())
3852 return false;
3853
Chandler Carruth14502c22011-05-26 08:53:10 +00003854 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00003855}
3856
Alexey Bataev93a546a2016-01-21 12:54:48 +00003857static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3858 CapturingScopeInfo *CSI) {
3859 assert(T->isVariablyModifiedType());
3860 assert(CSI != nullptr);
3861
3862 // We're going to walk down into the type and look for VLA expressions.
3863 do {
3864 const Type *Ty = T.getTypePtr();
3865 switch (Ty->getTypeClass()) {
3866#define TYPE(Class, Base)
3867#define ABSTRACT_TYPE(Class, Base)
3868#define NON_CANONICAL_TYPE(Class, Base)
3869#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3870#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3871#include "clang/AST/TypeNodes.def"
3872 T = QualType();
3873 break;
3874 // These types are never variably-modified.
3875 case Type::Builtin:
3876 case Type::Complex:
3877 case Type::Vector:
3878 case Type::ExtVector:
3879 case Type::Record:
3880 case Type::Enum:
3881 case Type::Elaborated:
3882 case Type::TemplateSpecialization:
3883 case Type::ObjCObject:
3884 case Type::ObjCInterface:
3885 case Type::ObjCObjectPointer:
Manman Rene6be26c2016-09-13 17:25:08 +00003886 case Type::ObjCTypeParam:
Alexey Bataev93a546a2016-01-21 12:54:48 +00003887 case Type::Pipe:
3888 llvm_unreachable("type class is never variably-modified!");
3889 case Type::Adjusted:
3890 T = cast<AdjustedType>(Ty)->getOriginalType();
3891 break;
3892 case Type::Decayed:
3893 T = cast<DecayedType>(Ty)->getPointeeType();
3894 break;
3895 case Type::Pointer:
3896 T = cast<PointerType>(Ty)->getPointeeType();
3897 break;
3898 case Type::BlockPointer:
3899 T = cast<BlockPointerType>(Ty)->getPointeeType();
3900 break;
3901 case Type::LValueReference:
3902 case Type::RValueReference:
3903 T = cast<ReferenceType>(Ty)->getPointeeType();
3904 break;
3905 case Type::MemberPointer:
3906 T = cast<MemberPointerType>(Ty)->getPointeeType();
3907 break;
3908 case Type::ConstantArray:
3909 case Type::IncompleteArray:
3910 // Losing element qualification here is fine.
3911 T = cast<ArrayType>(Ty)->getElementType();
3912 break;
3913 case Type::VariableArray: {
3914 // Losing element qualification here is fine.
3915 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3916
3917 // Unknown size indication requires no size computation.
3918 // Otherwise, evaluate and record it.
3919 if (auto Size = VAT->getSizeExpr()) {
3920 if (!CSI->isVLATypeCaptured(VAT)) {
3921 RecordDecl *CapRecord = nullptr;
3922 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3923 CapRecord = LSI->Lambda;
3924 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3925 CapRecord = CRSI->TheRecordDecl;
3926 }
3927 if (CapRecord) {
3928 auto ExprLoc = Size->getExprLoc();
3929 auto SizeType = Context.getSizeType();
3930 // Build the non-static data member.
3931 auto Field =
3932 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3933 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3934 /*BW*/ nullptr, /*Mutable*/ false,
3935 /*InitStyle*/ ICIS_NoInit);
3936 Field->setImplicit(true);
3937 Field->setAccess(AS_private);
3938 Field->setCapturedVLAType(VAT);
3939 CapRecord->addDecl(Field);
3940
3941 CSI->addVLATypeCapture(ExprLoc, SizeType);
3942 }
3943 }
3944 }
3945 T = VAT->getElementType();
3946 break;
3947 }
3948 case Type::FunctionProto:
3949 case Type::FunctionNoProto:
3950 T = cast<FunctionType>(Ty)->getReturnType();
3951 break;
3952 case Type::Paren:
3953 case Type::TypeOf:
3954 case Type::UnaryTransform:
3955 case Type::Attributed:
3956 case Type::SubstTemplateTypeParm:
3957 case Type::PackExpansion:
3958 // Keep walking after single level desugaring.
3959 T = T.getSingleStepDesugaredType(Context);
3960 break;
3961 case Type::Typedef:
3962 T = cast<TypedefType>(Ty)->desugar();
3963 break;
3964 case Type::Decltype:
3965 T = cast<DecltypeType>(Ty)->desugar();
3966 break;
3967 case Type::Auto:
3968 T = cast<AutoType>(Ty)->getDeducedType();
3969 break;
3970 case Type::TypeOfExpr:
3971 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3972 break;
3973 case Type::Atomic:
3974 T = cast<AtomicType>(Ty)->getValueType();
3975 break;
3976 }
3977 } while (!T.isNull() && T->isVariablyModifiedType());
3978}
3979
Douglas Gregor0950e412009-03-13 21:01:28 +00003980/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00003981ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003982Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3983 SourceLocation OpLoc,
3984 UnaryExprOrTypeTrait ExprKind,
3985 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00003986 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00003987 return ExprError();
3988
John McCallbcd03502009-12-07 02:54:59 +00003989 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00003990
Douglas Gregor0950e412009-03-13 21:01:28 +00003991 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00003992 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00003993 return ExprError();
3994
Alexey Bataev93a546a2016-01-21 12:54:48 +00003995 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3996 if (auto *TT = T->getAs<TypedefType>()) {
Alexey Bataev41ed6b72016-01-25 07:06:23 +00003997 for (auto I = FunctionScopes.rbegin(),
3998 E = std::prev(FunctionScopes.rend());
3999 I != E; ++I) {
4000 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4001 if (CSI == nullptr)
4002 break;
Alexey Bataev93a546a2016-01-21 12:54:48 +00004003 DeclContext *DC = nullptr;
Alexey Bataev41ed6b72016-01-25 07:06:23 +00004004 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
Alexey Bataev93a546a2016-01-21 12:54:48 +00004005 DC = LSI->CallOperator;
Alexey Bataev41ed6b72016-01-25 07:06:23 +00004006 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
Alexey Bataev93a546a2016-01-21 12:54:48 +00004007 DC = CRSI->TheCapturedDecl;
Alexey Bataev41ed6b72016-01-25 07:06:23 +00004008 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4009 DC = BSI->TheDecl;
4010 if (DC) {
4011 if (DC->containsDecl(TT->getDecl()))
4012 break;
Alexey Bataev93a546a2016-01-21 12:54:48 +00004013 captureVariablyModifiedType(Context, T, CSI);
Alexey Bataev41ed6b72016-01-25 07:06:23 +00004014 }
Alexey Bataev93a546a2016-01-21 12:54:48 +00004015 }
4016 }
4017 }
4018
Douglas Gregor0950e412009-03-13 21:01:28 +00004019 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004020 return new (Context) UnaryExprOrTypeTraitExpr(
4021 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
Douglas Gregor0950e412009-03-13 21:01:28 +00004022}
4023
4024/// \brief Build a sizeof or alignof expression given an expression
4025/// operand.
John McCalldadc5752010-08-24 06:29:42 +00004026ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00004027Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4028 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00004029 ExprResult PE = CheckPlaceholderExpr(E);
4030 if (PE.isInvalid())
4031 return ExprError();
4032
4033 E = PE.get();
4034
Douglas Gregor0950e412009-03-13 21:01:28 +00004035 // Verify that the operand is valid.
4036 bool isInvalid = false;
4037 if (E->isTypeDependent()) {
4038 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00004039 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00004040 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00004041 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00004042 isInvalid = CheckVecStepExpr(E);
Alexey Bataev00396512015-07-02 03:40:19 +00004043 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4044 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4045 isInvalid = true;
John McCalld25db7e2013-05-06 21:39:12 +00004046 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
Richard Smithe301ba22015-11-11 02:02:15 +00004047 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00004048 isInvalid = true;
4049 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00004050 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00004051 }
4052
4053 if (isInvalid)
4054 return ExprError();
4055
Eli Friedmane0afc982012-01-21 01:01:51 +00004056 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
Benjamin Kramerd81108f2012-11-14 15:08:31 +00004057 PE = TransformToPotentiallyEvaluated(E);
Eli Friedmane0afc982012-01-21 01:01:51 +00004058 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004059 E = PE.get();
Eli Friedmane0afc982012-01-21 01:01:51 +00004060 }
4061
Douglas Gregor0950e412009-03-13 21:01:28 +00004062 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004063 return new (Context) UnaryExprOrTypeTraitExpr(
4064 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
Douglas Gregor0950e412009-03-13 21:01:28 +00004065}
4066
Peter Collingbournee190dee2011-03-11 19:24:49 +00004067/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4068/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00004069/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00004070ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00004071Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004072 UnaryExprOrTypeTrait ExprKind, bool IsType,
Craig Toppere335f252015-10-04 04:53:55 +00004073 void *TyOrEx, SourceRange ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00004074 // If error parsing type, ignore.
Craig Topperc3ec1492014-05-26 06:22:03 +00004075 if (!TyOrEx) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00004076
Richard Trieuba63ce62011-09-09 01:45:06 +00004077 if (IsType) {
John McCallbcd03502009-12-07 02:54:59 +00004078 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00004079 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00004080 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00004081 }
Sebastian Redl6f282892008-11-11 17:56:53 +00004082
Douglas Gregor0950e412009-03-13 21:01:28 +00004083 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00004084 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004085 return Result;
Chris Lattnere168f762006-11-10 05:29:30 +00004086}
4087
John Wiegley01296292011-04-08 18:41:53 +00004088static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004089 bool IsReal) {
John Wiegley01296292011-04-08 18:41:53 +00004090 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00004091 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00004092
John McCall34376a62010-12-04 03:47:34 +00004093 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00004094 if (V.get()->getObjectKind() != OK_Ordinary) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004095 V = S.DefaultLvalueConversion(V.get());
John Wiegley01296292011-04-08 18:41:53 +00004096 if (V.isInvalid())
4097 return QualType();
4098 }
John McCall34376a62010-12-04 03:47:34 +00004099
Chris Lattnere267f5d2007-08-26 05:39:26 +00004100 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00004101 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00004102 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00004103
Chris Lattnere267f5d2007-08-26 05:39:26 +00004104 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00004105 if (V.get()->getType()->isArithmeticType())
4106 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004107
John McCall36226622010-10-12 02:09:17 +00004108 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00004109 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00004110 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004111 if (PR.get() != V.get()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004112 V = PR;
Richard Trieuba63ce62011-09-09 01:45:06 +00004113 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall36226622010-10-12 02:09:17 +00004114 }
4115
Chris Lattnere267f5d2007-08-26 05:39:26 +00004116 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00004117 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuba63ce62011-09-09 01:45:06 +00004118 << (IsReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00004119 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00004120}
4121
4122
Chris Lattnere168f762006-11-10 05:29:30 +00004123
John McCalldadc5752010-08-24 06:29:42 +00004124ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004125Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00004126 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00004127 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00004128 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00004129 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00004130 case tok::plusplus: Opc = UO_PostInc; break;
4131 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00004132 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004133
Sebastian Redla9351792012-02-11 23:51:47 +00004134 // Since this might is a postfix expression, get rid of ParenListExprs.
4135 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4136 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004137 Input = Result.get();
Sebastian Redla9351792012-02-11 23:51:47 +00004138
John McCallb268a282010-08-23 23:25:46 +00004139 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00004140}
4141
John McCallf2538342012-07-31 05:14:30 +00004142/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4143///
4144/// \return true on error
4145static bool checkArithmeticOnObjCPointer(Sema &S,
4146 SourceLocation opLoc,
4147 Expr *op) {
4148 assert(op->getType()->isObjCObjectPointerType());
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +00004149 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4150 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
John McCallf2538342012-07-31 05:14:30 +00004151 return false;
4152
4153 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4154 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4155 << op->getSourceRange();
4156 return true;
4157}
4158
Alexey Bataevf7630272015-11-25 12:01:00 +00004159static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4160 auto *BaseNoParens = Base->IgnoreParens();
4161 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4162 return MSProp->getPropertyDecl()->getType()->isArrayType();
4163 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4164}
4165
John McCalldadc5752010-08-24 06:29:42 +00004166ExprResult
John McCallf22d0ac2013-03-04 01:30:55 +00004167Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4168 Expr *idx, SourceLocation rbLoc) {
Alexey Bataev627cbd32015-08-25 15:15:12 +00004169 if (base && !base->getType().isNull() &&
4170 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004171 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4172 /*Length=*/nullptr, rbLoc);
4173
Nate Begeman5ec4b312009-08-10 23:49:36 +00004174 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCallf22d0ac2013-03-04 01:30:55 +00004175 if (isa<ParenListExpr>(base)) {
4176 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4177 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004178 base = result.get();
John McCallf22d0ac2013-03-04 01:30:55 +00004179 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00004180
John McCallf22d0ac2013-03-04 01:30:55 +00004181 // Handle any non-overload placeholder types in the base and index
4182 // expressions. We can't handle overloads here because the other
4183 // operand might be an overloadable type, in which case the overload
4184 // resolution for the operator overload should get the first crack
4185 // at the overload.
Alexey Bataevf7630272015-11-25 12:01:00 +00004186 bool IsMSPropertySubscript = false;
John McCallf22d0ac2013-03-04 01:30:55 +00004187 if (base->getType()->isNonOverloadPlaceholderType()) {
Alexey Bataevf7630272015-11-25 12:01:00 +00004188 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4189 if (!IsMSPropertySubscript) {
4190 ExprResult result = CheckPlaceholderExpr(base);
4191 if (result.isInvalid())
4192 return ExprError();
4193 base = result.get();
4194 }
John McCallf22d0ac2013-03-04 01:30:55 +00004195 }
4196 if (idx->getType()->isNonOverloadPlaceholderType()) {
4197 ExprResult result = CheckPlaceholderExpr(idx);
4198 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004199 idx = result.get();
John McCallf22d0ac2013-03-04 01:30:55 +00004200 }
Mike Stump11289f42009-09-09 15:08:12 +00004201
John McCallf22d0ac2013-03-04 01:30:55 +00004202 // Build an unanalyzed expression if either operand is type-dependent.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004203 if (getLangOpts().CPlusPlus &&
John McCallf22d0ac2013-03-04 01:30:55 +00004204 (base->isTypeDependent() || idx->isTypeDependent())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004205 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4206 VK_LValue, OK_Ordinary, rbLoc);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00004207 }
4208
Alexey Bataevf7630272015-11-25 12:01:00 +00004209 // MSDN, property (C++)
4210 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4211 // This attribute can also be used in the declaration of an empty array in a
4212 // class or structure definition. For example:
4213 // __declspec(property(get=GetX, put=PutX)) int x[];
4214 // The above statement indicates that x[] can be used with one or more array
4215 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4216 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4217 if (IsMSPropertySubscript) {
4218 // Build MS property subscript expression if base is MS property reference
4219 // or MS property subscript.
4220 return new (Context) MSPropertySubscriptExpr(
4221 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4222 }
4223
John McCallf22d0ac2013-03-04 01:30:55 +00004224 // Use C++ overloaded-operator rules if either operand has record
4225 // type. The spec says to do this if either type is *overloadable*,
4226 // but enum types can't declare subscript operators or conversion
4227 // operators, so there's nothing interesting for overload resolution
4228 // to do if there aren't any record types involved.
4229 //
4230 // ObjC pointers have their own subscripting logic that is not tied
4231 // to overload resolution and so should not take this path.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004232 if (getLangOpts().CPlusPlus &&
John McCallf22d0ac2013-03-04 01:30:55 +00004233 (base->getType()->isRecordType() ||
4234 (!base->getType()->isObjCObjectPointerType() &&
4235 idx->getType()->isRecordType()))) {
4236 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00004237 }
4238
John McCallf22d0ac2013-03-04 01:30:55 +00004239 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00004240}
4241
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004242ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4243 Expr *LowerBound,
4244 SourceLocation ColonLoc, Expr *Length,
4245 SourceLocation RBLoc) {
4246 if (Base->getType()->isPlaceholderType() &&
4247 !Base->getType()->isSpecificPlaceholderType(
4248 BuiltinType::OMPArraySection)) {
4249 ExprResult Result = CheckPlaceholderExpr(Base);
4250 if (Result.isInvalid())
4251 return ExprError();
4252 Base = Result.get();
4253 }
4254 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4255 ExprResult Result = CheckPlaceholderExpr(LowerBound);
4256 if (Result.isInvalid())
4257 return ExprError();
Alexey Bataev31300ed2016-02-04 11:27:03 +00004258 Result = DefaultLvalueConversion(Result.get());
4259 if (Result.isInvalid())
4260 return ExprError();
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004261 LowerBound = Result.get();
4262 }
4263 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4264 ExprResult Result = CheckPlaceholderExpr(Length);
4265 if (Result.isInvalid())
4266 return ExprError();
Alexey Bataev31300ed2016-02-04 11:27:03 +00004267 Result = DefaultLvalueConversion(Result.get());
4268 if (Result.isInvalid())
4269 return ExprError();
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004270 Length = Result.get();
4271 }
4272
4273 // Build an unanalyzed expression if either operand is type-dependent.
4274 if (Base->isTypeDependent() ||
4275 (LowerBound &&
4276 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4277 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4278 return new (Context)
4279 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4280 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4281 }
4282
4283 // Perform default conversions.
Alexey Bataeva1764212015-09-30 09:22:36 +00004284 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004285 QualType ResultTy;
4286 if (OriginalTy->isAnyPointerType()) {
4287 ResultTy = OriginalTy->getPointeeType();
4288 } else if (OriginalTy->isArrayType()) {
4289 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4290 } else {
4291 return ExprError(
4292 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4293 << Base->getSourceRange());
4294 }
4295 // C99 6.5.2.1p1
4296 if (LowerBound) {
4297 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4298 LowerBound);
4299 if (Res.isInvalid())
4300 return ExprError(Diag(LowerBound->getExprLoc(),
4301 diag::err_omp_typecheck_section_not_integer)
4302 << 0 << LowerBound->getSourceRange());
4303 LowerBound = Res.get();
4304
4305 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4306 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4307 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4308 << 0 << LowerBound->getSourceRange();
4309 }
4310 if (Length) {
4311 auto Res =
4312 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4313 if (Res.isInvalid())
4314 return ExprError(Diag(Length->getExprLoc(),
4315 diag::err_omp_typecheck_section_not_integer)
4316 << 1 << Length->getSourceRange());
4317 Length = Res.get();
4318
4319 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4320 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4321 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4322 << 1 << Length->getSourceRange();
4323 }
4324
4325 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4326 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4327 // type. Note that functions are not objects, and that (in C99 parlance)
4328 // incomplete types are not object types.
4329 if (ResultTy->isFunctionType()) {
4330 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4331 << ResultTy << Base->getSourceRange();
4332 return ExprError();
4333 }
4334
4335 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4336 diag::err_omp_section_incomplete_type, Base))
4337 return ExprError();
4338
Kelvin Liad9ecba2016-07-20 20:45:29 +00004339 if (LowerBound && !OriginalTy->isAnyPointerType()) {
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004340 llvm::APSInt LowerBoundValue;
4341 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
Kelvin Liad9ecba2016-07-20 20:45:29 +00004342 // OpenMP 4.5, [2.4 Array Sections]
4343 // The array section must be a subset of the original array.
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004344 if (LowerBoundValue.isNegative()) {
Kelvin Liad9ecba2016-07-20 20:45:29 +00004345 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004346 << LowerBound->getSourceRange();
4347 return ExprError();
4348 }
4349 }
4350 }
4351
4352 if (Length) {
4353 llvm::APSInt LengthValue;
4354 if (Length->EvaluateAsInt(LengthValue, Context)) {
Kelvin Liad9ecba2016-07-20 20:45:29 +00004355 // OpenMP 4.5, [2.4 Array Sections]
4356 // The length must evaluate to non-negative integers.
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004357 if (LengthValue.isNegative()) {
Kelvin Liad9ecba2016-07-20 20:45:29 +00004358 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4359 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004360 << Length->getSourceRange();
4361 return ExprError();
4362 }
4363 }
4364 } else if (ColonLoc.isValid() &&
4365 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4366 !OriginalTy->isVariableArrayType()))) {
Kelvin Liad9ecba2016-07-20 20:45:29 +00004367 // OpenMP 4.5, [2.4 Array Sections]
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004368 // When the size of the array dimension is not known, the length must be
4369 // specified explicitly.
4370 Diag(ColonLoc, diag::err_omp_section_length_undefined)
4371 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4372 return ExprError();
4373 }
4374
Alexey Bataev31300ed2016-02-04 11:27:03 +00004375 if (!Base->getType()->isSpecificPlaceholderType(
4376 BuiltinType::OMPArraySection)) {
4377 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4378 if (Result.isInvalid())
4379 return ExprError();
4380 Base = Result.get();
4381 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00004382 return new (Context)
4383 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4384 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4385}
4386
John McCalldadc5752010-08-24 06:29:42 +00004387ExprResult
John McCallb268a282010-08-23 23:25:46 +00004388Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004389 Expr *Idx, SourceLocation RLoc) {
John McCallb268a282010-08-23 23:25:46 +00004390 Expr *LHSExp = Base;
4391 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00004392
Richard Smithb3189a12016-12-05 07:49:14 +00004393 ExprValueKind VK = VK_LValue;
4394 ExprObjectKind OK = OK_Ordinary;
4395
4396 // Per C++ core issue 1213, the result is an xvalue if either operand is
4397 // a non-lvalue array, and an lvalue otherwise.
4398 if (getLangOpts().CPlusPlus11 &&
4399 ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4400 (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4401 VK = VK_XValue;
4402
Chris Lattner36d572b2007-07-16 00:14:47 +00004403 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00004404 if (!LHSExp->getType()->getAs<VectorType>()) {
4405 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4406 if (Result.isInvalid())
4407 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004408 LHSExp = Result.get();
John Wiegley01296292011-04-08 18:41:53 +00004409 }
4410 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4411 if (Result.isInvalid())
4412 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004413 RHSExp = Result.get();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004414
Chris Lattner36d572b2007-07-16 00:14:47 +00004415 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Steve Narofff1e53692007-03-23 22:27:02 +00004416
Steve Naroffc1aadb12007-03-28 21:49:40 +00004417 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00004418 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00004419 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00004420 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00004421 Expr *BaseExpr, *IndexExpr;
4422 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004423 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4424 BaseExpr = LHSExp;
4425 IndexExpr = RHSExp;
4426 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004427 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00004428 BaseExpr = LHSExp;
4429 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00004430 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004431 } else if (const ObjCObjectPointerType *PTy =
John McCallf2538342012-07-31 05:14:30 +00004432 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004433 BaseExpr = LHSExp;
4434 IndexExpr = RHSExp;
John McCallf2538342012-07-31 05:14:30 +00004435
4436 // Use custom logic if this should be the pseudo-object subscript
4437 // expression.
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +00004438 if (!LangOpts.isSubscriptPointerArithmetic())
Craig Topperc3ec1492014-05-26 06:22:03 +00004439 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4440 nullptr);
John McCallf2538342012-07-31 05:14:30 +00004441
Steve Naroff7cae42b2009-07-10 23:34:53 +00004442 ResultType = PTy->getPointeeType();
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00004443 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4444 // Handle the uncommon case of "123[Ptr]".
4445 BaseExpr = RHSExp;
4446 IndexExpr = LHSExp;
4447 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004448 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00004449 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004450 // Handle the uncommon case of "123[Ptr]".
4451 BaseExpr = RHSExp;
4452 IndexExpr = LHSExp;
4453 ResultType = PTy->getPointeeType();
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +00004454 if (!LangOpts.isSubscriptPointerArithmetic()) {
John McCallf2538342012-07-31 05:14:30 +00004455 Diag(LLoc, diag::err_subscript_nonfragile_interface)
4456 << ResultType << BaseExpr->getSourceRange();
4457 return ExprError();
4458 }
John McCall9dd450b2009-09-21 23:43:11 +00004459 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00004460 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00004461 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00004462 VK = LHSExp->getValueKind();
4463 if (VK != VK_RValue)
4464 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00004465
Chris Lattner36d572b2007-07-16 00:14:47 +00004466 // FIXME: need to deal with const...
4467 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00004468 } else if (LHSTy->isArrayType()) {
4469 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00004470 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00004471 // wasn't promoted because of the C90 rule that doesn't
4472 // allow promoting non-lvalue arrays. Warn, then
4473 // force the promotion here.
4474 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4475 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004476 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004477 CK_ArrayToPointerDecay).get();
Eli Friedmanab2784f2009-04-25 23:46:54 +00004478 LHSTy = LHSExp->getType();
4479
4480 BaseExpr = LHSExp;
4481 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004482 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00004483 } else if (RHSTy->isArrayType()) {
4484 // Same as previous, except for 123[f().a] case
4485 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4486 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004487 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004488 CK_ArrayToPointerDecay).get();
Eli Friedmanab2784f2009-04-25 23:46:54 +00004489 RHSTy = RHSExp->getType();
4490
4491 BaseExpr = RHSExp;
4492 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004493 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00004494 } else {
Chris Lattner003af242009-04-25 22:50:55 +00004495 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4496 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004497 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00004498 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00004499 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00004500 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4501 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00004502
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00004503 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00004504 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4505 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00004506 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4507
Douglas Gregorac1fb652009-03-24 19:52:54 +00004508 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00004509 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4510 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00004511 // incomplete types are not object types.
4512 if (ResultType->isFunctionType()) {
4513 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4514 << ResultType << BaseExpr->getSourceRange();
4515 return ExprError();
4516 }
Mike Stump11289f42009-09-09 15:08:12 +00004517
David Blaikiebbafb8a2012-03-11 07:00:24 +00004518 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00004519 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00004520 Diag(LLoc, diag::ext_gnu_subscript_void_type)
4521 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00004522
4523 // C forbids expressions of unqualified void type from being l-values.
4524 // See IsCForbiddenLValueType.
4525 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00004526 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00004527 RequireCompleteType(LLoc, ResultType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004528 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregorac1fb652009-03-24 19:52:54 +00004529 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004530
John McCall4bc41ae2010-11-18 19:01:18 +00004531 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00004532 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00004533
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004534 return new (Context)
4535 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
Chris Lattnere168f762006-11-10 05:29:30 +00004536}
4537
Reid Klecknerc01ee752016-11-23 16:51:30 +00004538bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4539 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00004540 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004541 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00004542 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00004543 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004544 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00004545 diag::note_default_argument_declared_here);
Reid Klecknerc01ee752016-11-23 16:51:30 +00004546 return true;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004547 }
4548
4549 if (Param->hasUninstantiatedDefaultArg()) {
4550 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00004551
Richard Smith505df232012-07-22 23:45:10 +00004552 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4553 Param);
4554
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004555 // Instantiate the expression.
Richard Smith47752e42013-05-03 23:46:09 +00004556 MultiLevelTemplateArgumentList MutiLevelArgList
Craig Topperc3ec1492014-05-26 06:22:03 +00004557 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00004558
Richard Smith80934652012-07-16 01:09:10 +00004559 InstantiatingTemplate Inst(*this, CallLoc, Param,
Richard Smith47752e42013-05-03 23:46:09 +00004560 MutiLevelArgList.getInnermost());
Alp Tokerd4a72d52013-10-08 08:09:04 +00004561 if (Inst.isInvalid())
Reid Klecknerc01ee752016-11-23 16:51:30 +00004562 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00004563 if (Inst.isAlreadyInstantiating()) {
4564 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4565 Param->setInvalidDecl();
Reid Klecknerc01ee752016-11-23 16:51:30 +00004566 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00004567 }
Anders Carlsson355933d2009-08-25 03:49:14 +00004568
Nico Weber44887f62010-11-29 18:19:25 +00004569 ExprResult Result;
4570 {
4571 // C++ [dcl.fct.default]p5:
4572 // The names in the [default argument] expression are bound, and
4573 // the semantic constraints are checked, at the point where the
4574 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00004575 ContextRAII SavedContext(*this, FD);
Douglas Gregora86bc002012-02-16 21:36:18 +00004576 LocalInstantiationScope Local(*this);
Richard Smith869d37e2016-10-14 01:12:20 +00004577 Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4578 /*DirectInit*/false);
Nico Weber44887f62010-11-29 18:19:25 +00004579 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004580 if (Result.isInvalid())
Reid Klecknerc01ee752016-11-23 16:51:30 +00004581 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004582
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004583 // Check the expression as an initializer for the parameter.
4584 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004585 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004586 InitializationKind Kind
4587 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004588 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004589 Expr *ResultE = Result.getAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00004590
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004591 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004592 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004593 if (Result.isInvalid())
Reid Klecknerc01ee752016-11-23 16:51:30 +00004594 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004595
John McCall8a43a0d2016-01-06 23:34:20 +00004596 Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4597 Param->getOuterLocStart());
4598 if (Result.isInvalid())
Reid Klecknerc01ee752016-11-23 16:51:30 +00004599 return true;
John McCall32791cc2016-01-06 22:34:54 +00004600
4601 // Remember the instantiated default argument.
John McCall8a43a0d2016-01-06 23:34:20 +00004602 Param->setDefaultArg(Result.getAs<Expr>());
John McCall32791cc2016-01-06 22:34:54 +00004603 if (ASTMutationListener *L = getASTMutationListener()) {
4604 L->DefaultArgumentInstantiated(Param);
4605 }
Anders Carlsson355933d2009-08-25 03:49:14 +00004606 }
4607
Serge Pavlovb82a9402016-06-14 02:55:56 +00004608 // If the default argument expression is not set yet, we are building it now.
4609 if (!Param->hasInit()) {
4610 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4611 Param->setInvalidDecl();
Reid Klecknerc01ee752016-11-23 16:51:30 +00004612 return true;
Serge Pavlovb82a9402016-06-14 02:55:56 +00004613 }
4614
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004615 // If the default expression creates temporaries, we need to
4616 // push them to the current stack of expression temporaries so they'll
4617 // be properly destroyed.
4618 // FIXME: We should really be rebuilding the default argument with new
4619 // bound temporaries; see the comment in PR5810.
John McCall28fc7092011-11-10 05:35:25 +00004620 // We don't need to do that with block decls, though, because
4621 // blocks in default argument expression can never capture anything.
Tim Shen4a05bb82016-06-21 20:29:17 +00004622 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
John McCall28fc7092011-11-10 05:35:25 +00004623 // Set the "needs cleanups" bit regardless of whether there are
4624 // any explicit objects.
Tim Shen4a05bb82016-06-21 20:29:17 +00004625 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
John McCall28fc7092011-11-10 05:35:25 +00004626
4627 // Append all the objects to the cleanup list. Right now, this
4628 // should always be a no-op, because blocks in default argument
4629 // expressions should never be able to capture anything.
Tim Shen4a05bb82016-06-21 20:29:17 +00004630 assert(!Init->getNumObjects() &&
John McCall28fc7092011-11-10 05:35:25 +00004631 "default argument expression has capturing blocks?");
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00004632 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004633
4634 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00004635 // Just mark all of the declarations in this potentially-evaluated expression
4636 // as being "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +00004637 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4638 /*SkipLocalVariables=*/true);
Reid Klecknerc01ee752016-11-23 16:51:30 +00004639 return false;
Anders Carlsson355933d2009-08-25 03:49:14 +00004640}
4641
Reid Klecknerc01ee752016-11-23 16:51:30 +00004642ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4643 FunctionDecl *FD, ParmVarDecl *Param) {
4644 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4645 return ExprError();
4646 return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4647}
Richard Smith55ce3522012-06-25 20:30:08 +00004648
4649Sema::VariadicCallType
4650Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4651 Expr *Fn) {
4652 if (Proto && Proto->isVariadic()) {
4653 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4654 return VariadicConstructor;
4655 else if (Fn && Fn->getType()->isBlockPointerType())
4656 return VariadicBlock;
4657 else if (FDecl) {
4658 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4659 if (Method->isInstance())
4660 return VariadicMethod;
Richard Trieu9be9c682013-06-22 02:30:38 +00004661 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4662 return VariadicMethod;
Richard Smith55ce3522012-06-25 20:30:08 +00004663 return VariadicFunction;
4664 }
4665 return VariadicDoesNotApply;
4666}
4667
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004668namespace {
4669class FunctionCallCCC : public FunctionCallFilterCCC {
4670public:
4671 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004672 unsigned NumArgs, MemberExpr *ME)
4673 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004674 FunctionName(FuncName) {}
4675
Craig Toppere14c0f82014-03-12 04:55:44 +00004676 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004677 if (!candidate.getCorrectionSpecifier() ||
4678 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4679 return false;
4680 }
4681
4682 return FunctionCallFilterCCC::ValidateCandidate(candidate);
4683 }
4684
4685private:
4686 const IdentifierInfo *const FunctionName;
4687};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004688}
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004689
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004690static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4691 FunctionDecl *FDecl,
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004692 ArrayRef<Expr *> Args) {
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004693 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4694 DeclarationName FuncName = FDecl->getDeclName();
4695 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004696
4697 if (TypoCorrection Corrected = S.CorrectTypo(
4698 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00004699 S.getScopeForContext(S.CurContext), nullptr,
4700 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4701 Args.size(), ME),
John Thompson2255f2c2014-04-23 12:57:01 +00004702 Sema::CTK_ErrorRecovery)) {
Richard Smithde6d6c42015-12-29 19:43:10 +00004703 if (NamedDecl *ND = Corrected.getFoundDecl()) {
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004704 if (Corrected.isOverloaded()) {
Richard Smith100b24a2014-04-17 01:52:14 +00004705 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004706 OverloadCandidateSet::iterator Best;
Craig Topperdfe29ae2015-12-21 06:35:56 +00004707 for (NamedDecl *CD : Corrected) {
4708 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004709 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4710 OCS);
4711 }
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004712 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004713 case OR_Success:
Richard Smithde6d6c42015-12-29 19:43:10 +00004714 ND = Best->FoundDecl;
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004715 Corrected.setCorrectionDecl(ND);
4716 break;
4717 default:
4718 break;
4719 }
4720 }
Richard Smithde6d6c42015-12-29 19:43:10 +00004721 ND = ND->getUnderlyingDecl();
4722 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004723 return Corrected;
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004724 }
4725 }
4726 return TypoCorrection();
4727}
4728
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004729/// ConvertArgumentsForCall - Converts the arguments specified in
4730/// Args/NumArgs to the parameter types of the function FDecl with
4731/// function prototype Proto. Call is the call expression itself, and
4732/// Fn is the function expression. For a C++ member function, this
4733/// routine does not attempt to convert the object argument. Returns
4734/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004735bool
4736Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004737 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004738 const FunctionProtoType *Proto,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004739 ArrayRef<Expr *> Args,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00004740 SourceLocation RParenLoc,
4741 bool IsExecConfig) {
John McCallbebede42011-02-26 05:39:39 +00004742 // Bail out early if calling a builtin with custom typechecking.
John McCallbebede42011-02-26 05:39:39 +00004743 if (FDecl)
4744 if (unsigned ID = FDecl->getBuiltinID())
4745 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4746 return false;
4747
Mike Stump4e1f26a2009-02-19 03:04:26 +00004748 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004749 // assignment, to the types of the corresponding parameter, ...
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004750 unsigned NumParams = Proto->getNumParams();
Douglas Gregorb6b99612009-01-23 21:30:56 +00004751 bool Invalid = false;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004752 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
Peter Collingbourne619a8c72011-10-02 23:49:29 +00004753 unsigned FnKind = Fn->getType()->isBlockPointerType()
4754 ? 1 /* block */
4755 : (IsExecConfig ? 3 /* kernel function (exec config) */
4756 : 0 /* function */);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004757
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004758 // If too few arguments are available (and we don't have default
4759 // arguments for the remaining parameters), don't make the call.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004760 if (Args.size() < NumParams) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004761 if (Args.size() < MinArgs) {
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004762 TypoCorrection TC;
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004763 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004764 unsigned diag_id =
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004765 MinArgs == NumParams && !Proto->isVariadic()
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004766 ? diag::err_typecheck_call_too_few_args_suggest
4767 : diag::err_typecheck_call_too_few_args_at_least_suggest;
Richard Smithf9b15102013-08-17 00:46:16 +00004768 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4769 << static_cast<unsigned>(Args.size())
Kaelyn Uhrain59baee82014-01-28 00:46:47 +00004770 << TC.getCorrectionRange());
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004771 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004772 Diag(RParenLoc,
4773 MinArgs == NumParams && !Proto->isVariadic()
4774 ? diag::err_typecheck_call_too_few_args_one
4775 : diag::err_typecheck_call_too_few_args_at_least_one)
4776 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
Richard Smith10ff50d2012-05-11 05:16:41 +00004777 else
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004778 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4779 ? diag::err_typecheck_call_too_few_args
4780 : diag::err_typecheck_call_too_few_args_at_least)
4781 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4782 << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00004783
4784 // Emit the location of the prototype.
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004785 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00004786 Diag(FDecl->getLocStart(), diag::note_callee_decl)
4787 << FDecl;
4788
4789 return true;
4790 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004791 Call->setNumArgs(Context, NumParams);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004792 }
4793
4794 // If too many are passed and not variadic, error on the extras and drop
4795 // them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004796 if (Args.size() > NumParams) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004797 if (!Proto->isVariadic()) {
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004798 TypoCorrection TC;
Kaelyn Takatafb271f02014-04-04 22:16:30 +00004799 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004800 unsigned diag_id =
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004801 MinArgs == NumParams && !Proto->isVariadic()
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004802 ? diag::err_typecheck_call_too_many_args_suggest
4803 : diag::err_typecheck_call_too_many_args_at_most_suggest;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004804 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
Richard Smithf9b15102013-08-17 00:46:16 +00004805 << static_cast<unsigned>(Args.size())
Kaelyn Uhrain59baee82014-01-28 00:46:47 +00004806 << TC.getCorrectionRange());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004807 } else if (NumParams == 1 && FDecl &&
Richard Smithf9b15102013-08-17 00:46:16 +00004808 FDecl->getParamDecl(0)->getDeclName())
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004809 Diag(Args[NumParams]->getLocStart(),
4810 MinArgs == NumParams
4811 ? diag::err_typecheck_call_too_many_args_one
4812 : diag::err_typecheck_call_too_many_args_at_most_one)
4813 << FnKind << FDecl->getParamDecl(0)
4814 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4815 << SourceRange(Args[NumParams]->getLocStart(),
4816 Args.back()->getLocEnd());
Richard Smithd72da152012-05-15 06:21:54 +00004817 else
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004818 Diag(Args[NumParams]->getLocStart(),
4819 MinArgs == NumParams
4820 ? diag::err_typecheck_call_too_many_args
4821 : diag::err_typecheck_call_too_many_args_at_most)
4822 << FnKind << NumParams << static_cast<unsigned>(Args.size())
4823 << Fn->getSourceRange()
4824 << SourceRange(Args[NumParams]->getLocStart(),
4825 Args.back()->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00004826
4827 // Emit the location of the prototype.
Kaelyn Uhrain476c8232013-07-08 23:13:44 +00004828 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00004829 Diag(FDecl->getLocStart(), diag::note_callee_decl)
4830 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00004831
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004832 // This deletes the extra arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004833 Call->setNumArgs(Context, NumParams);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004834 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004835 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004836 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004837 SmallVector<Expr *, 8> AllArgs;
Richard Smith55ce3522012-06-25 20:30:08 +00004838 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4839
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004840 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004841 Proto, 0, Args, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004842 if (Invalid)
4843 return true;
4844 unsigned TotalNumArgs = AllArgs.size();
4845 for (unsigned i = 0; i < TotalNumArgs; ++i)
4846 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004847
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004848 return false;
4849}
Mike Stump4e1f26a2009-02-19 03:04:26 +00004850
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004851bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004852 const FunctionProtoType *Proto,
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004853 unsigned FirstParam, ArrayRef<Expr *> Args,
Craig Topper5603df42013-07-05 19:34:19 +00004854 SmallVectorImpl<Expr *> &AllArgs,
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004855 VariadicCallType CallType, bool AllowExplicit,
Richard Smith6b216962013-02-05 05:52:24 +00004856 bool IsListInitialization) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004857 unsigned NumParams = Proto->getNumParams();
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004858 bool Invalid = false;
Craig Topperdfe29ae2015-12-21 06:35:56 +00004859 size_t ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004860 // Continue to check argument types (even if we have too few/many args).
Richard Smithd6f9e732014-05-13 19:56:21 +00004861 for (unsigned i = FirstParam; i < NumParams; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004862 QualType ProtoArgType = Proto->getParamType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004863
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004864 Expr *Arg;
Richard Smithd6f9e732014-05-13 19:56:21 +00004865 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00004866 if (ArgIx < Args.size()) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004867 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004868
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004869 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedman3164fb12009-03-22 22:00:50 +00004870 ProtoArgType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004871 diag::err_call_incomplete_argument, Arg))
Eli Friedman3164fb12009-03-22 22:00:50 +00004872 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004873
John McCall4124c492011-10-17 18:40:02 +00004874 // Strip the unbridged-cast placeholder expression off, if applicable.
Fariborz Jahanian48d94c82013-07-31 18:39:08 +00004875 bool CFAudited = false;
John McCall4124c492011-10-17 18:40:02 +00004876 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4877 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4878 (!Param || !Param->hasAttr<CFConsumedAttr>()))
4879 Arg = stripARCUnbridgedCast(Arg);
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004880 else if (getLangOpts().ObjCAutoRefCount &&
4881 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
Fariborz Jahanian48d94c82013-07-31 18:39:08 +00004882 (!Param || !Param->hasAttr<CFConsumedAttr>()))
4883 CFAudited = true;
John McCall4124c492011-10-17 18:40:02 +00004884
Alp Toker9cacbab2014-01-20 20:26:09 +00004885 InitializedEntity Entity =
4886 Param ? InitializedEntity::InitializeParameter(Context, Param,
4887 ProtoArgType)
4888 : InitializedEntity::InitializeParameter(
4889 Context, ProtoArgType, Proto->isParamConsumed(i));
4890
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004891 // Remember that parameter belongs to a CF audited API.
Fariborz Jahanian48d94c82013-07-31 18:39:08 +00004892 if (CFAudited)
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004893 Entity.setParameterCFAudited();
Richard Smithd6f9e732014-05-13 19:56:21 +00004894
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004895 ExprResult ArgE = PerformCopyInitialization(
4896 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004897 if (ArgE.isInvalid())
4898 return true;
4899
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004900 Arg = ArgE.getAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004901 } else {
Richard Smithd6f9e732014-05-13 19:56:21 +00004902 assert(Param && "can't use default arguments without a known callee");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004903
John McCalldadc5752010-08-24 06:29:42 +00004904 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004905 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004906 if (ArgExpr.isInvalid())
4907 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004908
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004909 Arg = ArgExpr.getAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004910 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004911
4912 // Check for array bounds violations for each argument to the call. This
4913 // check only triggers warnings when the argument isn't a more complex Expr
4914 // with its own checking, such as a BinaryOperator.
4915 CheckArrayAccess(Arg);
4916
Peter Collingbournea48f33f2011-10-19 00:16:45 +00004917 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4918 CheckStaticArrayArgument(CallLoc, Param, Arg);
4919
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004920 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004921 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004922
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004923 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004924 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00004925 // Assume that extern "C" functions with variadic arguments that
4926 // return __unknown_anytype aren't *really* variadic.
Alp Toker314cc812014-01-25 16:55:45 +00004927 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4928 FDecl->isExternC()) {
Craig Topperdfe29ae2015-12-21 06:35:56 +00004929 for (Expr *A : Args.slice(ArgIx)) {
John McCallcc5788c2013-03-04 07:34:02 +00004930 QualType paramType; // ignored
Craig Topperdfe29ae2015-12-21 06:35:56 +00004931 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
John McCall2979fe02011-04-12 00:42:48 +00004932 Invalid |= arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004933 AllArgs.push_back(arg.get());
John McCall2979fe02011-04-12 00:42:48 +00004934 }
4935
4936 // Otherwise do argument promotion, (C99 6.5.2.2p7).
4937 } else {
Craig Topperdfe29ae2015-12-21 06:35:56 +00004938 for (Expr *A : Args.slice(ArgIx)) {
4939 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
John McCall2979fe02011-04-12 00:42:48 +00004940 Invalid |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004941 AllArgs.push_back(Arg.get());
John McCall2979fe02011-04-12 00:42:48 +00004942 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004943 }
Ted Kremenekd41f3462011-09-26 23:36:13 +00004944
4945 // Check for array bounds violations.
Craig Topperdfe29ae2015-12-21 06:35:56 +00004946 for (Expr *A : Args.slice(ArgIx))
4947 CheckArrayAccess(A);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004948 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00004949 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004950}
4951
Peter Collingbournea48f33f2011-10-19 00:16:45 +00004952static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4953 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
Reid Kleckner8a365022013-06-24 17:51:48 +00004954 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4955 TL = DTL.getOriginalLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00004956 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
Peter Collingbournea48f33f2011-10-19 00:16:45 +00004957 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
David Blaikie6adc78e2013-02-18 22:06:02 +00004958 << ATL.getLocalSourceRange();
Peter Collingbournea48f33f2011-10-19 00:16:45 +00004959}
4960
4961/// CheckStaticArrayArgument - If the given argument corresponds to a static
4962/// array parameter, check that it is non-null, and that if it is formed by
4963/// array-to-pointer decay, the underlying array is sufficiently large.
4964///
4965/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4966/// array type derivation, then for each call to the function, the value of the
4967/// corresponding actual argument shall provide access to the first element of
4968/// an array with at least as many elements as specified by the size expression.
4969void
4970Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4971 ParmVarDecl *Param,
4972 const Expr *ArgExpr) {
4973 // Static array parameters are not supported in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004974 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbournea48f33f2011-10-19 00:16:45 +00004975 return;
4976
4977 QualType OrigTy = Param->getOriginalType();
4978
4979 const ArrayType *AT = Context.getAsArrayType(OrigTy);
4980 if (!AT || AT->getSizeModifier() != ArrayType::Static)
4981 return;
4982
4983 if (ArgExpr->isNullPointerConstant(Context,
4984 Expr::NPC_NeverValueDependent)) {
4985 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4986 DiagnoseCalleeStaticArrayParam(*this, Param);
4987 return;
4988 }
4989
4990 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4991 if (!CAT)
4992 return;
4993
4994 const ConstantArrayType *ArgCAT =
4995 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4996 if (!ArgCAT)
4997 return;
4998
4999 if (ArgCAT->getSize().ult(CAT->getSize())) {
5000 Diag(CallLoc, diag::warn_static_array_too_small)
5001 << ArgExpr->getSourceRange()
5002 << (unsigned) ArgCAT->getSize().getZExtValue()
5003 << (unsigned) CAT->getSize().getZExtValue();
5004 DiagnoseCalleeStaticArrayParam(*this, Param);
5005 }
5006}
5007
John McCall2979fe02011-04-12 00:42:48 +00005008/// Given a function expression of unknown-any type, try to rebuild it
5009/// to have a function type.
5010static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5011
John McCall5e77d762013-04-16 07:28:30 +00005012/// Is the given type a placeholder that we need to lower out
5013/// immediately during argument processing?
5014static bool isPlaceholderToRemoveAsArg(QualType type) {
5015 // Placeholders are never sugared.
5016 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5017 if (!placeholder) return false;
5018
5019 switch (placeholder->getKind()) {
5020 // Ignore all the non-placeholder types.
Alexey Bader954ba212016-04-08 13:40:33 +00005021#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5022 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00005023#include "clang/Basic/OpenCLImageTypes.def"
John McCall5e77d762013-04-16 07:28:30 +00005024#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5025#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5026#include "clang/AST/BuiltinTypes.def"
5027 return false;
5028
5029 // We cannot lower out overload sets; they might validly be resolved
5030 // by the call machinery.
5031 case BuiltinType::Overload:
5032 return false;
5033
5034 // Unbridged casts in ARC can be handled in some call positions and
5035 // should be left in place.
5036 case BuiltinType::ARCUnbridgedCast:
5037 return false;
5038
5039 // Pseudo-objects should be converted as soon as possible.
5040 case BuiltinType::PseudoObject:
5041 return true;
5042
5043 // The debugger mode could theoretically but currently does not try
5044 // to resolve unknown-typed arguments based on known parameter types.
5045 case BuiltinType::UnknownAny:
5046 return true;
5047
5048 // These are always invalid as call arguments and should be reported.
5049 case BuiltinType::BoundMember:
5050 case BuiltinType::BuiltinFn:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005051 case BuiltinType::OMPArraySection:
John McCall5e77d762013-04-16 07:28:30 +00005052 return true;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005053
John McCall5e77d762013-04-16 07:28:30 +00005054 }
5055 llvm_unreachable("bad builtin type kind");
5056}
5057
5058/// Check an argument list for placeholders that we won't try to
5059/// handle later.
5060static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5061 // Apply this processing to all the arguments at once instead of
5062 // dying at the first failure.
5063 bool hasInvalid = false;
5064 for (size_t i = 0, e = args.size(); i != e; i++) {
5065 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5066 ExprResult result = S.CheckPlaceholderExpr(args[i]);
5067 if (result.isInvalid()) hasInvalid = true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005068 else args[i] = result.get();
Kaelyn Takata15867822014-11-21 18:48:04 +00005069 } else if (hasInvalid) {
5070 (void)S.CorrectDelayedTyposInExpr(args[i]);
John McCall5e77d762013-04-16 07:28:30 +00005071 }
5072 }
5073 return hasInvalid;
5074}
5075
Tom Stellardb919c7d2015-03-31 16:39:02 +00005076/// If a builtin function has a pointer argument with no explicit address
Sanjay Patel71fca732015-12-29 20:09:37 +00005077/// space, then it should be able to accept a pointer to any address
Tom Stellardb919c7d2015-03-31 16:39:02 +00005078/// space as input. In order to do this, we need to replace the
5079/// standard builtin declaration with one that uses the same address space
5080/// as the call.
5081///
5082/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5083/// it does not contain any pointer arguments without
5084/// an address space qualifer. Otherwise the rewritten
5085/// FunctionDecl is returned.
5086/// TODO: Handle pointer return types.
5087static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5088 const FunctionDecl *FDecl,
5089 MultiExprArg ArgExprs) {
5090
5091 QualType DeclType = FDecl->getType();
5092 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5093
5094 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5095 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5096 return nullptr;
5097
5098 bool NeedsNewDecl = false;
5099 unsigned i = 0;
5100 SmallVector<QualType, 8> OverloadParams;
5101
5102 for (QualType ParamType : FT->param_types()) {
5103
5104 // Convert array arguments to pointer to simplify type lookup.
David Majnemere7287712016-07-21 23:03:43 +00005105 ExprResult ArgRes =
5106 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5107 if (ArgRes.isInvalid())
5108 return nullptr;
5109 Expr *Arg = ArgRes.get();
Tom Stellardb919c7d2015-03-31 16:39:02 +00005110 QualType ArgType = Arg->getType();
5111 if (!ParamType->isPointerType() ||
5112 ParamType.getQualifiers().hasAddressSpace() ||
5113 !ArgType->isPointerType() ||
5114 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5115 OverloadParams.push_back(ParamType);
5116 continue;
5117 }
5118
5119 NeedsNewDecl = true;
5120 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5121
5122 QualType PointeeType = ParamType->getPointeeType();
5123 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5124 OverloadParams.push_back(Context.getPointerType(PointeeType));
5125 }
5126
5127 if (!NeedsNewDecl)
5128 return nullptr;
5129
5130 FunctionProtoType::ExtProtoInfo EPI;
5131 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5132 OverloadParams, EPI);
5133 DeclContext *Parent = Context.getTranslationUnitDecl();
5134 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5135 FDecl->getLocation(),
5136 FDecl->getLocation(),
5137 FDecl->getIdentifier(),
5138 OverloadTy,
5139 /*TInfo=*/nullptr,
5140 SC_Extern, false,
5141 /*hasPrototype=*/true);
5142 SmallVector<ParmVarDecl*, 16> Params;
5143 FT = cast<FunctionProtoType>(OverloadTy);
5144 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5145 QualType ParamType = FT->getParamType(i);
5146 ParmVarDecl *Parm =
5147 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5148 SourceLocation(), nullptr, ParamType,
5149 /*TInfo=*/nullptr, SC_None, nullptr);
5150 Parm->setScopeInfo(0, i);
5151 Params.push_back(Parm);
5152 }
5153 OverloadDecl->setParams(Params);
5154 return OverloadDecl;
5155}
5156
George Burgess IV21d3bff2016-03-31 00:16:25 +00005157static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee,
5158 std::size_t NumArgs) {
5159 if (S.TooManyArguments(Callee->getNumParams(), NumArgs,
5160 /*PartialOverloading=*/false))
5161 return Callee->isVariadic();
5162 return Callee->getMinRequiredArguments() <= NumArgs;
5163}
5164
Justin Lebar9fdb46e2016-10-08 01:07:11 +00005165/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5166/// This provides the location of the left/right parens and a list of comma
5167/// locations.
5168ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5169 MultiExprArg ArgExprs, SourceLocation RParenLoc,
5170 Expr *ExecConfig, bool IsExecConfig) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005171 // Since this might be a postfix expression, get rid of ParenListExprs.
Justin Lebar9fdb46e2016-10-08 01:07:11 +00005172 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
John McCallb268a282010-08-23 23:25:46 +00005173 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005174 Fn = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00005175
Justin Lebar9fdb46e2016-10-08 01:07:11 +00005176 if (checkArgsForPlaceholders(*this, ArgExprs))
John McCall5e77d762013-04-16 07:28:30 +00005177 return ExprError();
5178
Justin Lebar9fdb46e2016-10-08 01:07:11 +00005179 if (getLangOpts().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00005180 // If this is a pseudo-destructor expression, build the call immediately.
5181 if (isa<CXXPseudoDestructorExpr>(Fn)) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00005182 if (!ArgExprs.empty()) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00005183 // Pseudo-destructor calls should not have any arguments.
Justin Lebar9fdb46e2016-10-08 01:07:11 +00005184 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Justin Lebar18e2d822016-08-15 23:00:49 +00005185 << FixItHint::CreateRemoval(
5186 SourceRange(ArgExprs.front()->getLocStart(),
5187 ArgExprs.back()->getLocEnd()));
Douglas Gregorad8a3362009-09-04 17:36:40 +00005188 }
Mike Stump11289f42009-09-09 15:08:12 +00005189
Justin Lebar9fdb46e2016-10-08 01:07:11 +00005190 return new (Context)
5191 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
Douglas Gregorad8a3362009-09-04 17:36:40 +00005192 }
Justin Lebar9fdb46e2016-10-08 01:07:11 +00005193 if (Fn->getType() == Context.PseudoObjectTy) {
5194 ExprResult result = CheckPlaceholderExpr(Fn);
John McCall5e77d762013-04-16 07:28:30 +00005195 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005196 Fn = result.get();
John McCall5e77d762013-04-16 07:28:30 +00005197 }
Mike Stump11289f42009-09-09 15:08:12 +00005198
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005199 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00005200 // in which case we won't do any semantic analysis now.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005201 bool Dependent = false;
5202 if (Fn->isTypeDependent())
5203 Dependent = true;
Benjamin Kramerc215e762012-08-24 11:54:20 +00005204 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005205 Dependent = true;
5206
Peter Collingbourne41f85462011-02-09 21:07:24 +00005207 if (Dependent) {
5208 if (ExecConfig) {
Justin Lebar9fdb46e2016-10-08 01:07:11 +00005209 return new (Context) CUDAKernelCallExpr(
5210 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5211 Context.DependentTy, VK_RValue, RParenLoc);
Peter Collingbourne41f85462011-02-09 21:07:24 +00005212 } else {
Justin Lebar9fdb46e2016-10-08 01:07:11 +00005213 return new (Context) CallExpr(
5214 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
Peter Collingbourne41f85462011-02-09 21:07:24 +00005215 }
5216 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005217
5218 // Determine whether this is a call to an object (C++ [over.call.object]).
5219 if (Fn->getType()->isRecordType())
Justin Lebar9fdb46e2016-10-08 01:07:11 +00005220 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5221 RParenLoc);
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005222
Justin Lebar9fdb46e2016-10-08 01:07:11 +00005223 if (Fn->getType() == Context.UnknownAnyTy) {
5224 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
John McCall2979fe02011-04-12 00:42:48 +00005225 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005226 Fn = result.get();
John McCall2979fe02011-04-12 00:42:48 +00005227 }
5228
Justin Lebar9fdb46e2016-10-08 01:07:11 +00005229 if (Fn->getType() == Context.BoundMemberTy) {
5230 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5231 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00005232 }
John McCall0009fcc2011-04-26 20:42:42 +00005233 }
John McCall10eae182009-11-30 22:42:35 +00005234
John McCall0009fcc2011-04-26 20:42:42 +00005235 // Check for overloaded calls. This can happen even in C due to extensions.
Justin Lebar9fdb46e2016-10-08 01:07:11 +00005236 if (Fn->getType() == Context.OverloadTy) {
John McCall0009fcc2011-04-26 20:42:42 +00005237 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5238
Justin Lebar18e2d822016-08-15 23:00:49 +00005239 // We aren't supposed to apply this logic for if there'Scope an '&'
5240 // involved.
Douglas Gregorf4a06c22011-10-13 18:26:27 +00005241 if (!find.HasFormOfMemberPointer) {
John McCall0009fcc2011-04-26 20:42:42 +00005242 OverloadExpr *ovl = find.Expression;
Yaron Keren442dfb42015-12-23 20:38:13 +00005243 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
Justin Lebar9fdb46e2016-10-08 01:07:11 +00005244 return BuildOverloadedCallExpr(
Justin Lebar18e2d822016-08-15 23:00:49 +00005245 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5246 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
Justin Lebar9fdb46e2016-10-08 01:07:11 +00005247 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5248 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00005249 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005250 }
5251
Douglas Gregore254f902009-02-04 00:32:51 +00005252 // If we're directly calling a function, get the appropriate declaration.
Justin Lebar9fdb46e2016-10-08 01:07:11 +00005253 if (Fn->getType() == Context.UnknownAnyTy) {
5254 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
Douglas Gregord8fb1e32011-12-01 01:37:36 +00005255 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005256 Fn = result.get();
Douglas Gregord8fb1e32011-12-01 01:37:36 +00005257 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005258
Eli Friedmane14b1992009-12-26 03:35:45 +00005259 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00005260
George Burgess IV7204ed92016-01-07 02:26:57 +00005261 bool CallingNDeclIndirectly = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00005262 NamedDecl *NDecl = nullptr;
George Burgess IV7204ed92016-01-07 02:26:57 +00005263 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5264 if (UnOp->getOpcode() == UO_AddrOf) {
5265 CallingNDeclIndirectly = true;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00005266 NakedFn = UnOp->getSubExpr()->IgnoreParens();
George Burgess IV7204ed92016-01-07 02:26:57 +00005267 }
5268 }
Tom Stellardb919c7d2015-03-31 16:39:02 +00005269
5270 if (isa<DeclRefExpr>(NakedFn)) {
John McCall57500772009-12-16 12:17:52 +00005271 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
Tom Stellardb919c7d2015-03-31 16:39:02 +00005272
5273 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5274 if (FDecl && FDecl->getBuiltinID()) {
Sanjay Patel71fca732015-12-29 20:09:37 +00005275 // Rewrite the function decl for this builtin by replacing parameters
Tom Stellardb919c7d2015-03-31 16:39:02 +00005276 // with no explicit address space with the address space of the arguments
5277 // in ArgExprs.
Justin Lebar18e2d822016-08-15 23:00:49 +00005278 if ((FDecl =
Justin Lebar9fdb46e2016-10-08 01:07:11 +00005279 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
Tom Stellardb919c7d2015-03-31 16:39:02 +00005280 NDecl = FDecl;
Justin Lebar18e2d822016-08-15 23:00:49 +00005281 Fn = DeclRefExpr::Create(
Justin Lebar9fdb46e2016-10-08 01:07:11 +00005282 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
Justin Lebar18e2d822016-08-15 23:00:49 +00005283 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
Tom Stellardb919c7d2015-03-31 16:39:02 +00005284 }
5285 }
5286 } else if (isa<MemberExpr>(NakedFn))
John McCall0009fcc2011-04-26 20:42:42 +00005287 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00005288
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005289 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
George Burgess IV7204ed92016-01-07 02:26:57 +00005290 if (CallingNDeclIndirectly &&
Justin Lebar9fdb46e2016-10-08 01:07:11 +00005291 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5292 Fn->getLocStart()))
George Burgess IV7204ed92016-01-07 02:26:57 +00005293 return ExprError();
5294
Yaxun Liu5b746652016-12-18 05:18:55 +00005295 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5296 return ExprError();
5297
George Burgess IV21d3bff2016-03-31 00:16:25 +00005298 // CheckEnableIf assumes that the we're passing in a sane number of args for
5299 // FD, but that doesn't always hold true here. This is because, in some
5300 // cases, we'll emit a diag about an ill-formed function call, but then
5301 // we'll continue on as if the function call wasn't ill-formed. So, if the
5302 // number of args looks incorrect, don't do enable_if checks; we should've
5303 // already emitted an error about the bad call.
5304 if (FD->hasAttr<EnableIfAttr>() &&
Justin Lebar9fdb46e2016-10-08 01:07:11 +00005305 isNumberOfArgsValidForCall(*this, FD, ArgExprs.size())) {
5306 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
5307 Diag(Fn->getLocStart(),
5308 isa<CXXMethodDecl>(FD)
5309 ? diag::err_ovl_no_viable_member_function_in_call
5310 : diag::err_ovl_no_viable_function_in_call)
Justin Lebar18e2d822016-08-15 23:00:49 +00005311 << FD << FD->getSourceRange();
Justin Lebar9fdb46e2016-10-08 01:07:11 +00005312 Diag(FD->getLocation(),
5313 diag::note_ovl_candidate_disabled_by_enable_if_attr)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005314 << Attr->getCond()->getSourceRange() << Attr->getMessage();
5315 }
5316 }
5317 }
5318
Justin Lebar9fdb46e2016-10-08 01:07:11 +00005319 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5320 ExecConfig, IsExecConfig);
Peter Collingbourne41f85462011-02-09 21:07:24 +00005321}
5322
Tanya Lattner55808c12011-06-04 00:47:47 +00005323/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5324///
5325/// __builtin_astype( value, dst type )
5326///
Richard Trieuba63ce62011-09-09 01:45:06 +00005327ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00005328 SourceLocation BuiltinLoc,
5329 SourceLocation RParenLoc) {
5330 ExprValueKind VK = VK_RValue;
5331 ExprObjectKind OK = OK_Ordinary;
Richard Trieuba63ce62011-09-09 01:45:06 +00005332 QualType DstTy = GetTypeFromParser(ParsedDestTy);
5333 QualType SrcTy = E->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00005334 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5335 return ExprError(Diag(BuiltinLoc,
5336 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00005337 << DstTy
5338 << SrcTy
Richard Trieuba63ce62011-09-09 01:45:06 +00005339 << E->getSourceRange());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005340 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Tanya Lattner55808c12011-06-04 00:47:47 +00005341}
5342
Hal Finkelc4d7c822013-09-18 03:29:45 +00005343/// ActOnConvertVectorExpr - create a new convert-vector expression from the
5344/// provided arguments.
5345///
5346/// __builtin_convertvector( value, dst type )
5347///
5348ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5349 SourceLocation BuiltinLoc,
5350 SourceLocation RParenLoc) {
5351 TypeSourceInfo *TInfo;
5352 GetTypeFromParser(ParsedDestTy, &TInfo);
5353 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5354}
5355
John McCall57500772009-12-16 12:17:52 +00005356/// BuildResolvedCallExpr - Build a call to a resolved expression,
5357/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00005358/// unary-convert to an expression of function-pointer or
5359/// block-pointer type.
5360///
5361/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00005362ExprResult
John McCall2d74de92009-12-01 22:10:20 +00005363Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5364 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005365 ArrayRef<Expr *> Args,
Peter Collingbourne41f85462011-02-09 21:07:24 +00005366 SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00005367 Expr *Config, bool IsExecConfig) {
John McCall2d74de92009-12-01 22:10:20 +00005368 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
Eli Friedman34866c72012-08-31 00:14:07 +00005369 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
John McCall2d74de92009-12-01 22:10:20 +00005370
Alexey Bataevd51e9932016-01-15 04:06:31 +00005371 // Functions with 'interrupt' attribute cannot be called directly.
5372 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5373 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5374 return ExprError();
5375 }
5376
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005377 // Promote the function operand.
Eli Friedman34866c72012-08-31 00:14:07 +00005378 // We special-case function promotion here because we only allow promoting
5379 // builtin functions to function pointers in the callee of a call.
5380 ExprResult Result;
5381 if (BuiltinID &&
5382 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5383 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005384 CK_BuiltinFnToFnPtr).get();
Eli Friedman34866c72012-08-31 00:14:07 +00005385 } else {
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +00005386 Result = CallExprUnaryConversions(Fn);
Eli Friedman34866c72012-08-31 00:14:07 +00005387 }
John Wiegley01296292011-04-08 18:41:53 +00005388 if (Result.isInvalid())
5389 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005390 Fn = Result.get();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005391
Chris Lattner08464942007-12-28 05:29:59 +00005392 // Make the call expr early, before semantic checks. This guarantees cleanup
5393 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00005394 CallExpr *TheCall;
Eric Christopher13586ab2012-05-30 01:14:28 +00005395 if (Config)
Peter Collingbourne41f85462011-02-09 21:07:24 +00005396 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005397 cast<CallExpr>(Config), Args,
5398 Context.BoolTy, VK_RValue,
Peter Collingbourne41f85462011-02-09 21:07:24 +00005399 RParenLoc);
Eric Christopher13586ab2012-05-30 01:14:28 +00005400 else
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005401 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5402 VK_RValue, RParenLoc);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005403
Kaelyn Takata72d16a52015-06-23 19:13:17 +00005404 if (!getLangOpts().CPlusPlus) {
5405 // C cannot always handle TypoExpr nodes in builtin calls and direct
5406 // function calls as their argument checking don't necessarily handle
5407 // dependent types properly, so make sure any TypoExprs have been
5408 // dealt with.
5409 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5410 if (!Result.isUsable()) return ExprError();
5411 TheCall = dyn_cast<CallExpr>(Result.get());
5412 if (!TheCall) return Result;
Craig Topper882bc8d2015-11-07 06:16:16 +00005413 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
Kaelyn Takatae53f0f92015-06-23 18:42:21 +00005414 }
John McCallbebede42011-02-26 05:39:39 +00005415
Kaelyn Takata72d16a52015-06-23 19:13:17 +00005416 // Bail out early if calling a builtin with custom typechecking.
5417 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5418 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5419
John McCall31996342011-04-07 08:22:57 +00005420 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005421 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00005422 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005423 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5424 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00005425 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Craig Topperc3ec1492014-05-26 06:22:03 +00005426 if (!FuncT)
John McCallbebede42011-02-26 05:39:39 +00005427 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5428 << Fn->getType() << Fn->getSourceRange());
5429 } else if (const BlockPointerType *BPT =
5430 Fn->getType()->getAs<BlockPointerType>()) {
5431 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5432 } else {
John McCall31996342011-04-07 08:22:57 +00005433 // Handle calls to expressions of unknown-any type.
5434 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00005435 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00005436 if (rewrite.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005437 Fn = rewrite.get();
John McCall39439732011-04-09 22:50:59 +00005438 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00005439 goto retry;
5440 }
5441
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005442 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5443 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00005444 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005445
David Blaikiebbafb8a2012-03-11 07:00:24 +00005446 if (getLangOpts().CUDA) {
Peter Collingbourne4b66c472011-02-23 01:53:29 +00005447 if (Config) {
5448 // CUDA: Kernel calls must be to global functions
5449 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5450 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5451 << FDecl->getName() << Fn->getSourceRange());
5452
5453 // CUDA: Kernel function must have 'void' return type
Alp Toker314cc812014-01-25 16:55:45 +00005454 if (!FuncT->getReturnType()->isVoidType())
Peter Collingbourne4b66c472011-02-23 01:53:29 +00005455 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5456 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne34a20b02011-10-02 23:49:15 +00005457 } else {
5458 // CUDA: Calls to global functions must be configured
5459 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5460 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5461 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne4b66c472011-02-23 01:53:29 +00005462 }
5463 }
5464
Eli Friedman3164fb12009-03-22 22:00:50 +00005465 // Check for a valid return type
Alp Toker314cc812014-01-25 16:55:45 +00005466 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00005467 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00005468 return ExprError();
5469
Chris Lattner08464942007-12-28 05:29:59 +00005470 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00005471 TheCall->setType(FuncT->getCallResultType(Context));
Alp Toker314cc812014-01-25 16:55:45 +00005472 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005473
Richard Smith55ce3522012-06-25 20:30:08 +00005474 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5475 if (Proto) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005476 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5477 IsExecConfig))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005478 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00005479 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005480 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005481
Douglas Gregord8e97de2009-04-02 15:37:10 +00005482 if (FDecl) {
5483 // Check if we have too few/too many template arguments, based
5484 // on our knowledge of the function definition.
Craig Topperc3ec1492014-05-26 06:22:03 +00005485 const FunctionDecl *Def = nullptr;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005486 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
Richard Smith55ce3522012-06-25 20:30:08 +00005487 Proto = Def->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005488 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00005489 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005490 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00005491 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00005492
5493 // If the function we're calling isn't a function prototype, but we have
5494 // a function prototype from a prior declaratiom, use that prototype.
5495 if (!FDecl->hasPrototype())
5496 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00005497 }
5498
Steve Naroff0b661582007-08-28 23:30:39 +00005499 // Promote the arguments (C99 6.5.2.2p6).
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005500 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Chris Lattner08464942007-12-28 05:29:59 +00005501 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00005502
Alp Toker9cacbab2014-01-20 20:26:09 +00005503 if (Proto && i < Proto->getNumParams()) {
5504 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5505 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005506 ExprResult ArgE =
5507 PerformCopyInitialization(Entity, SourceLocation(), Arg);
Douglas Gregor8e09a722010-10-25 20:39:23 +00005508 if (ArgE.isInvalid())
5509 return true;
5510
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005511 Arg = ArgE.getAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00005512
5513 } else {
John Wiegley01296292011-04-08 18:41:53 +00005514 ExprResult ArgE = DefaultArgumentPromotion(Arg);
5515
5516 if (ArgE.isInvalid())
5517 return true;
5518
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005519 Arg = ArgE.getAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00005520 }
5521
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005522 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor83025412010-10-26 05:45:40 +00005523 Arg->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005524 diag::err_call_incomplete_argument, Arg))
Douglas Gregor83025412010-10-26 05:45:40 +00005525 return ExprError();
5526
Chris Lattner08464942007-12-28 05:29:59 +00005527 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00005528 }
Steve Naroffae4143e2007-04-26 20:39:23 +00005529 }
Chris Lattner08464942007-12-28 05:29:59 +00005530
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005531 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5532 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005533 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5534 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005535
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00005536 // Check for sentinels
5537 if (NDecl)
Dmitri Gribenko9c785c22013-05-09 21:02:07 +00005538 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
Mike Stump11289f42009-09-09 15:08:12 +00005539
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005540 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005541 if (FDecl) {
Richard Smith55ce3522012-06-25 20:30:08 +00005542 if (CheckFunctionCall(FDecl, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005543 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00005544
John McCallbebede42011-02-26 05:39:39 +00005545 if (BuiltinID)
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00005546 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005547 } else if (NDecl) {
Richard Trieu664c4c62013-06-20 21:03:13 +00005548 if (CheckPointerCall(NDecl, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005549 return ExprError();
Richard Trieu41bc0992013-06-22 00:20:41 +00005550 } else {
5551 if (CheckOtherCall(TheCall, Proto))
5552 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005553 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005554
John McCallb268a282010-08-23 23:25:46 +00005555 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00005556}
5557
John McCalldadc5752010-08-24 06:29:42 +00005558ExprResult
John McCallba7bf592010-08-24 05:47:05 +00005559Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00005560 SourceLocation RParenLoc, Expr *InitExpr) {
David Blaikie7d170102013-05-15 07:37:26 +00005561 assert(Ty && "ActOnCompoundLiteral(): missing type");
Davide Italiano99219622015-08-19 02:21:12 +00005562 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00005563
5564 TypeSourceInfo *TInfo;
5565 QualType literalType = GetTypeFromParser(Ty, &TInfo);
5566 if (!TInfo)
5567 TInfo = Context.getTrivialTypeSourceInfo(literalType);
5568
John McCallb268a282010-08-23 23:25:46 +00005569 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00005570}
5571
John McCalldadc5752010-08-24 06:29:42 +00005572ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00005573Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00005574 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00005575 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00005576
Eli Friedman37a186d2008-05-20 05:22:08 +00005577 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00005578 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005579 diag::err_illegal_decl_array_incomplete_type,
5580 SourceRange(LParenLoc,
5581 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00005582 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00005583 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005584 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuba63ce62011-09-09 01:45:06 +00005585 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00005586 } else if (!literalType->isDependentType() &&
5587 RequireCompleteType(LParenLoc, literalType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005588 diag::err_typecheck_decl_incomplete_type,
5589 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00005590 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00005591
Douglas Gregor85dabae2009-12-16 01:38:02 +00005592 InitializedEntity Entity
Jordan Rose6c0505e2013-05-06 16:48:12 +00005593 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005594 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00005595 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl0501c632012-02-12 16:37:36 +00005596 SourceRange(LParenLoc, RParenLoc),
5597 /*InitList=*/true);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005598 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005599 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5600 &literalType);
Eli Friedmana553d4a2009-12-22 02:35:53 +00005601 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005602 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00005603 LiteralExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00005604
John McCall96482882016-10-31 21:56:26 +00005605 bool isFileScope = !CurContext->isFunctionOrMethod();
Eli Friedman4a962f02013-10-01 00:28:29 +00005606 if (isFileScope &&
5607 !LiteralExpr->isTypeDependent() &&
5608 !LiteralExpr->isValueDependent() &&
5609 !literalType->isDependentType()) { // 6.5.2.5p3
Richard Trieuba63ce62011-09-09 01:45:06 +00005610 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00005611 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00005612 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00005613
John McCall7decc9e2010-11-18 06:31:45 +00005614 // In C, compound literals are l-values for some reason.
Richard Smithb3189a12016-12-05 07:49:14 +00005615 // For GCC compatibility, in C++, file-scope array compound literals with
5616 // constant initializers are also l-values, and compound literals are
5617 // otherwise prvalues.
5618 //
5619 // (GCC also treats C++ list-initialized file-scope array prvalues with
5620 // constant initializers as l-values, but that's non-conforming, so we don't
5621 // follow it there.)
5622 //
5623 // FIXME: It would be better to handle the lvalue cases as materializing and
5624 // lifetime-extending a temporary object, but our materialized temporaries
5625 // representation only supports lifetime extension from a variable, not "out
5626 // of thin air".
5627 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5628 // is bound to the result of applying array-to-pointer decay to the compound
5629 // literal.
5630 // FIXME: GCC supports compound literals of reference type, which should
5631 // obviously have a value kind derived from the kind of reference involved.
5632 ExprValueKind VK =
5633 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5634 ? VK_RValue
5635 : VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00005636
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00005637 return MaybeBindToTemporary(
Richard Smithb3189a12016-12-05 07:49:14 +00005638 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5639 VK, LiteralExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00005640}
5641
John McCalldadc5752010-08-24 06:29:42 +00005642ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00005643Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb5d49352009-01-19 22:31:54 +00005644 SourceLocation RBraceLoc) {
John McCall526ab472011-10-25 17:37:35 +00005645 // Immediately handle non-overload placeholders. Overloads can be
5646 // resolved contextually, but everything else here can't.
Benjamin Kramerc215e762012-08-24 11:54:20 +00005647 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5648 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5649 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
John McCall526ab472011-10-25 17:37:35 +00005650
5651 // Ignore failures; dropping the entire initializer list because
5652 // of one failure would be terrible for indexing/etc.
5653 if (result.isInvalid()) continue;
5654
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005655 InitArgList[I] = result.get();
John McCall526ab472011-10-25 17:37:35 +00005656 }
5657 }
5658
Steve Naroff30d242c2007-09-15 18:49:24 +00005659 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00005660 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005661
Benjamin Kramerc215e762012-08-24 11:54:20 +00005662 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5663 RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005664 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005665 return E;
Steve Narofffbd09832007-07-19 01:06:55 +00005666}
5667
John McCallcd78e802011-09-10 01:16:55 +00005668/// Do an explicit extend of the given block pointer if we're in ARC.
Douglas Gregore83b9562015-07-07 03:57:53 +00005669void Sema::maybeExtendBlockObject(ExprResult &E) {
John McCallcd78e802011-09-10 01:16:55 +00005670 assert(E.get()->getType()->isBlockPointerType());
5671 assert(E.get()->isRValue());
5672
5673 // Only do this in an r-value context.
Douglas Gregore83b9562015-07-07 03:57:53 +00005674 if (!getLangOpts().ObjCAutoRefCount) return;
John McCallcd78e802011-09-10 01:16:55 +00005675
Douglas Gregore83b9562015-07-07 03:57:53 +00005676 E = ImplicitCastExpr::Create(Context, E.get()->getType(),
John McCall2d637d22011-09-10 06:18:15 +00005677 CK_ARCExtendBlockObject, E.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005678 /*base path*/ nullptr, VK_RValue);
Tim Shen4a05bb82016-06-21 20:29:17 +00005679 Cleanup.setExprNeedsCleanups(true);
John McCallcd78e802011-09-10 01:16:55 +00005680}
5681
5682/// Prepare a conversion of the given expression to an ObjC object
5683/// pointer type.
5684CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5685 QualType type = E.get()->getType();
5686 if (type->isObjCObjectPointerType()) {
5687 return CK_BitCast;
5688 } else if (type->isBlockPointerType()) {
Douglas Gregore83b9562015-07-07 03:57:53 +00005689 maybeExtendBlockObject(E);
John McCallcd78e802011-09-10 01:16:55 +00005690 return CK_BlockPointerToObjCPointerCast;
5691 } else {
5692 assert(type->isPointerType());
5693 return CK_CPointerToObjCPointerCast;
5694 }
5695}
5696
John McCalld7646252010-11-14 08:17:51 +00005697/// Prepares for a scalar cast, performing all the necessary stages
5698/// except the final cast and returning the kind required.
John McCall9776e432011-10-06 23:25:11 +00005699CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00005700 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5701 // Also, callers should have filtered out the invalid cases with
5702 // pointers. Everything else should be possible.
5703
John Wiegley01296292011-04-08 18:41:53 +00005704 QualType SrcTy = Src.get()->getType();
John McCall9776e432011-10-06 23:25:11 +00005705 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00005706 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00005707
John McCall9320b872011-09-09 05:25:32 +00005708 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00005709 case Type::STK_MemberPointer:
5710 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00005711
John McCall9320b872011-09-09 05:25:32 +00005712 case Type::STK_CPointer:
5713 case Type::STK_BlockPointer:
5714 case Type::STK_ObjCObjectPointer:
John McCall8cb679e2010-11-15 09:13:47 +00005715 switch (DestTy->getScalarTypeKind()) {
David Tweede1468322013-12-11 13:39:46 +00005716 case Type::STK_CPointer: {
5717 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5718 unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5719 if (SrcAS != DestAS)
5720 return CK_AddressSpaceConversion;
John McCall9320b872011-09-09 05:25:32 +00005721 return CK_BitCast;
David Tweede1468322013-12-11 13:39:46 +00005722 }
John McCall9320b872011-09-09 05:25:32 +00005723 case Type::STK_BlockPointer:
5724 return (SrcKind == Type::STK_BlockPointer
5725 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5726 case Type::STK_ObjCObjectPointer:
5727 if (SrcKind == Type::STK_ObjCObjectPointer)
5728 return CK_BitCast;
David Blaikie8a40f702012-01-17 06:56:22 +00005729 if (SrcKind == Type::STK_CPointer)
John McCall9320b872011-09-09 05:25:32 +00005730 return CK_CPointerToObjCPointerCast;
Douglas Gregore83b9562015-07-07 03:57:53 +00005731 maybeExtendBlockObject(Src);
David Blaikie8a40f702012-01-17 06:56:22 +00005732 return CK_BlockPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00005733 case Type::STK_Bool:
5734 return CK_PointerToBoolean;
5735 case Type::STK_Integral:
5736 return CK_PointerToIntegral;
5737 case Type::STK_Floating:
5738 case Type::STK_FloatingComplex:
5739 case Type::STK_IntegralComplex:
5740 case Type::STK_MemberPointer:
5741 llvm_unreachable("illegal cast from pointer");
5742 }
David Blaikie8a40f702012-01-17 06:56:22 +00005743 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005744
John McCall8cb679e2010-11-15 09:13:47 +00005745 case Type::STK_Bool: // casting from bool is like casting from an integer
5746 case Type::STK_Integral:
5747 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00005748 case Type::STK_CPointer:
5749 case Type::STK_ObjCObjectPointer:
5750 case Type::STK_BlockPointer:
John McCall9776e432011-10-06 23:25:11 +00005751 if (Src.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005752 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00005753 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00005754 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005755 case Type::STK_Bool:
5756 return CK_IntegralToBoolean;
5757 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00005758 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00005759 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00005760 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00005761 case Type::STK_IntegralComplex:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005762 Src = ImpCastExprToType(Src.get(),
George Burgess IV45461812015-10-11 20:13:20 +00005763 DestTy->castAs<ComplexType>()->getElementType(),
5764 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00005765 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005766 case Type::STK_FloatingComplex:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005767 Src = ImpCastExprToType(Src.get(),
George Burgess IV45461812015-10-11 20:13:20 +00005768 DestTy->castAs<ComplexType>()->getElementType(),
5769 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00005770 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005771 case Type::STK_MemberPointer:
5772 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005773 }
David Blaikie8a40f702012-01-17 06:56:22 +00005774 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005775
John McCall8cb679e2010-11-15 09:13:47 +00005776 case Type::STK_Floating:
5777 switch (DestTy->getScalarTypeKind()) {
5778 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00005779 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00005780 case Type::STK_Bool:
5781 return CK_FloatingToBoolean;
5782 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00005783 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00005784 case Type::STK_FloatingComplex:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005785 Src = ImpCastExprToType(Src.get(),
John McCall9776e432011-10-06 23:25:11 +00005786 DestTy->castAs<ComplexType>()->getElementType(),
5787 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00005788 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005789 case Type::STK_IntegralComplex:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005790 Src = ImpCastExprToType(Src.get(),
John McCall9776e432011-10-06 23:25:11 +00005791 DestTy->castAs<ComplexType>()->getElementType(),
5792 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00005793 return CK_IntegralRealToComplex;
John McCall9320b872011-09-09 05:25:32 +00005794 case Type::STK_CPointer:
5795 case Type::STK_ObjCObjectPointer:
5796 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00005797 llvm_unreachable("valid float->pointer cast?");
5798 case Type::STK_MemberPointer:
5799 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005800 }
David Blaikie8a40f702012-01-17 06:56:22 +00005801 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00005802
John McCall8cb679e2010-11-15 09:13:47 +00005803 case Type::STK_FloatingComplex:
5804 switch (DestTy->getScalarTypeKind()) {
5805 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00005806 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00005807 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00005808 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00005809 case Type::STK_Floating: {
John McCall9776e432011-10-06 23:25:11 +00005810 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5811 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00005812 return CK_FloatingComplexToReal;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005813 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00005814 return CK_FloatingCast;
5815 }
John McCall8cb679e2010-11-15 09:13:47 +00005816 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00005817 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00005818 case Type::STK_Integral:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005819 Src = ImpCastExprToType(Src.get(),
John McCall9776e432011-10-06 23:25:11 +00005820 SrcTy->castAs<ComplexType>()->getElementType(),
5821 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00005822 return CK_FloatingToIntegral;
John McCall9320b872011-09-09 05:25:32 +00005823 case Type::STK_CPointer:
5824 case Type::STK_ObjCObjectPointer:
5825 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00005826 llvm_unreachable("valid complex float->pointer cast?");
5827 case Type::STK_MemberPointer:
5828 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005829 }
David Blaikie8a40f702012-01-17 06:56:22 +00005830 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00005831
John McCall8cb679e2010-11-15 09:13:47 +00005832 case Type::STK_IntegralComplex:
5833 switch (DestTy->getScalarTypeKind()) {
5834 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00005835 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005836 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00005837 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00005838 case Type::STK_Integral: {
John McCall9776e432011-10-06 23:25:11 +00005839 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5840 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00005841 return CK_IntegralComplexToReal;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005842 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00005843 return CK_IntegralCast;
5844 }
John McCall8cb679e2010-11-15 09:13:47 +00005845 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00005846 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00005847 case Type::STK_Floating:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005848 Src = ImpCastExprToType(Src.get(),
John McCall9776e432011-10-06 23:25:11 +00005849 SrcTy->castAs<ComplexType>()->getElementType(),
5850 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00005851 return CK_IntegralToFloating;
John McCall9320b872011-09-09 05:25:32 +00005852 case Type::STK_CPointer:
5853 case Type::STK_ObjCObjectPointer:
5854 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00005855 llvm_unreachable("valid complex int->pointer cast?");
5856 case Type::STK_MemberPointer:
5857 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005858 }
David Blaikie8a40f702012-01-17 06:56:22 +00005859 llvm_unreachable("Should have returned before this");
Anders Carlsson094c4592009-10-18 18:12:03 +00005860 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005861
John McCalld7646252010-11-14 08:17:51 +00005862 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson094c4592009-10-18 18:12:03 +00005863}
5864
Fariborz Jahanian328a7c42014-03-06 22:47:09 +00005865static bool breakDownVectorType(QualType type, uint64_t &len,
5866 QualType &eltType) {
5867 // Vectors are simple.
5868 if (const VectorType *vecType = type->getAs<VectorType>()) {
5869 len = vecType->getNumElements();
5870 eltType = vecType->getElementType();
5871 assert(eltType->isScalarType());
5872 return true;
5873 }
5874
5875 // We allow lax conversion to and from non-vector types, but only if
5876 // they're real types (i.e. non-complex, non-pointer scalar types).
5877 if (!type->isRealType()) return false;
5878
5879 len = 1;
5880 eltType = type;
5881 return true;
5882}
5883
John McCall1c78f082015-07-23 23:54:07 +00005884/// Are the two types lax-compatible vector types? That is, given
5885/// that one of them is a vector, do they have equal storage sizes,
5886/// where the storage size is the number of elements times the element
5887/// size?
5888///
5889/// This will also return false if either of the types is neither a
5890/// vector nor a real type.
5891bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5892 assert(destTy->isVectorType() || srcTy->isVectorType());
Stephen Canonca8eefd2015-09-15 00:21:56 +00005893
5894 // Disallow lax conversions between scalars and ExtVectors (these
5895 // conversions are allowed for other vector types because common headers
5896 // depend on them). Most scalar OP ExtVector cases are handled by the
5897 // splat path anyway, which does what we want (convert, not bitcast).
5898 // What this rules out for ExtVectors is crazy things like char4*float.
5899 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5900 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
John McCall1c78f082015-07-23 23:54:07 +00005901
Fariborz Jahanian328a7c42014-03-06 22:47:09 +00005902 uint64_t srcLen, destLen;
Vedant Kumar55c21442015-10-09 01:47:26 +00005903 QualType srcEltTy, destEltTy;
5904 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5905 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
Fariborz Jahanian328a7c42014-03-06 22:47:09 +00005906
5907 // ASTContext::getTypeSize will return the size rounded up to a
5908 // power of 2, so instead of using that, we need to use the raw
5909 // element size multiplied by the element count.
Vedant Kumar55c21442015-10-09 01:47:26 +00005910 uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5911 uint64_t destEltSize = Context.getTypeSize(destEltTy);
Fariborz Jahanian328a7c42014-03-06 22:47:09 +00005912
5913 return (srcLen * srcEltSize == destLen * destEltSize);
5914}
5915
John McCall1c78f082015-07-23 23:54:07 +00005916/// Is this a legal conversion between two types, one of which is
5917/// known to be a vector type?
Fariborz Jahanian328a7c42014-03-06 22:47:09 +00005918bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5919 assert(destTy->isVectorType() || srcTy->isVectorType());
5920
5921 if (!Context.getLangOpts().LaxVectorConversions)
5922 return false;
John McCall1c78f082015-07-23 23:54:07 +00005923 return areLaxCompatibleVectorTypes(srcTy, destTy);
Fariborz Jahanian328a7c42014-03-06 22:47:09 +00005924}
5925
Anders Carlsson525b76b2009-10-16 02:48:28 +00005926bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00005927 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00005928 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005929
John McCall1c78f082015-07-23 23:54:07 +00005930 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5931 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
Anders Carlssonde71adf2007-11-27 05:51:55 +00005932 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00005933 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00005934 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00005935 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005936 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005937 } else
5938 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00005939 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005940 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005941
John McCalle3027922010-08-25 11:45:40 +00005942 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005943 return false;
5944}
5945
George Burgess IVdf1ed002016-01-13 01:52:39 +00005946ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5947 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5948
5949 if (DestElemTy == SplattedExpr->getType())
5950 return SplattedExpr;
5951
5952 assert(DestElemTy->isFloatingType() ||
5953 DestElemTy->isIntegralOrEnumerationType());
5954
5955 CastKind CK;
5956 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5957 // OpenCL requires that we convert `true` boolean expressions to -1, but
5958 // only when splatting vectors.
5959 if (DestElemTy->isFloatingType()) {
5960 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5961 // in two steps: boolean to signed integral, then to floating.
5962 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5963 CK_BooleanToSignedIntegral);
5964 SplattedExpr = CastExprRes.get();
5965 CK = CK_IntegralToFloating;
5966 } else {
5967 CK = CK_BooleanToSignedIntegral;
5968 }
5969 } else {
5970 ExprResult CastExprRes = SplattedExpr;
5971 CK = PrepareScalarCast(CastExprRes, DestElemTy);
5972 if (CastExprRes.isInvalid())
5973 return ExprError();
5974 SplattedExpr = CastExprRes.get();
5975 }
5976 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
5977}
5978
John Wiegley01296292011-04-08 18:41:53 +00005979ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5980 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00005981 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005982
Anders Carlsson43d70f82009-10-16 05:23:41 +00005983 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005984
Nate Begemanc8961a42009-06-27 22:05:55 +00005985 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5986 // an ExtVectorType.
Tobias Grosser766bcc22011-09-22 13:03:14 +00005987 // In OpenCL, casts between vectors of different types are not allowed.
5988 // (See OpenCL 6.2).
Nate Begemanc69b7402009-06-26 00:50:28 +00005989 if (SrcTy->isVectorType()) {
John McCall1c78f082015-07-23 23:54:07 +00005990 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
David Blaikiebbafb8a2012-03-11 07:00:24 +00005991 || (getLangOpts().OpenCL &&
Tobias Grosser766bcc22011-09-22 13:03:14 +00005992 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005993 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00005994 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00005995 return ExprError();
5996 }
John McCalle3027922010-08-25 11:45:40 +00005997 Kind = CK_BitCast;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005998 return CastExpr;
Nate Begemanc69b7402009-06-26 00:50:28 +00005999 }
6000
Nate Begemanbd956c42009-06-28 02:36:38 +00006001 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00006002 // conversion will take place first from scalar to elt type, and then
6003 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00006004 if (SrcTy->isPointerType())
6005 return Diag(R.getBegin(),
6006 diag::err_invalid_conversion_between_vector_and_scalar)
6007 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00006008
John McCalle3027922010-08-25 11:45:40 +00006009 Kind = CK_VectorSplat;
George Burgess IVdf1ed002016-01-13 01:52:39 +00006010 return prepareVectorSplat(DestTy, CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00006011}
6012
John McCalldadc5752010-08-24 06:29:42 +00006013ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00006014Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6015 Declarator &D, ParsedType &Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00006016 SourceLocation RParenLoc, Expr *CastExpr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006017 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00006018 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00006019
Richard Trieuba63ce62011-09-09 01:45:06 +00006020 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00006021 if (D.isInvalidType())
6022 return ExprError();
6023
David Blaikiebbafb8a2012-03-11 07:00:24 +00006024 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00006025 // Check that there are no default arguments (C++ only).
6026 CheckExtraCXXDefaultArguments(D);
Kaelyn Takata13da33f2014-11-24 21:46:59 +00006027 } else {
6028 // Make sure any TypoExprs have been dealt with.
6029 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6030 if (!Res.isUsable())
6031 return ExprError();
6032 CastExpr = Res.get();
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00006033 }
6034
John McCall42856de2011-10-01 05:17:03 +00006035 checkUnusedDeclAttributes(D);
6036
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00006037 QualType castType = castTInfo->getType();
6038 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00006039
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00006040 bool isVectorLiteral = false;
6041
6042 // Check for an altivec or OpenCL literal,
6043 // i.e. all the elements are integer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00006044 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6045 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00006046 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
Tobias Grosser0a3a22f2011-09-21 18:28:29 +00006047 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00006048 if (PLE && PLE->getNumExprs() == 0) {
6049 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6050 return ExprError();
6051 }
6052 if (PE || PLE->getNumExprs() == 1) {
6053 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6054 if (!E->getType()->isVectorType())
6055 isVectorLiteral = true;
6056 }
6057 else
6058 isVectorLiteral = true;
6059 }
6060
6061 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6062 // then handle it as such.
6063 if (isVectorLiteral)
Richard Trieuba63ce62011-09-09 01:45:06 +00006064 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00006065
Nate Begeman5ec4b312009-08-10 23:49:36 +00006066 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00006067 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6068 // sequence of BinOp comma operators.
Richard Trieuba63ce62011-09-09 01:45:06 +00006069 if (isa<ParenListExpr>(CastExpr)) {
6070 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00006071 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006072 CastExpr = Result.get();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00006073 }
John McCallebe54742010-01-15 18:56:44 +00006074
Alp Toker15ab3732013-12-12 12:47:48 +00006075 if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6076 !getSourceManager().isInSystemMacro(LParenLoc))
6077 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00006078
6079 CheckTollFreeBridgeCast(castType, CastExpr);
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00006080
6081 CheckObjCBridgeRelatedCast(castType, CastExpr);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00006082
6083 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6084
Richard Trieuba63ce62011-09-09 01:45:06 +00006085 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallebe54742010-01-15 18:56:44 +00006086}
6087
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00006088ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6089 SourceLocation RParenLoc, Expr *E,
6090 TypeSourceInfo *TInfo) {
6091 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6092 "Expected paren or paren list expression");
6093
6094 Expr **exprs;
6095 unsigned numExprs;
6096 Expr *subExpr;
Richard Smith9ca91012013-02-05 05:55:57 +00006097 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00006098 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
Richard Smith9ca91012013-02-05 05:55:57 +00006099 LiteralLParenLoc = PE->getLParenLoc();
6100 LiteralRParenLoc = PE->getRParenLoc();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00006101 exprs = PE->getExprs();
6102 numExprs = PE->getNumExprs();
Richard Smith9ca91012013-02-05 05:55:57 +00006103 } else { // isa<ParenExpr> by assertion at function entrance
6104 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6105 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00006106 subExpr = cast<ParenExpr>(E)->getSubExpr();
6107 exprs = &subExpr;
6108 numExprs = 1;
6109 }
6110
6111 QualType Ty = TInfo->getType();
6112 assert(Ty->isVectorType() && "Expected vector type");
6113
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006114 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00006115 const VectorType *VTy = Ty->getAs<VectorType>();
6116 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6117
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00006118 // '(...)' form of vector initialization in AltiVec: the number of
6119 // initializers must be one or must match the size of the vector.
6120 // If a single value is specified in the initializer then it will be
6121 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00006122 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00006123 // The number of initializers must be one or must match the size of the
6124 // vector. If a single value is specified in the initializer then it will
6125 // be replicated to all the components of the vector
6126 if (numExprs == 1) {
6127 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00006128 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6129 if (Literal.isInvalid())
6130 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006131 Literal = ImpCastExprToType(Literal.get(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00006132 PrepareScalarCast(Literal, ElemTy));
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006133 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00006134 }
6135 else if (numExprs < numElems) {
6136 Diag(E->getExprLoc(),
6137 diag::err_incorrect_number_of_vector_initializers);
6138 return ExprError();
6139 }
6140 else
Benjamin Kramer8001f742012-02-14 12:06:21 +00006141 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00006142 }
Tanya Lattner83559382011-07-15 23:07:01 +00006143 else {
6144 // For OpenCL, when the number of initializers is a single value,
6145 // it will be replicated to all components of the vector.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006146 if (getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +00006147 VTy->getVectorKind() == VectorType::GenericVector &&
6148 numExprs == 1) {
6149 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00006150 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6151 if (Literal.isInvalid())
6152 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006153 Literal = ImpCastExprToType(Literal.get(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00006154 PrepareScalarCast(Literal, ElemTy));
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006155 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
Tanya Lattner83559382011-07-15 23:07:01 +00006156 }
6157
Benjamin Kramer8001f742012-02-14 12:06:21 +00006158 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner83559382011-07-15 23:07:01 +00006159 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00006160 // FIXME: This means that pretty-printing the final AST will produce curly
6161 // braces instead of the original commas.
Richard Smith9ca91012013-02-05 05:55:57 +00006162 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6163 initExprs, LiteralRParenLoc);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00006164 initE->setType(Ty);
6165 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6166}
6167
Sebastian Redla9351792012-02-11 23:51:47 +00006168/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6169/// the ParenListExpr into a sequence of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00006170ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00006171Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6172 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00006173 if (!E)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006174 return OrigExpr;
Mike Stump11289f42009-09-09 15:08:12 +00006175
John McCalldadc5752010-08-24 06:29:42 +00006176 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00006177
Nate Begeman5ec4b312009-08-10 23:49:36 +00006178 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00006179 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6180 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00006181
John McCallb268a282010-08-23 23:25:46 +00006182 if (Result.isInvalid()) return ExprError();
6183
6184 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00006185}
6186
Sebastian Redla9351792012-02-11 23:51:47 +00006187ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6188 SourceLocation R,
6189 MultiExprArg Val) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00006190 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006191 return expr;
Nate Begeman5ec4b312009-08-10 23:49:36 +00006192}
6193
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00006194/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006195/// constant and the other is not a pointer. Returns true if a diagnostic is
6196/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00006197bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00006198 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00006199 Expr *NullExpr = LHSExpr;
6200 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00006201 Expr::NullPointerConstantKind NullKind =
6202 NullExpr->isNullPointerConstant(Context,
6203 Expr::NPC_ValueDependentIsNotNull);
6204
6205 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00006206 NullExpr = RHSExpr;
6207 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00006208 NullKind =
6209 NullExpr->isNullPointerConstant(Context,
6210 Expr::NPC_ValueDependentIsNotNull);
6211 }
6212
6213 if (NullKind == Expr::NPCK_NotNull)
6214 return false;
6215
David Blaikie1c7c8f72012-08-08 17:33:31 +00006216 if (NullKind == Expr::NPCK_ZeroExpression)
6217 return false;
6218
6219 if (NullKind == Expr::NPCK_ZeroLiteral) {
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00006220 // In this case, check to make sure that we got here from a "NULL"
6221 // string in the source code.
6222 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00006223 SourceLocation loc = NullExpr->getExprLoc();
6224 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00006225 return false;
6226 }
6227
Richard Smith89645bc2013-01-02 12:01:23 +00006228 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00006229 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6230 << NonPointerExpr->getType() << DiagType
6231 << NonPointerExpr->getSourceRange();
6232 return true;
6233}
6234
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006235/// \brief Return false if the condition expression is valid, true otherwise.
Sameer Sahasrabuddhee8d2aaf2015-02-04 06:38:18 +00006236static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006237 QualType CondTy = Cond->getType();
6238
Sameer Sahasrabuddhee8d2aaf2015-02-04 06:38:18 +00006239 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6240 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6241 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6242 << CondTy << Cond->getSourceRange();
6243 return true;
6244 }
6245
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006246 // C99 6.5.15p2
6247 if (CondTy->isScalarType()) return false;
6248
Sameer Sahasrabuddhee8d2aaf2015-02-04 06:38:18 +00006249 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6250 << CondTy << Cond->getSourceRange();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006251 return true;
6252}
6253
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006254/// \brief Handle when one or both operands are void type.
6255static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6256 ExprResult &RHS) {
6257 Expr *LHSExpr = LHS.get();
6258 Expr *RHSExpr = RHS.get();
6259
6260 if (!LHSExpr->getType()->isVoidType())
6261 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6262 << RHSExpr->getSourceRange();
6263 if (!RHSExpr->getType()->isVoidType())
6264 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6265 << LHSExpr->getSourceRange();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006266 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6267 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006268 return S.Context.VoidTy;
6269}
6270
6271/// \brief Return false if the NullExpr can be promoted to PointerTy,
6272/// true otherwise.
6273static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6274 QualType PointerTy) {
6275 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6276 !NullExpr.get()->isNullPointerConstant(S.Context,
6277 Expr::NPC_ValueDependentIsNull))
6278 return true;
6279
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006280 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006281 return false;
6282}
6283
6284/// \brief Checks compatibility between two pointers and return the resulting
6285/// type.
6286static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6287 ExprResult &RHS,
6288 SourceLocation Loc) {
6289 QualType LHSTy = LHS.get()->getType();
6290 QualType RHSTy = RHS.get()->getType();
6291
6292 if (S.Context.hasSameType(LHSTy, RHSTy)) {
6293 // Two identical pointers types are always compatible.
6294 return LHSTy;
6295 }
6296
6297 QualType lhptee, rhptee;
6298
6299 // Get the pointee types.
Fariborz Jahanian1edacec2013-06-07 16:07:38 +00006300 bool IsBlockPointer = false;
John McCall9320b872011-09-09 05:25:32 +00006301 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6302 lhptee = LHSBTy->getPointeeType();
6303 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanian1edacec2013-06-07 16:07:38 +00006304 IsBlockPointer = true;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006305 } else {
John McCall9320b872011-09-09 05:25:32 +00006306 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6307 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006308 }
6309
Eli Friedman57a75392012-04-05 22:30:04 +00006310 // C99 6.5.15p6: If both operands are pointers to compatible types or to
6311 // differently qualified versions of compatible types, the result type is
6312 // a pointer to an appropriately qualified version of the composite
6313 // type.
6314
6315 // Only CVR-qualifiers exist in the standard, and the differently-qualified
6316 // clause doesn't make sense for our extensions. E.g. address space 2 should
6317 // be incompatible with address space 3: they may live on different devices or
6318 // anything.
6319 Qualifiers lhQual = lhptee.getQualifiers();
6320 Qualifiers rhQual = rhptee.getQualifiers();
6321
6322 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6323 lhQual.removeCVRQualifiers();
6324 rhQual.removeCVRQualifiers();
6325
6326 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6327 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6328
Yaxun Liua1a87ad2016-04-12 19:43:36 +00006329 // For OpenCL:
6330 // 1. If LHS and RHS types match exactly and:
6331 // (a) AS match => use standard C rules, no bitcast or addrspacecast
6332 // (b) AS overlap => generate addrspacecast
6333 // (c) AS don't overlap => give an error
6334 // 2. if LHS and RHS types don't match:
6335 // (a) AS match => use standard C rules, generate bitcast
6336 // (b) AS overlap => generate addrspacecast instead of bitcast
6337 // (c) AS don't overlap => give an error
6338
6339 // For OpenCL, non-null composite type is returned only for cases 1a and 1b.
Eli Friedman57a75392012-04-05 22:30:04 +00006340 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6341
Yaxun Liua1a87ad2016-04-12 19:43:36 +00006342 // OpenCL cases 1c, 2a, 2b, and 2c.
Eli Friedman57a75392012-04-05 22:30:04 +00006343 if (CompositeTy.isNull()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006344 // In this situation, we assume void* type. No especially good
6345 // reason, but this is what gcc does, and we do have to pick
6346 // to get a consistent AST.
Yaxun Liua1a87ad2016-04-12 19:43:36 +00006347 QualType incompatTy;
6348 if (S.getLangOpts().OpenCL) {
6349 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6350 // spaces is disallowed.
6351 unsigned ResultAddrSpace;
6352 if (lhQual.isAddressSpaceSupersetOf(rhQual)) {
6353 // Cases 2a and 2b.
6354 ResultAddrSpace = lhQual.getAddressSpace();
6355 } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) {
6356 // Cases 2a and 2b.
6357 ResultAddrSpace = rhQual.getAddressSpace();
6358 } else {
6359 // Cases 1c and 2c.
6360 S.Diag(Loc,
6361 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6362 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6363 << RHS.get()->getSourceRange();
6364 return QualType();
6365 }
6366
6367 // Continue handling cases 2a and 2b.
6368 incompatTy = S.Context.getPointerType(
6369 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6370 LHS = S.ImpCastExprToType(LHS.get(), incompatTy,
6371 (lhQual.getAddressSpace() != ResultAddrSpace)
6372 ? CK_AddressSpaceConversion /* 2b */
6373 : CK_BitCast /* 2a */);
6374 RHS = S.ImpCastExprToType(RHS.get(), incompatTy,
6375 (rhQual.getAddressSpace() != ResultAddrSpace)
6376 ? CK_AddressSpaceConversion /* 2b */
6377 : CK_BitCast /* 2a */);
6378 } else {
6379 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6380 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6381 << RHS.get()->getSourceRange();
6382 incompatTy = S.Context.getPointerType(S.Context.VoidTy);
6383 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6384 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6385 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006386 return incompatTy;
6387 }
6388
6389 // The pointer types are compatible.
Eli Friedman57a75392012-04-05 22:30:04 +00006390 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
Yaxun Liua1a87ad2016-04-12 19:43:36 +00006391 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
Fariborz Jahanian1edacec2013-06-07 16:07:38 +00006392 if (IsBlockPointer)
Fariborz Jahanian44d23b82013-06-07 00:48:14 +00006393 ResultTy = S.Context.getBlockPointerType(ResultTy);
Yaxun Liua1a87ad2016-04-12 19:43:36 +00006394 else {
6395 // Cases 1a and 1b for OpenCL.
6396 auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace();
6397 LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace
6398 ? CK_BitCast /* 1a */
6399 : CK_AddressSpaceConversion /* 1b */;
6400 RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace
6401 ? CK_BitCast /* 1a */
6402 : CK_AddressSpaceConversion /* 1b */;
Fariborz Jahanian44d23b82013-06-07 00:48:14 +00006403 ResultTy = S.Context.getPointerType(ResultTy);
Yaxun Liua1a87ad2016-04-12 19:43:36 +00006404 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006405
Yaxun Liua1a87ad2016-04-12 19:43:36 +00006406 // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast
6407 // if the target type does not change.
6408 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6409 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
Eli Friedman57a75392012-04-05 22:30:04 +00006410 return ResultTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006411}
6412
6413/// \brief Return the resulting type when the operands are both block pointers.
6414static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6415 ExprResult &LHS,
6416 ExprResult &RHS,
6417 SourceLocation Loc) {
6418 QualType LHSTy = LHS.get()->getType();
6419 QualType RHSTy = RHS.get()->getType();
6420
6421 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6422 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6423 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006424 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6425 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006426 return destType;
6427 }
6428 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6429 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6430 << RHS.get()->getSourceRange();
6431 return QualType();
6432 }
6433
6434 // We have 2 block pointer types.
6435 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6436}
6437
6438/// \brief Return the resulting type when the operands are both pointers.
6439static QualType
6440checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6441 ExprResult &RHS,
6442 SourceLocation Loc) {
6443 // get the pointer types
6444 QualType LHSTy = LHS.get()->getType();
6445 QualType RHSTy = RHS.get()->getType();
6446
6447 // get the "pointed to" types
6448 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6449 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6450
6451 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6452 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6453 // Figure out necessary qualifiers (C99 6.5.15p6)
6454 QualType destPointee
6455 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6456 QualType destType = S.Context.getPointerType(destPointee);
6457 // Add qualifiers if necessary.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006458 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006459 // Promote to void*.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006460 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006461 return destType;
6462 }
6463 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6464 QualType destPointee
6465 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6466 QualType destType = S.Context.getPointerType(destPointee);
6467 // Add qualifiers if necessary.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006468 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006469 // Promote to void*.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006470 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006471 return destType;
6472 }
6473
6474 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6475}
6476
6477/// \brief Return false if the first expression is not an integer and the second
6478/// expression is not a pointer, true otherwise.
6479static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6480 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006481 bool IsIntFirstExpr) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006482 if (!PointerExpr->getType()->isPointerType() ||
6483 !Int.get()->getType()->isIntegerType())
6484 return false;
6485
Richard Trieuba63ce62011-09-09 01:45:06 +00006486 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6487 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006488
Richard Smith1b98ccc2014-07-19 01:39:17 +00006489 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006490 << Expr1->getType() << Expr2->getType()
6491 << Expr1->getSourceRange() << Expr2->getSourceRange();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006492 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006493 CK_IntegralToPointer);
6494 return true;
6495}
6496
Sameer Sahasrabuddhee8d2aaf2015-02-04 06:38:18 +00006497/// \brief Simple conversion between integer and floating point types.
6498///
6499/// Used when handling the OpenCL conditional operator where the
6500/// condition is a vector while the other operands are scalar.
6501///
6502/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6503/// types are either integer or floating type. Between the two
6504/// operands, the type with the higher rank is defined as the "result
6505/// type". The other operand needs to be promoted to the same type. No
6506/// other type promotion is allowed. We cannot use
6507/// UsualArithmeticConversions() for this purpose, since it always
6508/// promotes promotable types.
6509static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6510 ExprResult &RHS,
6511 SourceLocation QuestionLoc) {
6512 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6513 if (LHS.isInvalid())
6514 return QualType();
6515 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6516 if (RHS.isInvalid())
6517 return QualType();
6518
6519 // For conversion purposes, we ignore any qualifiers.
6520 // For example, "const float" and "float" are equivalent.
6521 QualType LHSType =
6522 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6523 QualType RHSType =
6524 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6525
6526 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6527 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6528 << LHSType << LHS.get()->getSourceRange();
6529 return QualType();
6530 }
6531
6532 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6533 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6534 << RHSType << RHS.get()->getSourceRange();
6535 return QualType();
6536 }
6537
6538 // If both types are identical, no conversion is needed.
6539 if (LHSType == RHSType)
6540 return LHSType;
6541
6542 // Now handle "real" floating types (i.e. float, double, long double).
6543 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6544 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6545 /*IsCompAssign = */ false);
6546
6547 // Finally, we have two differing integer types.
6548 return handleIntegerConversion<doIntegralCast, doIntegralCast>
6549 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6550}
6551
6552/// \brief Convert scalar operands to a vector that matches the
6553/// condition in length.
6554///
6555/// Used when handling the OpenCL conditional operator where the
6556/// condition is a vector while the other operands are scalar.
6557///
6558/// We first compute the "result type" for the scalar operands
6559/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6560/// into a vector of that type where the length matches the condition
6561/// vector type. s6.11.6 requires that the element types of the result
6562/// and the condition must have the same number of bits.
6563static QualType
6564OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6565 QualType CondTy, SourceLocation QuestionLoc) {
6566 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6567 if (ResTy.isNull()) return QualType();
6568
6569 const VectorType *CV = CondTy->getAs<VectorType>();
6570 assert(CV);
6571
6572 // Determine the vector result type
6573 unsigned NumElements = CV->getNumElements();
6574 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6575
6576 // Ensure that all types have the same number of bits
6577 if (S.Context.getTypeSize(CV->getElementType())
6578 != S.Context.getTypeSize(ResTy)) {
6579 // Since VectorTy is created internally, it does not pretty print
6580 // with an OpenCL name. Instead, we just print a description.
6581 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6582 SmallString<64> Str;
6583 llvm::raw_svector_ostream OS(Str);
6584 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6585 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6586 << CondTy << OS.str();
6587 return QualType();
6588 }
6589
6590 // Convert operands to the vector result type
6591 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6592 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6593
6594 return VectorTy;
6595}
6596
6597/// \brief Return false if this is a valid OpenCL condition vector
6598static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6599 SourceLocation QuestionLoc) {
6600 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6601 // integral type.
6602 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6603 assert(CondTy);
6604 QualType EleTy = CondTy->getElementType();
6605 if (EleTy->isIntegerType()) return false;
6606
6607 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6608 << Cond->getType() << Cond->getSourceRange();
6609 return true;
6610}
6611
6612/// \brief Return false if the vector condition type and the vector
6613/// result type are compatible.
6614///
6615/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6616/// number of elements, and their element types have the same number
6617/// of bits.
6618static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6619 SourceLocation QuestionLoc) {
6620 const VectorType *CV = CondTy->getAs<VectorType>();
6621 const VectorType *RV = VecResTy->getAs<VectorType>();
6622 assert(CV && RV);
6623
6624 if (CV->getNumElements() != RV->getNumElements()) {
6625 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6626 << CondTy << VecResTy;
6627 return true;
6628 }
6629
6630 QualType CVE = CV->getElementType();
6631 QualType RVE = RV->getElementType();
6632
6633 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6634 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6635 << CondTy << VecResTy;
6636 return true;
6637 }
6638
6639 return false;
6640}
6641
6642/// \brief Return the resulting type for the conditional operator in
6643/// OpenCL (aka "ternary selection operator", OpenCL v1.1
6644/// s6.3.i) when the condition is a vector type.
6645static QualType
6646OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6647 ExprResult &LHS, ExprResult &RHS,
6648 SourceLocation QuestionLoc) {
6649 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6650 if (Cond.isInvalid())
6651 return QualType();
6652 QualType CondTy = Cond.get()->getType();
6653
6654 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6655 return QualType();
6656
6657 // If either operand is a vector then find the vector type of the
6658 // result as specified in OpenCL v1.1 s6.3.i.
6659 if (LHS.get()->getType()->isVectorType() ||
6660 RHS.get()->getType()->isVectorType()) {
6661 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00006662 /*isCompAssign*/false,
6663 /*AllowBothBool*/true,
6664 /*AllowBoolConversions*/false);
Sameer Sahasrabuddhee8d2aaf2015-02-04 06:38:18 +00006665 if (VecResTy.isNull()) return QualType();
6666 // The result type must match the condition type as specified in
6667 // OpenCL v1.1 s6.11.6.
6668 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6669 return QualType();
6670 return VecResTy;
6671 }
6672
6673 // Both operands are scalar.
6674 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6675}
6676
Xiuli Pan89307aa2016-02-24 04:29:36 +00006677/// \brief Return true if the Expr is block type
6678static bool checkBlockType(Sema &S, const Expr *E) {
6679 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6680 QualType Ty = CE->getCallee()->getType();
6681 if (Ty->isBlockPointerType()) {
6682 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6683 return true;
6684 }
6685 }
6686 return false;
6687}
6688
Richard Trieud33e46e2011-09-06 20:06:39 +00006689/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6690/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00006691/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00006692QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6693 ExprResult &RHS, ExprValueKind &VK,
6694 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00006695 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00006696
Richard Trieud33e46e2011-09-06 20:06:39 +00006697 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6698 if (!LHSResult.isUsable()) return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006699 LHS = LHSResult;
Douglas Gregor0124e9b2010-11-09 21:07:58 +00006700
Richard Trieud33e46e2011-09-06 20:06:39 +00006701 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6702 if (!RHSResult.isUsable()) return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006703 RHS = RHSResult;
Douglas Gregor0124e9b2010-11-09 21:07:58 +00006704
Sebastian Redl1a99f442009-04-16 17:51:27 +00006705 // C++ is sufficiently different to merit its own checker.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006706 if (getLangOpts().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00006707 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00006708
6709 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00006710 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006711
Sameer Sahasrabuddhee8d2aaf2015-02-04 06:38:18 +00006712 // The OpenCL operator with a vector condition is sufficiently
6713 // different to merit its own checker.
6714 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6715 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6716
Jin-Gu Kang09c22132013-09-02 20:32:37 +00006717 // First, check the condition.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006718 Cond = UsualUnaryConversions(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00006719 if (Cond.isInvalid())
6720 return QualType();
Sameer Sahasrabuddhee8d2aaf2015-02-04 06:38:18 +00006721 if (checkCondition(*this, Cond.get(), QuestionLoc))
Jin-Gu Kang09c22132013-09-02 20:32:37 +00006722 return QualType();
6723
6724 // Now check the two expressions.
6725 if (LHS.get()->getType()->isVectorType() ||
6726 RHS.get()->getType()->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00006727 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6728 /*AllowBothBool*/true,
6729 /*AllowBoolConversions*/false);
Jin-Gu Kang09c22132013-09-02 20:32:37 +00006730
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006731 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
Eli Friedmane6d33952013-07-08 20:20:06 +00006732 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006733 return QualType();
6734
John Wiegley01296292011-04-08 18:41:53 +00006735 QualType LHSTy = LHS.get()->getType();
6736 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00006737
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006738 // Diagnose attempts to convert between __float128 and long double where
6739 // such conversions currently can't be handled.
6740 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6741 Diag(QuestionLoc,
6742 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6743 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6744 return QualType();
6745 }
6746
Xiuli Pan89307aa2016-02-24 04:29:36 +00006747 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6748 // selection operator (?:).
6749 if (getLangOpts().OpenCL &&
6750 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6751 return QualType();
6752 }
6753
Chris Lattnere2949f42008-01-06 22:42:25 +00006754 // If both operands have arithmetic type, do the usual arithmetic conversions
6755 // to find a common type: C99 6.5.15p3,5.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006756 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6757 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6758 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6759
6760 return ResTy;
6761 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006762
Chris Lattnere2949f42008-01-06 22:42:25 +00006763 // If both operands are the same structure or union type, the result is that
6764 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006765 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
6766 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00006767 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00006768 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00006769 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00006770 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00006771 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00006772 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006773
Chris Lattnere2949f42008-01-06 22:42:25 +00006774 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00006775 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00006776 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006777 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00006778 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006779
Steve Naroff039ad3c2008-01-08 01:11:38 +00006780 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6781 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006782 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6783 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006784
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006785 // All objective-c pointer type analysis is done here.
6786 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6787 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00006788 if (LHS.isInvalid() || RHS.isInvalid())
6789 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006790 if (!compositeType.isNull())
6791 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006792
6793
Steve Naroff05efa972009-07-01 14:36:47 +00006794 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006795 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6796 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6797 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006798
Steve Naroff05efa972009-07-01 14:36:47 +00006799 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006800 if (LHSTy->isPointerType() && RHSTy->isPointerType())
6801 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6802 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006803
John McCalle84af4e2010-11-13 01:35:44 +00006804 // GCC compatibility: soften pointer/integer mismatch. Note that
6805 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006806 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6807 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00006808 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00006809 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6810 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00006811 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00006812
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00006813 // Emit a better diagnostic if one of the expressions is a null pointer
6814 // constant and the other is not a pointer type. In this case, the user most
6815 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00006816 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00006817 return QualType();
6818
Chris Lattnere2949f42008-01-06 22:42:25 +00006819 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00006820 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00006821 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6822 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00006823 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00006824}
6825
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006826/// FindCompositeObjCPointerType - Helper method to find composite type of
6827/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00006828QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006829 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00006830 QualType LHSTy = LHS.get()->getType();
6831 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006832
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006833 // Handle things like Class and struct objc_class*. Here we case the result
6834 // to the pseudo-builtin, because that will be implicitly cast back to the
6835 // redefinition type if an attempt is made to access its fields.
6836 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00006837 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006838 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006839 return LHSTy;
6840 }
6841 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00006842 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006843 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006844 return RHSTy;
6845 }
6846 // And the same for struct objc_object* / id
6847 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00006848 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006849 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006850 return LHSTy;
6851 }
6852 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00006853 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006854 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006855 return RHSTy;
6856 }
6857 // And the same for struct objc_selector* / SEL
6858 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00006859 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006860 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006861 return LHSTy;
6862 }
6863 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00006864 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006865 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006866 return RHSTy;
6867 }
6868 // Check constraints for Objective-C object pointers types.
6869 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006870
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006871 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6872 // Two identical object pointer types are always compatible.
6873 return LHSTy;
6874 }
John McCall9320b872011-09-09 05:25:32 +00006875 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6876 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006877 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006878
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006879 // If both operands are interfaces and either operand can be
6880 // assigned to the other, use that type as the composite
6881 // type. This allows
6882 // xxx ? (A*) a : (B*) b
6883 // where B is a subclass of A.
6884 //
6885 // Additionally, as for assignment, if either type is 'id'
6886 // allow silent coercion. Finally, if the types are
6887 // incompatible then make sure to use 'id' as the composite
6888 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006889
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006890 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6891 // It could return the composite type.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006892 if (!(compositeType =
6893 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6894 // Nothing more to do.
6895 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006896 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6897 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6898 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6899 } else if ((LHSTy->isObjCQualifiedIdType() ||
6900 RHSTy->isObjCQualifiedIdType()) &&
6901 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6902 // Need to handle "id<xx>" explicitly.
6903 // GCC allows qualified id and any Objective-C type to devolve to
6904 // id. Currently localizing to here until clear this should be
6905 // part of ObjCQualifiedIdTypesAreCompatible.
6906 compositeType = Context.getObjCIdType();
6907 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6908 compositeType = Context.getObjCIdType();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006909 } else {
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006910 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6911 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00006912 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006913 QualType incompatTy = Context.getObjCIdType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006914 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6915 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006916 return incompatTy;
6917 }
6918 // The object pointer types are compatible.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006919 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6920 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006921 return compositeType;
6922 }
6923 // Check Objective-C object pointer types and 'void *'
6924 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006925 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00006926 // ARC forbids the implicit conversion of object pointers to 'void *',
6927 // so these types are not compatible.
6928 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6929 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6930 LHS = RHS = true;
6931 return QualType();
6932 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006933 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6934 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6935 QualType destPointee
6936 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6937 QualType destType = Context.getPointerType(destPointee);
6938 // Add qualifiers if necessary.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006939 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006940 // Promote to void*.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006941 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006942 return destType;
6943 }
6944 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006945 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00006946 // ARC forbids the implicit conversion of object pointers to 'void *',
6947 // so these types are not compatible.
6948 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6949 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6950 LHS = RHS = true;
6951 return QualType();
6952 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006953 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6954 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6955 QualType destPointee
6956 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6957 QualType destType = Context.getPointerType(destPointee);
6958 // Add qualifiers if necessary.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006959 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006960 // Promote to void*.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006961 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006962 return destType;
6963 }
6964 return QualType();
6965}
6966
Chandler Carruthb00e8c02011-06-16 01:05:14 +00006967/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006968/// ParenRange in parentheses.
6969static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00006970 const PartialDiagnostic &Note,
6971 SourceRange ParenRange) {
Craig Topper07fa1762015-11-15 02:31:46 +00006972 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
Chandler Carruthb00e8c02011-06-16 01:05:14 +00006973 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6974 EndLoc.isValid()) {
6975 Self.Diag(Loc, Note)
6976 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6977 << FixItHint::CreateInsertion(EndLoc, ")");
6978 } else {
6979 // We can't display the parentheses, so just show the bare note.
6980 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006981 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006982}
6983
6984static bool IsArithmeticOp(BinaryOperatorKind Opc) {
Craig Topperb0dfa7a2015-12-13 05:41:37 +00006985 return BinaryOperator::isAdditiveOp(Opc) ||
6986 BinaryOperator::isMultiplicativeOp(Opc) ||
6987 BinaryOperator::isShiftOp(Opc);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006988}
6989
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006990/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6991/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00006992/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6993/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006994static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00006995 Expr **RHSExprs) {
Hans Wennborgbe207b32011-09-12 12:07:30 +00006996 // Don't strip parenthesis: we should not warn if E is in parenthesis.
6997 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006998 E = E->IgnoreConversionOperator();
Hans Wennborgbe207b32011-09-12 12:07:30 +00006999 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00007000
7001 // Built-in binary operator.
7002 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7003 if (IsArithmeticOp(OP->getOpcode())) {
7004 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00007005 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00007006 return true;
7007 }
7008 }
7009
7010 // Overloaded operator.
7011 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7012 if (Call->getNumArgs() != 2)
7013 return false;
7014
7015 // Make sure this is really a binary operator that is safe to pass into
7016 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7017 OverloadedOperatorKind OO = Call->getOperator();
Benjamin Kramer0345f9f2013-03-30 11:56:00 +00007018 if (OO < OO_Plus || OO > OO_Arrow ||
7019 OO == OO_PlusPlus || OO == OO_MinusMinus)
Hans Wennborgde2e67e2011-06-09 17:06:51 +00007020 return false;
7021
7022 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7023 if (IsArithmeticOp(OpKind)) {
7024 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00007025 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00007026 return true;
7027 }
7028 }
7029
7030 return false;
7031}
7032
Hans Wennborgde2e67e2011-06-09 17:06:51 +00007033/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7034/// or is a logical expression such as (x==y) which has int type, but is
7035/// commonly interpreted as boolean.
7036static bool ExprLooksBoolean(Expr *E) {
7037 E = E->IgnoreParenImpCasts();
7038
7039 if (E->getType()->isBooleanType())
7040 return true;
7041 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
Craig Topperb0dfa7a2015-12-13 05:41:37 +00007042 return OP->isComparisonOp() || OP->isLogicalOp();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00007043 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7044 return OP->getOpcode() == UO_LNot;
Hans Wennborgb60dfbe2015-01-22 22:11:56 +00007045 if (E->getType()->isPointerType())
7046 return true;
Hans Wennborgde2e67e2011-06-09 17:06:51 +00007047
7048 return false;
7049}
7050
Hans Wennborgcf9bac42011-06-03 18:00:36 +00007051/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7052/// and binary operator are mixed in a way that suggests the programmer assumed
7053/// the conditional operator has higher precedence, for example:
7054/// "int x = a + someBinaryCondition ? 1 : 2".
7055static void DiagnoseConditionalPrecedence(Sema &Self,
7056 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00007057 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00007058 Expr *LHSExpr,
7059 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00007060 BinaryOperatorKind CondOpcode;
7061 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00007062
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00007063 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00007064 return;
7065 if (!ExprLooksBoolean(CondRHS))
7066 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00007067
Hans Wennborgde2e67e2011-06-09 17:06:51 +00007068 // The condition is an arithmetic binary expression, with a right-
7069 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00007070
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007071 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00007072 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00007073 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00007074
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007075 SuggestParentheses(Self, OpLoc,
David Blaikiedac86fd2012-10-08 01:19:49 +00007076 Self.PDiag(diag::note_precedence_silence)
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007077 << BinaryOperator::getOpcodeStr(CondOpcode),
7078 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00007079
7080 SuggestParentheses(Self, OpLoc,
7081 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00007082 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00007083}
7084
Akira Hatanaka73118fd2016-07-20 01:48:11 +00007085/// Compute the nullability of a conditional expression.
7086static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7087 QualType LHSTy, QualType RHSTy,
7088 ASTContext &Ctx) {
Akira Hatanaka1b074962016-07-25 21:58:19 +00007089 if (!ResTy->isAnyPointerType())
Akira Hatanaka73118fd2016-07-20 01:48:11 +00007090 return ResTy;
7091
7092 auto GetNullability = [&Ctx](QualType Ty) {
7093 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7094 if (Kind)
7095 return *Kind;
7096 return NullabilityKind::Unspecified;
7097 };
7098
7099 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7100 NullabilityKind MergedKind;
7101
7102 // Compute nullability of a binary conditional expression.
7103 if (IsBin) {
7104 if (LHSKind == NullabilityKind::NonNull)
7105 MergedKind = NullabilityKind::NonNull;
7106 else
7107 MergedKind = RHSKind;
7108 // Compute nullability of a normal conditional expression.
7109 } else {
7110 if (LHSKind == NullabilityKind::Nullable ||
7111 RHSKind == NullabilityKind::Nullable)
7112 MergedKind = NullabilityKind::Nullable;
7113 else if (LHSKind == NullabilityKind::NonNull)
7114 MergedKind = RHSKind;
7115 else if (RHSKind == NullabilityKind::NonNull)
7116 MergedKind = LHSKind;
7117 else
7118 MergedKind = NullabilityKind::Unspecified;
7119 }
7120
7121 // Return if ResTy already has the correct nullability.
7122 if (GetNullability(ResTy) == MergedKind)
7123 return ResTy;
7124
7125 // Strip all nullability from ResTy.
7126 while (ResTy->getNullability(Ctx))
7127 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7128
7129 // Create a new AttributedType with the new nullability kind.
7130 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7131 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7132}
7133
Steve Naroff83895f72007-09-16 03:34:24 +00007134/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00007135/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00007136ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00007137 SourceLocation ColonLoc,
7138 Expr *CondExpr, Expr *LHSExpr,
7139 Expr *RHSExpr) {
Kaelyn Takata05f40502015-01-27 18:26:18 +00007140 if (!getLangOpts().CPlusPlus) {
7141 // C cannot handle TypoExpr nodes in the condition because it
7142 // doesn't handle dependent types properly, so make sure any TypoExprs have
7143 // been dealt with before checking the operands.
7144 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
David Majnemer2eb74e22016-02-17 17:19:00 +00007145 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7146 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7147
7148 if (!CondResult.isUsable())
7149 return ExprError();
7150
7151 if (LHSExpr) {
7152 if (!LHSResult.isUsable())
7153 return ExprError();
7154 }
7155
7156 if (!RHSResult.isUsable())
7157 return ExprError();
7158
Kaelyn Takata05f40502015-01-27 18:26:18 +00007159 CondExpr = CondResult.get();
David Majnemer2eb74e22016-02-17 17:19:00 +00007160 LHSExpr = LHSResult.get();
7161 RHSExpr = RHSResult.get();
Kaelyn Takata05f40502015-01-27 18:26:18 +00007162 }
7163
Chris Lattner2ab40a62007-11-26 01:40:58 +00007164 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7165 // was the condition.
Craig Topperc3ec1492014-05-26 06:22:03 +00007166 OpaqueValueExpr *opaqueValue = nullptr;
7167 Expr *commonExpr = nullptr;
7168 if (!LHSExpr) {
John McCallc07a0c72011-02-17 10:25:35 +00007169 commonExpr = CondExpr;
Fariborz Jahanian3caab6c2013-05-17 16:29:36 +00007170 // Lower out placeholder types first. This is important so that we don't
7171 // try to capture a placeholder. This happens in few cases in C++; such
7172 // as Objective-C++'s dictionary subscripting syntax.
7173 if (commonExpr->hasPlaceholderType()) {
7174 ExprResult result = CheckPlaceholderExpr(commonExpr);
7175 if (!result.isUsable()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007176 commonExpr = result.get();
Fariborz Jahanian3caab6c2013-05-17 16:29:36 +00007177 }
John McCallc07a0c72011-02-17 10:25:35 +00007178 // We usually want to apply unary conversions *before* saving, except
7179 // in the special case of a C++ l-value conditional.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007180 if (!(getLangOpts().CPlusPlus
John McCallc07a0c72011-02-17 10:25:35 +00007181 && !commonExpr->isTypeDependent()
7182 && commonExpr->getValueKind() == RHSExpr->getValueKind()
7183 && commonExpr->isGLValue()
7184 && commonExpr->isOrdinaryOrBitFieldObject()
7185 && RHSExpr->isOrdinaryOrBitFieldObject()
7186 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00007187 ExprResult commonRes = UsualUnaryConversions(commonExpr);
7188 if (commonRes.isInvalid())
7189 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007190 commonExpr = commonRes.get();
John McCallc07a0c72011-02-17 10:25:35 +00007191 }
7192
7193 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7194 commonExpr->getType(),
7195 commonExpr->getValueKind(),
Douglas Gregor2d5aea02012-02-23 22:17:26 +00007196 commonExpr->getObjectKind(),
7197 commonExpr);
John McCallc07a0c72011-02-17 10:25:35 +00007198 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00007199 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00007200
Akira Hatanaka73118fd2016-07-20 01:48:11 +00007201 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
John McCall7decc9e2010-11-18 06:31:45 +00007202 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00007203 ExprObjectKind OK = OK_Ordinary;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007204 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
John Wiegley01296292011-04-08 18:41:53 +00007205 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00007206 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00007207 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7208 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007209 return ExprError();
7210
Hans Wennborgcf9bac42011-06-03 18:00:36 +00007211 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7212 RHS.get());
7213
Richard Trieucbab79a2015-05-20 23:29:18 +00007214 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7215
Akira Hatanaka73118fd2016-07-20 01:48:11 +00007216 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7217 Context);
7218
John McCallc07a0c72011-02-17 10:25:35 +00007219 if (!commonExpr)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007220 return new (Context)
7221 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7222 RHS.get(), result, VK, OK);
John McCallc07a0c72011-02-17 10:25:35 +00007223
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007224 return new (Context) BinaryConditionalOperator(
7225 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7226 ColonLoc, result, VK, OK);
Chris Lattnere168f762006-11-10 05:29:30 +00007227}
7228
John McCallaba90822011-01-31 23:13:11 +00007229// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00007230// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00007231// routine is it effectively iqnores the qualifiers on the top level pointee.
7232// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7233// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00007234static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00007235checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7236 assert(LHSType.isCanonical() && "LHS not canonicalized!");
7237 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00007238
Steve Naroff1f4d7272007-05-11 04:00:31 +00007239 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00007240 const Type *lhptee, *rhptee;
7241 Qualifiers lhq, rhq;
Benjamin Kramercef536e2014-03-02 13:18:22 +00007242 std::tie(lhptee, lhq) =
7243 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7244 std::tie(rhptee, rhq) =
7245 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007246
John McCallaba90822011-01-31 23:13:11 +00007247 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007248
7249 // C99 6.5.16.1p1: This following citation is common to constraints
7250 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7251 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00007252
John McCall31168b02011-06-15 23:02:42 +00007253 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7254 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7255 lhq.compatiblyIncludesObjCLifetime(rhq)) {
7256 // Ignore lifetime for further calculation.
7257 lhq.removeObjCLifetime();
7258 rhq.removeObjCLifetime();
7259 }
7260
John McCall4fff8f62011-02-01 00:10:29 +00007261 if (!lhq.compatiblyIncludes(rhq)) {
7262 // Treat address-space mismatches as fatal. TODO: address subspaces
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00007263 if (!lhq.isAddressSpaceSupersetOf(rhq))
John McCall4fff8f62011-02-01 00:10:29 +00007264 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7265
John McCall31168b02011-06-15 23:02:42 +00007266 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00007267 // and from void*.
John McCall18ce25e2012-02-08 00:46:36 +00007268 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCall31168b02011-06-15 23:02:42 +00007269 .compatiblyIncludes(
John McCall18ce25e2012-02-08 00:46:36 +00007270 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall78535952011-03-26 02:56:45 +00007271 && (lhptee->isVoidType() || rhptee->isVoidType()))
7272 ; // keep old
7273
John McCall31168b02011-06-15 23:02:42 +00007274 // Treat lifetime mismatches as fatal.
7275 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7276 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7277
Andrey Bokhanko45d41322016-05-11 18:38:21 +00007278 // For GCC/MS compatibility, other qualifier mismatches are treated
John McCall4fff8f62011-02-01 00:10:29 +00007279 // as still compatible in C.
7280 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7281 }
Steve Naroff3f597292007-05-11 22:18:03 +00007282
Mike Stump4e1f26a2009-02-19 03:04:26 +00007283 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7284 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00007285 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00007286 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00007287 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00007288 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007289
Chris Lattner0a788432008-01-03 22:56:36 +00007290 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00007291 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00007292 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00007293 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007294
Chris Lattner0a788432008-01-03 22:56:36 +00007295 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00007296 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00007297 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00007298
7299 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00007300 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00007301 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00007302 }
John McCall4fff8f62011-02-01 00:10:29 +00007303
Mike Stump4e1f26a2009-02-19 03:04:26 +00007304 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00007305 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00007306 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7307 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00007308 // Check if the pointee types are compatible ignoring the sign.
7309 // We explicitly check for char so that we catch "char" vs
7310 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00007311 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00007312 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007313 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00007314 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007315
Chris Lattnerec3a1562009-10-17 20:33:28 +00007316 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00007317 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007318 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00007319 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00007320
John McCall4fff8f62011-02-01 00:10:29 +00007321 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00007322 // Types are compatible ignoring the sign. Qualifier incompatibility
7323 // takes priority over sign incompatibility because the sign
7324 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00007325 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00007326 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00007327
John McCallaba90822011-01-31 23:13:11 +00007328 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00007329 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007330
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00007331 // If we are a multi-level pointer, it's possible that our issue is simply
7332 // one of qualification - e.g. char ** -> const char ** is not allowed. If
7333 // the eventual target type is the same and the pointers have the same
7334 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00007335 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00007336 do {
John McCall4fff8f62011-02-01 00:10:29 +00007337 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7338 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00007339 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007340
John McCall4fff8f62011-02-01 00:10:29 +00007341 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00007342 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00007343 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007344
Eli Friedman80160bd2009-03-22 23:59:44 +00007345 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00007346 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00007347 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00007348 if (!S.getLangOpts().CPlusPlus &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00007349 S.IsFunctionConversion(ltrans, rtrans, ltrans))
Fariborz Jahanian48c69102011-10-05 00:05:34 +00007350 return Sema::IncompatiblePointer;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007351 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00007352}
7353
John McCallaba90822011-01-31 23:13:11 +00007354/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00007355/// block pointer types are compatible or whether a block and normal pointer
7356/// are compatible. It is more restrict than comparing two function pointer
7357// types.
John McCallaba90822011-01-31 23:13:11 +00007358static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00007359checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7360 QualType RHSType) {
7361 assert(LHSType.isCanonical() && "LHS not canonicalized!");
7362 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00007363
Steve Naroff081c7422008-09-04 15:10:53 +00007364 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007365
Steve Naroff081c7422008-09-04 15:10:53 +00007366 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00007367 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7368 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007369
John McCallaba90822011-01-31 23:13:11 +00007370 // In C++, the types have to match exactly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007371 if (S.getLangOpts().CPlusPlus)
John McCallaba90822011-01-31 23:13:11 +00007372 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007373
John McCallaba90822011-01-31 23:13:11 +00007374 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007375
Steve Naroff081c7422008-09-04 15:10:53 +00007376 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00007377 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
7378 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007379
Richard Trieua871b972011-09-06 20:21:22 +00007380 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00007381 return Sema::IncompatibleBlockPointer;
7382
Steve Naroff081c7422008-09-04 15:10:53 +00007383 return ConvTy;
7384}
7385
John McCallaba90822011-01-31 23:13:11 +00007386/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00007387/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00007388static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00007389checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7390 QualType RHSType) {
7391 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7392 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00007393
Richard Trieua871b972011-09-06 20:21:22 +00007394 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00007395 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00007396 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7397 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00007398 return Sema::IncompatiblePointer;
7399 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00007400 }
Richard Trieua871b972011-09-06 20:21:22 +00007401 if (RHSType->isObjCBuiltinType()) {
Richard Trieua871b972011-09-06 20:21:22 +00007402 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7403 !LHSType->isObjCQualifiedClassType())
Fariborz Jahaniand923eb02011-09-15 20:40:18 +00007404 return Sema::IncompatiblePointer;
John McCallaba90822011-01-31 23:13:11 +00007405 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00007406 }
Richard Trieua871b972011-09-06 20:21:22 +00007407 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7408 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007409
Fariborz Jahaniane74d47e2012-01-12 22:12:08 +00007410 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7411 // make an exception for id<P>
7412 !LHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00007413 return Sema::CompatiblePointerDiscardsQualifiers;
7414
Richard Trieua871b972011-09-06 20:21:22 +00007415 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00007416 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00007417 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00007418 return Sema::IncompatibleObjCQualifiedId;
7419 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00007420}
7421
John McCall29600e12010-11-16 02:32:08 +00007422Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00007423Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00007424 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00007425 // Fake up an opaque expression. We don't actually care about what
7426 // cast operations are required, so if CheckAssignmentConstraints
7427 // adds casts to this they'll be wasted, but fortunately that doesn't
7428 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00007429 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7430 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00007431 CastKind K = CK_Invalid;
7432
George Burgess IV45461812015-10-11 20:13:20 +00007433 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
John McCall29600e12010-11-16 02:32:08 +00007434}
7435
Mike Stump4e1f26a2009-02-19 03:04:26 +00007436/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7437/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00007438/// pointers. Here are some objectionable examples that GCC considers warnings:
7439///
7440/// int a, *pint;
7441/// short *pshort;
7442/// struct foo *pfoo;
7443///
7444/// pint = pshort; // warning: assignment from incompatible pointer type
7445/// a = pint; // warning: assignment makes integer from pointer without a cast
7446/// pint = a; // warning: assignment makes pointer from integer without a cast
7447/// pint = pfoo; // warning: assignment from incompatible pointer type
7448///
7449/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00007450/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00007451///
John McCall8cb679e2010-11-15 09:13:47 +00007452/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00007453Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00007454Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
George Burgess IV45461812015-10-11 20:13:20 +00007455 CastKind &Kind, bool ConvertRHS) {
Richard Trieude4958f2011-09-06 20:30:53 +00007456 QualType RHSType = RHS.get()->getType();
7457 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00007458
Chris Lattnera52c2f22008-01-04 23:18:45 +00007459 // Get canonical types. We're not formatting these types, just comparing
7460 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00007461 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7462 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00007463
John McCalle5255932011-01-31 22:28:28 +00007464 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00007465 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00007466 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00007467 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00007468 }
7469
Eli Friedman93ee5ca2012-06-16 02:19:17 +00007470 // If we have an atomic type, try a non-atomic assignment, then just add an
7471 // atomic qualification step.
David Chisnallfa35df62012-01-16 17:27:18 +00007472 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman93ee5ca2012-06-16 02:19:17 +00007473 Sema::AssignConvertType result =
7474 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7475 if (result != Compatible)
7476 return result;
George Burgess IV45461812015-10-11 20:13:20 +00007477 if (Kind != CK_NoOp && ConvertRHS)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007478 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
Eli Friedman93ee5ca2012-06-16 02:19:17 +00007479 Kind = CK_NonAtomicToAtomic;
7480 return Compatible;
David Chisnallfa35df62012-01-16 17:27:18 +00007481 }
7482
Douglas Gregor6b754842008-10-28 00:22:11 +00007483 // If the left-hand side is a reference type, then we are in a
7484 // (rare!) case where we've allowed the use of references in C,
7485 // e.g., as a parameter type in a built-in function. In this case,
7486 // just make sure that the type referenced is compatible with the
7487 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00007488 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00007489 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00007490 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7491 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00007492 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00007493 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00007494 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00007495 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00007496 }
John McCalle5255932011-01-31 22:28:28 +00007497
Nate Begemanbd956c42009-06-28 02:36:38 +00007498 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7499 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00007500 if (LHSType->isExtVectorType()) {
7501 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00007502 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00007503 if (RHSType->isArithmeticType()) {
George Burgess IVdf1ed002016-01-13 01:52:39 +00007504 // CK_VectorSplat does T -> vector T, so first cast to the element type.
7505 if (ConvertRHS)
7506 RHS = prepareVectorSplat(LHSType, RHS.get());
John McCall29600e12010-11-16 02:32:08 +00007507 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00007508 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00007509 }
Nate Begemanbd956c42009-06-28 02:36:38 +00007510 }
Mike Stump11289f42009-09-09 15:08:12 +00007511
John McCalle5255932011-01-31 22:28:28 +00007512 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00007513 if (LHSType->isVectorType() || RHSType->isVectorType()) {
7514 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00007515 // Allow assignments of an AltiVec vector type to an equivalent GCC
7516 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00007517 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00007518 Kind = CK_BitCast;
7519 return Compatible;
7520 }
7521
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007522 // If we are allowing lax vector conversions, and LHS and RHS are both
7523 // vectors, the total size only needs to be the same. This is a bitcast;
7524 // no bits are changed but the result type is different.
John McCall9b595db2014-02-04 23:58:19 +00007525 if (isLaxVectorConversion(RHSType, LHSType)) {
John McCall3065d042010-11-15 10:08:00 +00007526 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00007527 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00007528 }
Chris Lattner881a2122008-01-04 23:32:24 +00007529 }
Bruno Cardoso Lopes2ebe18b2016-07-06 18:05:23 +00007530
7531 // When the RHS comes from another lax conversion (e.g. binops between
7532 // scalars and vectors) the result is canonicalized as a vector. When the
7533 // LHS is also a vector, the lax is allowed by the condition above. Handle
7534 // the case where LHS is a scalar.
7535 if (LHSType->isScalarType()) {
7536 const VectorType *VecType = RHSType->getAs<VectorType>();
7537 if (VecType && VecType->getNumElements() == 1 &&
7538 isLaxVectorConversion(RHSType, LHSType)) {
7539 ExprResult *VecExpr = &RHS;
7540 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7541 Kind = CK_BitCast;
7542 return Compatible;
7543 }
7544 }
7545
Chris Lattner881a2122008-01-04 23:32:24 +00007546 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007547 }
Eli Friedman3360d892008-05-30 18:07:22 +00007548
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007549 // Diagnose attempts to convert between __float128 and long double where
7550 // such conversions currently can't be handled.
7551 if (unsupportedTypeConversion(*this, LHSType, RHSType))
7552 return Incompatible;
7553
John McCalle5255932011-01-31 22:28:28 +00007554 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00007555 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007556 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
George Burgess IV45461812015-10-11 20:13:20 +00007557 if (ConvertRHS)
7558 Kind = PrepareScalarCast(RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00007559 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00007560 }
Eli Friedman3360d892008-05-30 18:07:22 +00007561
John McCalle5255932011-01-31 22:28:28 +00007562 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00007563 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00007564 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00007565 if (isa<PointerType>(RHSType)) {
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00007566 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7567 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7568 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00007569 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00007570 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007571
John McCalle5255932011-01-31 22:28:28 +00007572 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00007573 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00007574 Kind = CK_IntegralToPointer; // FIXME: null?
7575 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007576 }
John McCalle5255932011-01-31 22:28:28 +00007577
7578 // C pointers are not compatible with ObjC object pointers,
7579 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00007580 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00007581 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00007582 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall9320b872011-09-09 05:25:32 +00007583 Kind = CK_BitCast;
John McCalle5255932011-01-31 22:28:28 +00007584 return Compatible;
7585 }
7586
7587 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00007588 if (RHSType->isObjCClassType() &&
7589 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00007590 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00007591 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00007592 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00007593 }
Douglas Gregor486b74e2011-09-27 16:10:05 +00007594
John McCalle5255932011-01-31 22:28:28 +00007595 Kind = CK_BitCast;
7596 return IncompatiblePointer;
7597 }
7598
7599 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00007600 if (RHSType->getAs<BlockPointerType>()) {
7601 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00007602 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00007603 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00007604 }
Steve Naroff32d072c2008-09-29 18:10:17 +00007605 }
John McCalle5255932011-01-31 22:28:28 +00007606
Steve Naroff081c7422008-09-04 15:10:53 +00007607 return Incompatible;
7608 }
7609
John McCalle5255932011-01-31 22:28:28 +00007610 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00007611 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00007612 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00007613 if (RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00007614 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00007615 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00007616 }
7617
7618 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00007619 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00007620 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00007621 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00007622 }
7623
John McCalle5255932011-01-31 22:28:28 +00007624 // id -> T^
David Blaikiebbafb8a2012-03-11 07:00:24 +00007625 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00007626 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00007627 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00007628 }
Steve Naroff32d072c2008-09-29 18:10:17 +00007629
John McCalle5255932011-01-31 22:28:28 +00007630 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00007631 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00007632 if (RHSPT->getPointeeType()->isVoidType()) {
7633 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00007634 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00007635 }
John McCall8cb679e2010-11-15 09:13:47 +00007636
Chris Lattnera52c2f22008-01-04 23:18:45 +00007637 return Incompatible;
7638 }
7639
John McCalle5255932011-01-31 22:28:28 +00007640 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00007641 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00007642 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00007643 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00007644 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00007645 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00007646 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikiebbafb8a2012-03-11 07:00:24 +00007647 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00007648 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00007649 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00007650 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00007651 return result;
John McCalle5255932011-01-31 22:28:28 +00007652 }
7653
7654 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00007655 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00007656 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00007657 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00007658 }
7659
John McCalle5255932011-01-31 22:28:28 +00007660 // In general, C pointers are not compatible with ObjC object pointers,
7661 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00007662 if (isa<PointerType>(RHSType)) {
John McCall9320b872011-09-09 05:25:32 +00007663 Kind = CK_CPointerToObjCPointerCast;
7664
John McCalle5255932011-01-31 22:28:28 +00007665 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00007666 if (RHSType->isVoidPointerType()) {
Steve Naroffaccc4882009-07-20 17:56:53 +00007667 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00007668 }
7669
7670 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00007671 if (LHSType->isObjCClassType() &&
7672 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00007673 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00007674 return Compatible;
7675 }
7676
Steve Naroffaccc4882009-07-20 17:56:53 +00007677 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007678 }
John McCalle5255932011-01-31 22:28:28 +00007679
Fariborz Jahanian7ea91b22014-06-09 21:42:01 +00007680 // Only under strict condition T^ is compatible with an Objective-C pointer.
Douglas Gregore9d95f12015-07-07 03:57:35 +00007681 if (RHSType->isBlockPointerType() &&
7682 LHSType->isBlockCompatibleObjCPointerType(Context)) {
George Burgess IV45461812015-10-11 20:13:20 +00007683 if (ConvertRHS)
7684 maybeExtendBlockObject(RHS);
John McCall9320b872011-09-09 05:25:32 +00007685 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007686 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00007687 }
7688
Steve Naroff7cae42b2009-07-10 23:34:53 +00007689 return Incompatible;
7690 }
John McCalle5255932011-01-31 22:28:28 +00007691
7692 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00007693 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00007694 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00007695 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00007696 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00007697 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00007698 }
Eli Friedman3360d892008-05-30 18:07:22 +00007699
John McCalle5255932011-01-31 22:28:28 +00007700 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00007701 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00007702 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00007703 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00007704 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007705
Chris Lattnera52c2f22008-01-04 23:18:45 +00007706 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00007707 }
John McCalle5255932011-01-31 22:28:28 +00007708
7709 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00007710 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00007711 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00007712 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00007713 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007714 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00007715 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007716
John McCalle5255932011-01-31 22:28:28 +00007717 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00007718 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00007719 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007720 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00007721 }
7722
Steve Naroff7cae42b2009-07-10 23:34:53 +00007723 return Incompatible;
7724 }
Eli Friedman3360d892008-05-30 18:07:22 +00007725
John McCalle5255932011-01-31 22:28:28 +00007726 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00007727 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7728 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00007729 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00007730 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00007731 }
Bill Wendling216423b2007-05-30 06:30:29 +00007732 }
John McCalle5255932011-01-31 22:28:28 +00007733
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00007734 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7735 Kind = CK_IntToOCLSampler;
7736 return Compatible;
7737 }
7738
Steve Naroff98cf3e92007-06-06 18:38:38 +00007739 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00007740}
7741
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007742/// \brief Constructs a transparent union from an expression that is
7743/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00007744static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7745 ExprResult &EResult, QualType UnionType,
7746 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007747 // Build an initializer list that designates the appropriate member
7748 // of the transparent union.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007749 Expr *E = EResult.get();
Ted Kremenekac034612010-04-13 23:39:13 +00007750 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00007751 E, SourceLocation());
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007752 Initializer->setType(UnionType);
7753 Initializer->setInitializedFieldInUnion(Field);
7754
7755 // Build a compound literal constructing a value of the transparent
7756 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00007757 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007758 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7759 VK_RValue, Initializer, false);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007760}
7761
7762Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00007763Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00007764 ExprResult &RHS) {
7765 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007766
Mike Stump11289f42009-09-09 15:08:12 +00007767 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007768 // transparent_union GCC extension.
7769 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00007770 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007771 return Incompatible;
7772
7773 // The field to initialize within the transparent union.
7774 RecordDecl *UD = UT->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00007775 FieldDecl *InitField = nullptr;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007776 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007777 for (auto *it : UD->fields()) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007778 if (it->getType()->isPointerType()) {
7779 // If the transparent union contains a pointer type, we allow:
7780 // 1) void pointer
7781 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00007782 if (RHSType->isPointerType())
John McCall9320b872011-09-09 05:25:32 +00007783 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007784 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007785 InitField = it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007786 break;
7787 }
Mike Stump11289f42009-09-09 15:08:12 +00007788
Richard Trieueb299142011-09-06 20:40:12 +00007789 if (RHS.get()->isNullPointerConstant(Context,
7790 Expr::NPC_ValueDependentIsNull)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007791 RHS = ImpCastExprToType(RHS.get(), it->getType(),
Richard Trieueb299142011-09-06 20:40:12 +00007792 CK_NullToPointer);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007793 InitField = it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007794 break;
7795 }
7796 }
7797
John McCall8cb679e2010-11-15 09:13:47 +00007798 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00007799 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007800 == Compatible) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007801 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007802 InitField = it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007803 break;
7804 }
7805 }
7806
7807 if (!InitField)
7808 return Incompatible;
7809
Richard Trieueb299142011-09-06 20:40:12 +00007810 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00007811 return Compatible;
7812}
7813
Chris Lattner9bad62c2008-01-04 18:04:52 +00007814Sema::AssignConvertType
George Burgess IV45461812015-10-11 20:13:20 +00007815Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
Fariborz Jahanian25eef192013-07-31 21:40:51 +00007816 bool Diagnose,
George Burgess IV45461812015-10-11 20:13:20 +00007817 bool DiagnoseCFAudited,
7818 bool ConvertRHS) {
Richard Smithe15a3702016-10-06 23:12:58 +00007819 // We need to be able to tell the caller whether we diagnosed a problem, if
7820 // they ask us to issue diagnostics.
7821 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7822
George Burgess IV45461812015-10-11 20:13:20 +00007823 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7824 // we can't avoid *all* modifications at the moment, so we need some somewhere
7825 // to put the updated value.
7826 ExprResult LocalRHS = CallerRHS;
7827 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7828
David Blaikiebbafb8a2012-03-11 07:00:24 +00007829 if (getLangOpts().CPlusPlus) {
Eli Friedman0dfb8892011-10-06 23:00:33 +00007830 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00007831 // C++ 5.17p3: If the left operand is not of class type, the
7832 // expression is implicitly converted (C++ 4) to the
7833 // cv-unqualified type of the left operand.
Richard Smithe15a3702016-10-06 23:12:58 +00007834 QualType RHSType = RHS.get()->getType();
Sebastian Redlcc152642011-10-16 18:19:06 +00007835 if (Diagnose) {
Richard Smithe15a3702016-10-06 23:12:58 +00007836 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
Sebastian Redlcc152642011-10-16 18:19:06 +00007837 AA_Assigning);
7838 } else {
7839 ImplicitConversionSequence ICS =
7840 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7841 /*SuppressUserConversions=*/false,
7842 /*AllowExplicit=*/false,
7843 /*InOverloadResolution=*/false,
7844 /*CStyle=*/false,
7845 /*AllowObjCWritebackConversion=*/false);
7846 if (ICS.isFailure())
7847 return Incompatible;
Richard Smithe15a3702016-10-06 23:12:58 +00007848 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
Sebastian Redlcc152642011-10-16 18:19:06 +00007849 ICS, AA_Assigning);
7850 }
Richard Smithe15a3702016-10-06 23:12:58 +00007851 if (RHS.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00007852 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00007853 Sema::AssignConvertType result = Compatible;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007854 if (getLangOpts().ObjCAutoRefCount &&
Richard Smithe15a3702016-10-06 23:12:58 +00007855 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00007856 result = IncompatibleObjCWeakRef;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00007857 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00007858 }
7859
7860 // FIXME: Currently, we fall through and treat C++ classes like C
7861 // structures.
Eli Friedman0dfb8892011-10-06 23:00:33 +00007862 // FIXME: We also fall through for atomics; not sure what should
7863 // happen there, though.
George Burgess IV5f21c712015-10-12 19:57:04 +00007864 } else if (RHS.get()->getType() == Context.OverloadTy) {
7865 // As a set of extensions to C, we support overloading on functions. These
7866 // functions need to be resolved here.
7867 DeclAccessPair DAP;
7868 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7869 RHS.get(), LHSType, /*Complain=*/false, DAP))
7870 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7871 else
7872 return Incompatible;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007873 }
Douglas Gregor9a657932008-10-21 23:43:52 +00007874
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00007875 // C99 6.5.16.1p1: the left operand is a pointer and the right is
7876 // a null pointer constant.
Richard Smithe934d7c2013-11-21 01:53:02 +00007877 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7878 LHSType->isBlockPointerType()) &&
7879 RHS.get()->isNullPointerConstant(Context,
7880 Expr::NPC_ValueDependentIsNull)) {
George Burgess IV60bc9722016-01-13 23:36:34 +00007881 if (Diagnose || ConvertRHS) {
7882 CastKind Kind;
7883 CXXCastPath Path;
7884 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7885 /*IgnoreBaseAccess=*/false, Diagnose);
7886 if (ConvertRHS)
7887 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7888 }
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00007889 return Compatible;
7890 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007891
Chris Lattnere6dcd502007-10-16 02:55:40 +00007892 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007893 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00007894 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00007895 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00007896 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00007897 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00007898 if (!LHSType->isReferenceType()) {
George Burgess IV45461812015-10-11 20:13:20 +00007899 // FIXME: We potentially allocate here even if ConvertRHS is false.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007900 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
Richard Trieueb299142011-09-06 20:40:12 +00007901 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007902 return Incompatible;
7903 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00007904
Fariborz Jahaniana57d91c22014-07-25 19:45:01 +00007905 Expr *PRE = RHS.get()->IgnoreParenCasts();
George Burgess IV60bc9722016-01-13 23:36:34 +00007906 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7907 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
Fariborz Jahaniana57d91c22014-07-25 19:45:01 +00007908 if (PDecl && !PDecl->hasDefinition()) {
7909 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7910 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7911 }
7912 }
7913
John McCall8cb679e2010-11-15 09:13:47 +00007914 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007915 Sema::AssignConvertType result =
George Burgess IV45461812015-10-11 20:13:20 +00007916 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007917
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00007918 // C99 6.5.16.1p2: The value of the right operand is converted to the
7919 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00007920 // CheckAssignmentConstraints allows the left-hand side to be a reference,
7921 // so that we can use references in built-in functions even in C.
7922 // The getNonReferenceType() call makes sure that the resulting expression
7923 // does not have reference type.
Fariborz Jahanian374089e2013-07-31 17:12:26 +00007924 if (result != Incompatible && RHS.get()->getType() != LHSType) {
7925 QualType Ty = LHSType.getNonLValueExprType(Context);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007926 Expr *E = RHS.get();
Bob Wilsonf5c53b82016-02-13 01:41:41 +00007927
7928 // Check for various Objective-C errors. If we are not reporting
7929 // diagnostics and just checking for errors, e.g., during overload
7930 // resolution, return Incompatible to indicate the failure.
7931 if (getLangOpts().ObjCAutoRefCount &&
7932 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7933 Diagnose, DiagnoseCFAudited) != ACR_okay) {
7934 if (!Diagnose)
7935 return Incompatible;
7936 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00007937 if (getLangOpts().ObjC1 &&
George Burgess IV60bc9722016-01-13 23:36:34 +00007938 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7939 E->getType(), E, Diagnose) ||
7940 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
Bob Wilsonf5c53b82016-02-13 01:41:41 +00007941 if (!Diagnose)
7942 return Incompatible;
7943 // Replace the expression with a corrected version and continue so we
7944 // can find further errors.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007945 RHS = E;
Fariborz Jahanian381edf52013-12-16 22:54:37 +00007946 return Compatible;
7947 }
7948
George Burgess IV45461812015-10-11 20:13:20 +00007949 if (ConvertRHS)
7950 RHS = ImpCastExprToType(E, Ty, Kind);
Fariborz Jahanian374089e2013-07-31 17:12:26 +00007951 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00007952 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007953}
7954
Richard Trieueb299142011-09-06 20:40:12 +00007955QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7956 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007957 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00007958 << LHS.get()->getType() << RHS.get()->getType()
7959 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00007960 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00007961}
7962
Stephen Canon3ba640d2014-04-03 10:33:25 +00007963/// Try to convert a value of non-vector type to a vector type by converting
7964/// the type to the element type of the vector and then performing a splat.
7965/// If the language is OpenCL, we only use conversions that promote scalar
7966/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7967/// for float->int.
John McCall9b595db2014-02-04 23:58:19 +00007968///
7969/// \param scalar - if non-null, actually perform the conversions
7970/// \return true if the operation fails (but without diagnosing the failure)
Stephen Canon3ba640d2014-04-03 10:33:25 +00007971static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
John McCall9b595db2014-02-04 23:58:19 +00007972 QualType scalarTy,
7973 QualType vectorEltTy,
7974 QualType vectorTy) {
7975 // The conversion to apply to the scalar before splatting it,
7976 // if necessary.
7977 CastKind scalarCast = CK_Invalid;
Stephen Canon3ba640d2014-04-03 10:33:25 +00007978
John McCall9b595db2014-02-04 23:58:19 +00007979 if (vectorEltTy->isIntegralType(S.Context)) {
Stephen Canon3ba640d2014-04-03 10:33:25 +00007980 if (!scalarTy->isIntegralType(S.Context))
7981 return true;
7982 if (S.getLangOpts().OpenCL &&
7983 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
7984 return true;
7985 scalarCast = CK_IntegralCast;
John McCall9b595db2014-02-04 23:58:19 +00007986 } else if (vectorEltTy->isRealFloatingType()) {
7987 if (scalarTy->isRealFloatingType()) {
Stephen Canon3ba640d2014-04-03 10:33:25 +00007988 if (S.getLangOpts().OpenCL &&
7989 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
7990 return true;
7991 scalarCast = CK_FloatingCast;
John McCall9b595db2014-02-04 23:58:19 +00007992 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00007993 else if (scalarTy->isIntegralType(S.Context))
7994 scalarCast = CK_IntegralToFloating;
7995 else
7996 return true;
John McCall9b595db2014-02-04 23:58:19 +00007997 } else {
7998 return true;
7999 }
8000
8001 // Adjust scalar if desired.
8002 if (scalar) {
8003 if (scalarCast != CK_Invalid)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008004 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8005 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
John McCall9b595db2014-02-04 23:58:19 +00008006 }
8007 return false;
8008}
8009
Richard Trieu859d23f2011-09-06 21:01:04 +00008010QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00008011 SourceLocation Loc, bool IsCompAssign,
8012 bool AllowBothBool,
8013 bool AllowBoolConversions) {
Richard Smith508ebf32011-10-28 03:31:48 +00008014 if (!IsCompAssign) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008015 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
Richard Smith508ebf32011-10-28 03:31:48 +00008016 if (LHS.isInvalid())
8017 return QualType();
8018 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008019 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
Richard Smith508ebf32011-10-28 03:31:48 +00008020 if (RHS.isInvalid())
8021 return QualType();
8022
Mike Stump4e1f26a2009-02-19 03:04:26 +00008023 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00008024 // For example, "const float" and "float" are equivalent.
John McCall9b595db2014-02-04 23:58:19 +00008025 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8026 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00008027
John McCall9b595db2014-02-04 23:58:19 +00008028 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8029 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8030 assert(LHSVecType || RHSVecType);
8031
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00008032 // AltiVec-style "vector bool op vector bool" combinations are allowed
8033 // for some operators but not others.
8034 if (!AllowBothBool &&
8035 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8036 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8037 return InvalidOperands(Loc, LHS, RHS);
8038
8039 // If the vector types are identical, return.
8040 if (Context.hasSameType(LHSType, RHSType))
8041 return LHSType;
8042
John McCall9b595db2014-02-04 23:58:19 +00008043 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8044 if (LHSVecType && RHSVecType &&
Richard Trieu859d23f2011-09-06 21:01:04 +00008045 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
John McCall9b595db2014-02-04 23:58:19 +00008046 if (isa<ExtVectorType>(LHSVecType)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008047 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
Richard Trieu859d23f2011-09-06 21:01:04 +00008048 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00008049 }
8050
Richard Trieuba63ce62011-09-09 01:45:06 +00008051 if (!IsCompAssign)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008052 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
Richard Trieu859d23f2011-09-06 21:01:04 +00008053 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00008054 }
8055
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00008056 // AllowBoolConversions says that bool and non-bool AltiVec vectors
8057 // can be mixed, with the result being the non-bool type. The non-bool
8058 // operand must have integer element type.
8059 if (AllowBoolConversions && LHSVecType && RHSVecType &&
8060 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8061 (Context.getTypeSize(LHSVecType->getElementType()) ==
8062 Context.getTypeSize(RHSVecType->getElementType()))) {
8063 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8064 LHSVecType->getElementType()->isIntegerType() &&
8065 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8066 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8067 return LHSType;
8068 }
8069 if (!IsCompAssign &&
8070 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8071 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8072 RHSVecType->getElementType()->isIntegerType()) {
8073 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8074 return RHSType;
8075 }
8076 }
8077
Stephen Canon3ba640d2014-04-03 10:33:25 +00008078 // If there's an ext-vector type and a scalar, try to convert the scalar to
8079 // the vector element type and splat.
Bruno Cardoso Lopesc08cd4e2016-09-30 22:19:38 +00008080 // FIXME: this should also work for regular vector types as supported in GCC.
Stephen Canon3ba640d2014-04-03 10:33:25 +00008081 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
8082 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8083 LHSVecType->getElementType(), LHSType))
8084 return LHSType;
8085 }
8086 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008087 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8088 LHSType, RHSVecType->getElementType(),
8089 RHSType))
Stephen Canon3ba640d2014-04-03 10:33:25 +00008090 return RHSType;
8091 }
8092
Bruno Cardoso Lopesc08cd4e2016-09-30 22:19:38 +00008093 // FIXME: The code below also handles convertion between vectors and
8094 // non-scalars, we should break this down into fine grained specific checks
8095 // and emit proper diagnostics.
Reid Klecknere1a16462016-04-14 21:03:38 +00008096 QualType VecType = LHSVecType ? LHSType : RHSType;
Bruno Cardoso Lopesc08cd4e2016-09-30 22:19:38 +00008097 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8098 QualType OtherType = LHSVecType ? RHSType : LHSType;
8099 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8100 if (isLaxVectorConversion(OtherType, VecType)) {
8101 // If we're allowing lax vector conversions, only the total (data) size
8102 // needs to be the same. For non compound assignment, if one of the types is
8103 // scalar, the result is always the vector type.
8104 if (!IsCompAssign) {
8105 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8106 return VecType;
8107 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8108 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8109 // type. Note that this is already done by non-compound assignments in
8110 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8111 // <1 x T> -> T. The result is also a vector type.
8112 } else if (OtherType->isExtVectorType() ||
8113 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8114 ExprResult *RHSExpr = &RHS;
8115 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8116 return VecType;
8117 }
Eli Friedman1408bc92011-06-23 18:10:35 +00008118 }
8119
John McCall9b595db2014-02-04 23:58:19 +00008120 // Okay, the expression is invalid.
8121
8122 // If there's a non-vector, non-real operand, diagnose that.
8123 if ((!RHSVecType && !RHSType->isRealType()) ||
8124 (!LHSVecType && !LHSType->isRealType())) {
Argyrios Kyrtzidisd07dcdb2014-01-07 07:59:31 +00008125 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
John McCall9b595db2014-02-04 23:58:19 +00008126 << LHSType << RHSType
8127 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Argyrios Kyrtzidisd07dcdb2014-01-07 07:59:31 +00008128 return QualType();
8129 }
8130
Alexey Baderf961e752015-08-30 18:06:39 +00008131 // OpenCL V1.1 6.2.6.p1:
8132 // If the operands are of more than one vector type, then an error shall
8133 // occur. Implicit conversions between vector types are not permitted, per
8134 // section 6.2.1.
8135 if (getLangOpts().OpenCL &&
8136 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8137 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8138 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8139 << RHSType;
8140 return QualType();
8141 }
8142
John McCall9b595db2014-02-04 23:58:19 +00008143 // Otherwise, use the generic diagnostic.
Chris Lattner377d1f82008-11-18 22:52:51 +00008144 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John McCall9b595db2014-02-04 23:58:19 +00008145 << LHSType << RHSType
Richard Trieu859d23f2011-09-06 21:01:04 +00008146 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00008147 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00008148}
8149
Richard Trieuf8916e12011-09-16 00:53:10 +00008150// checkArithmeticNull - Detect when a NULL constant is used improperly in an
8151// expression. These are mainly cases where the null pointer is used as an
8152// integer instead of a pointer.
8153static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8154 SourceLocation Loc, bool IsCompare) {
8155 // The canonical way to check for a GNU null is with isNullPointerConstant,
8156 // but we use a bit of a hack here for speed; this is a relatively
8157 // hot path, and isNullPointerConstant is slow.
8158 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8159 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8160
8161 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8162
8163 // Avoid analyzing cases where the result will either be invalid (and
8164 // diagnosed as such) or entirely valid and not something to warn about.
8165 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8166 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8167 return;
8168
8169 // Comparison operations would not make sense with a null pointer no matter
8170 // what the other expression is.
8171 if (!IsCompare) {
8172 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8173 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8174 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8175 return;
8176 }
8177
8178 // The rest of the operations only make sense with a null pointer
8179 // if the other expression is a pointer.
8180 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8181 NonNullType->canDecayToPointerType())
8182 return;
8183
8184 S.Diag(Loc, diag::warn_null_in_comparison_operation)
8185 << LHSNull /* LHS is NULL */ << NonNullType
8186 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8187}
8188
Davide Italianof76da1d2015-08-01 10:13:39 +00008189static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8190 ExprResult &RHS,
8191 SourceLocation Loc, bool IsDiv) {
8192 // Check for division/remainder by zero.
Davide Italianof76da1d2015-08-01 10:13:39 +00008193 llvm::APSInt RHSValue;
8194 if (!RHS.get()->isValueDependent() &&
8195 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8196 S.DiagRuntimeBehavior(Loc, RHS.get(),
Craig Topperda7b27f2015-11-17 05:40:09 +00008197 S.PDiag(diag::warn_remainder_division_by_zero)
8198 << IsDiv << RHS.get()->getSourceRange());
Davide Italianof76da1d2015-08-01 10:13:39 +00008199}
8200
Richard Trieu859d23f2011-09-06 21:01:04 +00008201QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00008202 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008203 bool IsCompAssign, bool IsDiv) {
Richard Trieuf8916e12011-09-16 00:53:10 +00008204 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8205
Richard Trieu859d23f2011-09-06 21:01:04 +00008206 if (LHS.get()->getType()->isVectorType() ||
8207 RHS.get()->getType()->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00008208 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8209 /*AllowBothBool*/getLangOpts().AltiVec,
8210 /*AllowBoolConversions*/false);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008211
Richard Trieuba63ce62011-09-09 01:45:06 +00008212 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00008213 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00008214 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00008215
David Chisnallfa35df62012-01-16 17:27:18 +00008216
Eli Friedman93ee5ca2012-06-16 02:19:17 +00008217 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu859d23f2011-09-06 21:01:04 +00008218 return InvalidOperands(Loc, LHS, RHS);
Davide Italianof76da1d2015-08-01 10:13:39 +00008219 if (IsDiv)
8220 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
Chris Lattnerfaa54172010-01-12 21:23:57 +00008221 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00008222}
8223
Chris Lattnerfaa54172010-01-12 21:23:57 +00008224QualType Sema::CheckRemainderOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00008225 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00008226 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8227
Richard Trieu859d23f2011-09-06 21:01:04 +00008228 if (LHS.get()->getType()->isVectorType() ||
8229 RHS.get()->getType()->isVectorType()) {
8230 if (LHS.get()->getType()->hasIntegerRepresentation() &&
8231 RHS.get()->getType()->hasIntegerRepresentation())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00008232 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8233 /*AllowBothBool*/getLangOpts().AltiVec,
8234 /*AllowBoolConversions*/false);
Richard Trieu859d23f2011-09-06 21:01:04 +00008235 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00008236 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00008237
Richard Trieuba63ce62011-09-09 01:45:06 +00008238 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00008239 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00008240 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00008241
Eli Friedman93ee5ca2012-06-16 02:19:17 +00008242 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu859d23f2011-09-06 21:01:04 +00008243 return InvalidOperands(Loc, LHS, RHS);
Davide Italianof76da1d2015-08-01 10:13:39 +00008244 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
Chris Lattnerfaa54172010-01-12 21:23:57 +00008245 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008246}
8247
Chandler Carruthc9332212011-06-27 08:02:19 +00008248/// \brief Diagnose invalid arithmetic on two void pointers.
8249static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00008250 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008251 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00008252 ? diag::err_typecheck_pointer_arith_void_type
8253 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00008254 << 1 /* two pointers */ << LHSExpr->getSourceRange()
8255 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00008256}
8257
8258/// \brief Diagnose invalid arithmetic on a void pointer.
8259static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8260 Expr *Pointer) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008261 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00008262 ? diag::err_typecheck_pointer_arith_void_type
8263 : diag::ext_gnu_void_ptr)
8264 << 0 /* one pointer */ << Pointer->getSourceRange();
8265}
8266
8267/// \brief Diagnose invalid arithmetic on two function pointers.
8268static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8269 Expr *LHS, Expr *RHS) {
8270 assert(LHS->getType()->isAnyPointerType());
8271 assert(RHS->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008272 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00008273 ? diag::err_typecheck_pointer_arith_function_type
8274 : diag::ext_gnu_ptr_func_arith)
8275 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8276 // We only show the second type if it differs from the first.
8277 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8278 RHS->getType())
8279 << RHS->getType()->getPointeeType()
8280 << LHS->getSourceRange() << RHS->getSourceRange();
8281}
8282
8283/// \brief Diagnose invalid arithmetic on a function pointer.
8284static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8285 Expr *Pointer) {
8286 assert(Pointer->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008287 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00008288 ? diag::err_typecheck_pointer_arith_function_type
8289 : diag::ext_gnu_ptr_func_arith)
8290 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8291 << 0 /* one pointer, so only one type */
8292 << Pointer->getSourceRange();
8293}
8294
Richard Trieu993f3ab2011-09-12 18:08:02 +00008295/// \brief Emit error if Operand is incomplete pointer type
Richard Trieuaba22802011-09-02 02:15:37 +00008296///
8297/// \returns True if pointer has incomplete type
8298static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8299 Expr *Operand) {
David Majnemercf7d1642015-02-12 21:07:34 +00008300 QualType ResType = Operand->getType();
8301 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8302 ResType = ResAtomicType->getValueType();
8303
8304 assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8305 QualType PointeeTy = ResType->getPointeeType();
John McCallf2538342012-07-31 05:14:30 +00008306 return S.RequireCompleteType(Loc, PointeeTy,
8307 diag::err_typecheck_arithmetic_incomplete_type,
8308 PointeeTy, Operand->getSourceRange());
Richard Trieuaba22802011-09-02 02:15:37 +00008309}
8310
Chandler Carruthc9332212011-06-27 08:02:19 +00008311/// \brief Check the validity of an arithmetic pointer operand.
8312///
8313/// If the operand has pointer type, this code will check for pointer types
8314/// which are invalid in arithmetic operations. These will be diagnosed
8315/// appropriately, including whether or not the use is supported as an
8316/// extension.
8317///
8318/// \returns True when the operand is valid to use (even if as an extension).
8319static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8320 Expr *Operand) {
David Majnemercf7d1642015-02-12 21:07:34 +00008321 QualType ResType = Operand->getType();
8322 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8323 ResType = ResAtomicType->getValueType();
Chandler Carruthc9332212011-06-27 08:02:19 +00008324
David Majnemercf7d1642015-02-12 21:07:34 +00008325 if (!ResType->isAnyPointerType()) return true;
8326
8327 QualType PointeeTy = ResType->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00008328 if (PointeeTy->isVoidType()) {
8329 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00008330 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00008331 }
8332 if (PointeeTy->isFunctionType()) {
8333 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00008334 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00008335 }
8336
Richard Trieuaba22802011-09-02 02:15:37 +00008337 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00008338
8339 return true;
8340}
8341
8342/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8343/// operands.
8344///
8345/// This routine will diagnose any invalid arithmetic on pointer operands much
8346/// like \see checkArithmeticOpPointerOperand. However, it has special logic
8347/// for emitting a single diagnostic even for operations where both LHS and RHS
8348/// are (potentially problematic) pointers.
8349///
8350/// \returns True when the operand is valid to use (even if as an extension).
8351static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00008352 Expr *LHSExpr, Expr *RHSExpr) {
8353 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8354 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00008355 if (!isLHSPointer && !isRHSPointer) return true;
8356
8357 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00008358 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8359 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00008360
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00008361 // if both are pointers check if operation is valid wrt address spaces
Anastasia Stulovae6e08232015-09-30 13:49:55 +00008362 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00008363 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8364 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8365 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8366 S.Diag(Loc,
8367 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8368 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8369 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8370 return false;
8371 }
8372 }
8373
Chandler Carruthc9332212011-06-27 08:02:19 +00008374 // Check for arithmetic on pointers to incomplete types.
8375 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8376 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8377 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00008378 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8379 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8380 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00008381
David Blaikiebbafb8a2012-03-11 07:00:24 +00008382 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00008383 }
8384
8385 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8386 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8387 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00008388 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8389 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8390 RHSExpr);
8391 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00008392
David Blaikiebbafb8a2012-03-11 07:00:24 +00008393 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00008394 }
8395
John McCallf2538342012-07-31 05:14:30 +00008396 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8397 return false;
8398 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8399 return false;
Richard Trieuaba22802011-09-02 02:15:37 +00008400
Chandler Carruthc9332212011-06-27 08:02:19 +00008401 return true;
8402}
8403
Nico Weberccec40d2012-03-02 22:01:22 +00008404/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8405/// literal.
8406static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8407 Expr *LHSExpr, Expr *RHSExpr) {
8408 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8409 Expr* IndexExpr = RHSExpr;
8410 if (!StrExpr) {
8411 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8412 IndexExpr = LHSExpr;
8413 }
8414
8415 bool IsStringPlusInt = StrExpr &&
8416 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
David Majnemer7e217452014-12-15 10:00:35 +00008417 if (!IsStringPlusInt || IndexExpr->isValueDependent())
Nico Weberccec40d2012-03-02 22:01:22 +00008418 return;
8419
8420 llvm::APSInt index;
8421 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8422 unsigned StrLenWithNull = StrExpr->getLength() + 1;
8423 if (index.isNonNegative() &&
8424 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8425 index.isUnsigned()))
8426 return;
8427 }
8428
8429 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8430 Self.Diag(OpLoc, diag::warn_string_plus_int)
8431 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8432
8433 // Only print a fixit for "str" + int, not for int + "str".
8434 if (IndexExpr == RHSExpr) {
Craig Topper07fa1762015-11-15 02:31:46 +00008435 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
Jordan Rose55659412013-10-25 16:52:00 +00008436 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
Nico Weberccec40d2012-03-02 22:01:22 +00008437 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8438 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8439 << FixItHint::CreateInsertion(EndLoc, "]");
8440 } else
Jordan Rose55659412013-10-25 16:52:00 +00008441 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8442}
8443
8444/// \brief Emit a warning when adding a char literal to a string.
8445static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8446 Expr *LHSExpr, Expr *RHSExpr) {
Daniel Marjamaki36859002014-12-15 20:22:33 +00008447 const Expr *StringRefExpr = LHSExpr;
Jordan Rose55659412013-10-25 16:52:00 +00008448 const CharacterLiteral *CharExpr =
8449 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
Daniel Marjamaki36859002014-12-15 20:22:33 +00008450
8451 if (!CharExpr) {
Jordan Rose55659412013-10-25 16:52:00 +00008452 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
Daniel Marjamaki36859002014-12-15 20:22:33 +00008453 StringRefExpr = RHSExpr;
Jordan Rose55659412013-10-25 16:52:00 +00008454 }
8455
8456 if (!CharExpr || !StringRefExpr)
8457 return;
8458
8459 const QualType StringType = StringRefExpr->getType();
8460
8461 // Return if not a PointerType.
8462 if (!StringType->isAnyPointerType())
8463 return;
8464
8465 // Return if not a CharacterType.
8466 if (!StringType->getPointeeType()->isAnyCharacterType())
8467 return;
8468
8469 ASTContext &Ctx = Self.getASTContext();
8470 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8471
8472 const QualType CharType = CharExpr->getType();
8473 if (!CharType->isAnyCharacterType() &&
8474 CharType->isIntegerType() &&
8475 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8476 Self.Diag(OpLoc, diag::warn_string_plus_char)
8477 << DiagRange << Ctx.CharTy;
8478 } else {
8479 Self.Diag(OpLoc, diag::warn_string_plus_char)
8480 << DiagRange << CharExpr->getType();
8481 }
8482
8483 // Only print a fixit for str + char, not for char + str.
8484 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
Craig Topper07fa1762015-11-15 02:31:46 +00008485 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
Jordan Rose55659412013-10-25 16:52:00 +00008486 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8487 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8488 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8489 << FixItHint::CreateInsertion(EndLoc, "]");
8490 } else {
8491 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8492 }
Nico Weberccec40d2012-03-02 22:01:22 +00008493}
8494
Richard Trieu993f3ab2011-09-12 18:08:02 +00008495/// \brief Emit error when two pointers are incompatible.
Richard Trieub10c6312011-09-01 22:53:23 +00008496static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00008497 Expr *LHSExpr, Expr *RHSExpr) {
8498 assert(LHSExpr->getType()->isAnyPointerType());
8499 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00008500 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00008501 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8502 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00008503}
8504
Craig Toppera92ffb02015-12-10 08:51:49 +00008505// C99 6.5.6
8506QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8507 SourceLocation Loc, BinaryOperatorKind Opc,
8508 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00008509 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8510
Richard Trieu4ae7e972011-09-06 21:13:51 +00008511 if (LHS.get()->getType()->isVectorType() ||
8512 RHS.get()->getType()->isVectorType()) {
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00008513 QualType compType = CheckVectorOperands(
8514 LHS, RHS, Loc, CompLHSTy,
8515 /*AllowBothBool*/getLangOpts().AltiVec,
8516 /*AllowBoolConversions*/getLangOpts().ZVector);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008517 if (CompLHSTy) *CompLHSTy = compType;
8518 return compType;
8519 }
Steve Naroff7a5af782007-07-13 16:58:59 +00008520
Richard Trieu4ae7e972011-09-06 21:13:51 +00008521 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8522 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00008523 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00008524
Jordan Rose55659412013-10-25 16:52:00 +00008525 // Diagnose "string literal" '+' int and string '+' "char literal".
8526 if (Opc == BO_Add) {
Nico Weberccec40d2012-03-02 22:01:22 +00008527 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
Jordan Rose55659412013-10-25 16:52:00 +00008528 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8529 }
Nico Weberccec40d2012-03-02 22:01:22 +00008530
Steve Naroffe4718892007-04-27 18:30:00 +00008531 // handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00008532 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008533 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00008534 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008535 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00008536
John McCallf2538342012-07-31 05:14:30 +00008537 // Type-checking. Ultimately the pointer's going to be in PExp;
8538 // note that we bias towards the LHS being the pointer.
8539 Expr *PExp = LHS.get(), *IExp = RHS.get();
Eli Friedman8e122982008-05-18 18:08:51 +00008540
John McCallf2538342012-07-31 05:14:30 +00008541 bool isObjCPointer;
8542 if (PExp->getType()->isPointerType()) {
8543 isObjCPointer = false;
8544 } else if (PExp->getType()->isObjCObjectPointerType()) {
8545 isObjCPointer = true;
8546 } else {
8547 std::swap(PExp, IExp);
8548 if (PExp->getType()->isPointerType()) {
8549 isObjCPointer = false;
8550 } else if (PExp->getType()->isObjCObjectPointerType()) {
8551 isObjCPointer = true;
8552 } else {
8553 return InvalidOperands(Loc, LHS, RHS);
8554 }
8555 }
8556 assert(PExp->getType()->isAnyPointerType());
Chandler Carruthc9332212011-06-27 08:02:19 +00008557
Richard Trieub420bca2011-09-12 18:37:54 +00008558 if (!IExp->getType()->isIntegerType())
8559 return InvalidOperands(Loc, LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00008560
Richard Trieub420bca2011-09-12 18:37:54 +00008561 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8562 return QualType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008563
John McCallf2538342012-07-31 05:14:30 +00008564 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
Richard Trieub420bca2011-09-12 18:37:54 +00008565 return QualType();
8566
8567 // Check array bounds for pointer arithemtic
8568 CheckArrayAccess(PExp, IExp);
8569
8570 if (CompLHSTy) {
8571 QualType LHSTy = Context.isPromotableBitField(LHS.get());
8572 if (LHSTy.isNull()) {
8573 LHSTy = LHS.get()->getType();
8574 if (LHSTy->isPromotableIntegerType())
8575 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00008576 }
Richard Trieub420bca2011-09-12 18:37:54 +00008577 *CompLHSTy = LHSTy;
Eli Friedman8e122982008-05-18 18:08:51 +00008578 }
8579
Richard Trieub420bca2011-09-12 18:37:54 +00008580 return PExp->getType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00008581}
8582
Chris Lattner2a3569b2008-04-07 05:30:13 +00008583// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00008584QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00008585 SourceLocation Loc,
8586 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00008587 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8588
Richard Trieu4ae7e972011-09-06 21:13:51 +00008589 if (LHS.get()->getType()->isVectorType() ||
8590 RHS.get()->getType()->isVectorType()) {
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00008591 QualType compType = CheckVectorOperands(
8592 LHS, RHS, Loc, CompLHSTy,
8593 /*AllowBothBool*/getLangOpts().AltiVec,
8594 /*AllowBoolConversions*/getLangOpts().ZVector);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008595 if (CompLHSTy) *CompLHSTy = compType;
8596 return compType;
8597 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008598
Richard Trieu4ae7e972011-09-06 21:13:51 +00008599 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8600 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00008601 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00008602
Chris Lattner4d62f422007-12-09 21:53:25 +00008603 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008604
Chris Lattner4d62f422007-12-09 21:53:25 +00008605 // Handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00008606 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008607 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00008608 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008609 }
Mike Stump11289f42009-09-09 15:08:12 +00008610
Chris Lattner4d62f422007-12-09 21:53:25 +00008611 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00008612 if (LHS.get()->getType()->isAnyPointerType()) {
8613 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00008614
Chris Lattner12bdebb2009-04-24 23:50:08 +00008615 // Diagnose bad cases where we step over interface counts.
John McCallf2538342012-07-31 05:14:30 +00008616 if (LHS.get()->getType()->isObjCObjectPointerType() &&
8617 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00008618 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00008619
Chris Lattner4d62f422007-12-09 21:53:25 +00008620 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00008621 if (RHS.get()->getType()->isIntegerType()) {
8622 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00008623 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00008624
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008625 // Check array bounds for pointer arithemtic
Craig Topperc3ec1492014-05-26 06:22:03 +00008626 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
Richard Smith13f67182011-12-16 19:31:14 +00008627 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008628
Richard Trieu4ae7e972011-09-06 21:13:51 +00008629 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8630 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00008631 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008632
Chris Lattner4d62f422007-12-09 21:53:25 +00008633 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00008634 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00008635 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00008636 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00008637
David Blaikiebbafb8a2012-03-11 07:00:24 +00008638 if (getLangOpts().CPlusPlus) {
Eli Friedman168fe152009-05-16 13:54:38 +00008639 // Pointee types must be the same: C++ [expr.add]
8640 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00008641 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00008642 }
8643 } else {
8644 // Pointee types must be compatible C99 6.5.6p3
8645 if (!Context.typesAreCompatible(
8646 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8647 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00008648 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00008649 return QualType();
8650 }
Chris Lattner4d62f422007-12-09 21:53:25 +00008651 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008652
Chandler Carruthc9332212011-06-27 08:02:19 +00008653 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00008654 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00008655 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008656
Richard Smith84c6b3d2013-09-10 21:34:14 +00008657 // The pointee type may have zero size. As an extension, a structure or
8658 // union may have zero size or an array may have zero length. In this
8659 // case subtraction does not make sense.
8660 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8661 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8662 if (ElementSize.isZero()) {
8663 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8664 << rpointee.getUnqualifiedType()
8665 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8666 }
8667 }
8668
Richard Trieu4ae7e972011-09-06 21:13:51 +00008669 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00008670 return Context.getPointerDiffType();
8671 }
8672 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008673
Richard Trieu4ae7e972011-09-06 21:13:51 +00008674 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008675}
8676
Douglas Gregor0bf31402010-10-08 23:50:27 +00008677static bool isScopedEnumerationType(QualType T) {
Richard Smith43d3f552015-01-14 00:33:10 +00008678 if (const EnumType *ET = T->getAs<EnumType>())
Douglas Gregor0bf31402010-10-08 23:50:27 +00008679 return ET->getDecl()->isScoped();
8680 return false;
8681}
8682
Richard Trieue4a19fb2011-09-06 21:21:28 +00008683static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Craig Toppera92ffb02015-12-10 08:51:49 +00008684 SourceLocation Loc, BinaryOperatorKind Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00008685 QualType LHSType) {
David Tweed042e0882013-01-07 16:43:27 +00008686 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8687 // so skip remaining warnings as we don't want to modify values within Sema.
8688 if (S.getLangOpts().OpenCL)
8689 return;
8690
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008691 llvm::APSInt Right;
8692 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00008693 if (RHS.get()->isValueDependent() ||
Davide Italiano346048a2015-03-26 21:37:49 +00008694 !RHS.get()->EvaluateAsInt(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008695 return;
8696
8697 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00008698 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00008699 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00008700 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008701 return;
8702 }
8703 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00008704 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008705 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00008706 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00008707 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00008708 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008709 return;
8710 }
8711 if (Opc != BO_Shl)
8712 return;
8713
8714 // When left shifting an ICE which is signed, we can check for overflow which
8715 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8716 // integers have defined behavior modulo one more than the maximum value
8717 // representable in the result type, so never warn for those.
8718 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00008719 if (LHS.get()->isValueDependent() ||
Davide Italianobf0f7752015-07-06 18:02:09 +00008720 LHSType->hasUnsignedIntegerRepresentation() ||
8721 !LHS.get()->EvaluateAsInt(Left, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008722 return;
Davide Italianobf0f7752015-07-06 18:02:09 +00008723
8724 // If LHS does not have a signed type and non-negative value
8725 // then, the behavior is undefined. Warn about it.
James Molloy59802322016-08-16 09:45:36 +00008726 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
Davide Italianobf0f7752015-07-06 18:02:09 +00008727 S.DiagRuntimeBehavior(Loc, LHS.get(),
8728 S.PDiag(diag::warn_shift_lhs_negative)
8729 << LHS.get()->getSourceRange());
8730 return;
8731 }
8732
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008733 llvm::APInt ResultBits =
8734 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8735 if (LeftBits.uge(ResultBits))
8736 return;
8737 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8738 Result = Result.shl(Right);
8739
Ted Kremenek70f05fd2011-06-15 00:54:52 +00008740 // Print the bit representation of the signed integer as an unsigned
8741 // hexadecimal number.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008742 SmallString<40> HexResult;
Ted Kremenek70f05fd2011-06-15 00:54:52 +00008743 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8744
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008745 // If we are only missing a sign bit, this is less likely to result in actual
8746 // bugs -- if the result is cast back to an unsigned type, it will have the
8747 // expected value. Thus we place this behind a different warning that can be
8748 // turned off separately if needed.
8749 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00008750 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Yaron Keren92e1b622015-03-18 10:17:07 +00008751 << HexResult << LHSType
Richard Trieue4a19fb2011-09-06 21:21:28 +00008752 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008753 return;
8754 }
8755
8756 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00008757 << HexResult.str() << Result.getMinSignedBits() << LHSType
8758 << Left.getBitWidth() << LHS.get()->getSourceRange()
8759 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008760}
8761
Andrey Bokhanko1d31e452016-08-12 11:22:12 +00008762/// \brief Return the resulting type when a vector is shifted
Sameer Sahasrabuddhea75db662015-02-25 05:48:23 +00008763/// by a scalar or vector shift amount.
Andrey Bokhanko1d31e452016-08-12 11:22:12 +00008764static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
8765 SourceLocation Loc, bool IsCompAssign) {
Sameer Sahasrabuddhea75db662015-02-25 05:48:23 +00008766 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
Akira Hatanaka81986712016-09-15 22:19:25 +00008767 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
8768 !LHS.get()->getType()->isVectorType()) {
Sameer Sahasrabuddhea75db662015-02-25 05:48:23 +00008769 S.Diag(Loc, diag::err_shift_rhs_only_vector)
8770 << RHS.get()->getType() << LHS.get()->getType()
8771 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8772 return QualType();
8773 }
8774
8775 if (!IsCompAssign) {
8776 LHS = S.UsualUnaryConversions(LHS.get());
8777 if (LHS.isInvalid()) return QualType();
8778 }
8779
8780 RHS = S.UsualUnaryConversions(RHS.get());
8781 if (RHS.isInvalid()) return QualType();
8782
8783 QualType LHSType = LHS.get()->getType();
Akira Hatanaka81986712016-09-15 22:19:25 +00008784 // Note that LHS might be a scalar because the routine calls not only in
8785 // OpenCL case.
8786 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
8787 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
Sameer Sahasrabuddhea75db662015-02-25 05:48:23 +00008788
8789 // Note that RHS might not be a vector.
8790 QualType RHSType = RHS.get()->getType();
8791 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8792 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8793
Akira Hatanaka81986712016-09-15 22:19:25 +00008794 // The operands need to be integers.
Sameer Sahasrabuddhea75db662015-02-25 05:48:23 +00008795 if (!LHSEleType->isIntegerType()) {
8796 S.Diag(Loc, diag::err_typecheck_expect_int)
8797 << LHS.get()->getType() << LHS.get()->getSourceRange();
8798 return QualType();
8799 }
8800
8801 if (!RHSEleType->isIntegerType()) {
8802 S.Diag(Loc, diag::err_typecheck_expect_int)
8803 << RHS.get()->getType() << RHS.get()->getSourceRange();
8804 return QualType();
8805 }
8806
Akira Hatanaka81986712016-09-15 22:19:25 +00008807 if (!LHSVecTy) {
8808 assert(RHSVecTy);
8809 if (IsCompAssign)
8810 return RHSType;
8811 if (LHSEleType != RHSEleType) {
8812 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
8813 LHSEleType = RHSEleType;
8814 }
8815 QualType VecTy =
8816 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
8817 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
8818 LHSType = VecTy;
8819 } else if (RHSVecTy) {
Sameer Sahasrabuddhea75db662015-02-25 05:48:23 +00008820 // OpenCL v1.1 s6.3.j says that for vector types, the operators
8821 // are applied component-wise. So if RHS is a vector, then ensure
8822 // that the number of elements is the same as LHS...
8823 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8824 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8825 << LHS.get()->getType() << RHS.get()->getType()
8826 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8827 return QualType();
8828 }
Andrey Bokhanko9941ca82016-10-19 12:06:10 +00008829 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
8830 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
8831 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
8832 if (LHSBT != RHSBT &&
8833 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
8834 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
8835 << LHS.get()->getType() << RHS.get()->getType()
8836 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8837 }
8838 }
Sameer Sahasrabuddhea75db662015-02-25 05:48:23 +00008839 } else {
8840 // ...else expand RHS to match the number of elements in LHS.
8841 QualType VecTy =
8842 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8843 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8844 }
8845
8846 return LHSType;
8847}
8848
Chris Lattner2a3569b2008-04-07 05:30:13 +00008849// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00008850QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Craig Toppera92ffb02015-12-10 08:51:49 +00008851 SourceLocation Loc, BinaryOperatorKind Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008852 bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00008853 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8854
Nate Begemane46ee9a2009-10-25 02:26:48 +00008855 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00008856 if (LHS.get()->getType()->isVectorType() ||
Sameer Sahasrabuddhea75db662015-02-25 05:48:23 +00008857 RHS.get()->getType()->isVectorType()) {
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00008858 if (LangOpts.ZVector) {
8859 // The shift operators for the z vector extensions work basically
Andrey Bokhanko1d31e452016-08-12 11:22:12 +00008860 // like general shifts, except that neither the LHS nor the RHS is
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00008861 // allowed to be a "vector bool".
8862 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8863 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8864 return InvalidOperands(Loc, LHS, RHS);
8865 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8866 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8867 return InvalidOperands(Loc, LHS, RHS);
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00008868 }
Andrey Bokhanko1d31e452016-08-12 11:22:12 +00008869 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
Sameer Sahasrabuddhea75db662015-02-25 05:48:23 +00008870 }
Nate Begemane46ee9a2009-10-25 02:26:48 +00008871
Chris Lattner5c11c412007-12-12 05:47:28 +00008872 // Shifts don't perform usual arithmetic conversions, they just do integer
8873 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008874
John McCall57cdd882010-12-16 19:28:59 +00008875 // For the LHS, do usual unary conversions, but then reset them away
8876 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00008877 ExprResult OldLHS = LHS;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008878 LHS = UsualUnaryConversions(LHS.get());
Richard Trieue4a19fb2011-09-06 21:21:28 +00008879 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00008880 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00008881 QualType LHSType = LHS.get()->getType();
Richard Trieuba63ce62011-09-09 01:45:06 +00008882 if (IsCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00008883
8884 // The RHS is simpler.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008885 RHS = UsualUnaryConversions(RHS.get());
Richard Trieue4a19fb2011-09-06 21:21:28 +00008886 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00008887 return QualType();
Douglas Gregor8997dac2013-04-16 15:41:08 +00008888 QualType RHSType = RHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00008889
Douglas Gregor8997dac2013-04-16 15:41:08 +00008890 // C99 6.5.7p2: Each of the operands shall have integer type.
8891 if (!LHSType->hasIntegerRepresentation() ||
8892 !RHSType->hasIntegerRepresentation())
8893 return InvalidOperands(Loc, LHS, RHS);
8894
8895 // C++0x: Don't allow scoped enums. FIXME: Use something better than
8896 // hasIntegerRepresentation() above instead of this.
8897 if (isScopedEnumerationType(LHSType) ||
8898 isScopedEnumerationType(RHSType)) {
8899 return InvalidOperands(Loc, LHS, RHS);
8900 }
Ryan Flynnf53fab82009-08-07 16:20:20 +00008901 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00008902 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00008903
Chris Lattner5c11c412007-12-12 05:47:28 +00008904 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00008905 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00008906}
8907
Chandler Carruth17773fc2010-07-10 12:30:03 +00008908static bool IsWithinTemplateSpecialization(Decl *D) {
8909 if (DeclContext *DC = D->getDeclContext()) {
8910 if (isa<ClassTemplateSpecializationDecl>(DC))
8911 return true;
8912 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8913 return FD->isFunctionTemplateSpecialization();
8914 }
8915 return false;
8916}
8917
Richard Trieueea56f72011-09-02 03:48:46 +00008918/// If two different enums are compared, raise a warning.
Ted Kremenekf2ca8ec2013-01-30 19:10:21 +00008919static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8920 Expr *RHS) {
8921 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8922 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00008923
8924 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8925 if (!LHSEnumType)
8926 return;
8927 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8928 if (!RHSEnumType)
8929 return;
8930
8931 // Ignore anonymous enums.
8932 if (!LHSEnumType->getDecl()->getIdentifier())
8933 return;
8934 if (!RHSEnumType->getDecl()->getIdentifier())
8935 return;
8936
8937 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8938 return;
8939
8940 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8941 << LHSStrippedType << RHSStrippedType
Ted Kremenekf2ca8ec2013-01-30 19:10:21 +00008942 << LHS->getSourceRange() << RHS->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00008943}
8944
Richard Trieudd82a5c2011-09-02 02:55:45 +00008945/// \brief Diagnose bad pointer comparisons.
8946static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00008947 ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00008948 bool IsError) {
8949 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieudd82a5c2011-09-02 02:55:45 +00008950 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00008951 << LHS.get()->getType() << RHS.get()->getType()
8952 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00008953}
8954
8955/// \brief Returns false if the pointers are converted to a composite type,
8956/// true otherwise.
8957static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00008958 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00008959 // C++ [expr.rel]p2:
8960 // [...] Pointer conversions (4.10) and qualification
8961 // conversions (4.4) are performed on pointer operands (or on
8962 // a pointer operand and a null pointer constant) to bring
8963 // them to their composite pointer type. [...]
8964 //
8965 // C++ [expr.eq]p1 uses the same notion for (in)equality
8966 // comparisons of pointers.
8967
Richard Trieu1762d7c2011-09-06 21:27:33 +00008968 QualType LHSType = LHS.get()->getType();
8969 QualType RHSType = RHS.get()->getType();
Richard Smith5e9746f2016-10-21 22:00:42 +00008970 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
8971 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
Richard Trieudd82a5c2011-09-02 02:55:45 +00008972
Richard Smith5e9746f2016-10-21 22:00:42 +00008973 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
Richard Trieudd82a5c2011-09-02 02:55:45 +00008974 if (T.isNull()) {
Richard Smith5e9746f2016-10-21 22:00:42 +00008975 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
8976 (RHSType->isPointerType() || RHSType->isMemberPointerType()))
8977 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
8978 else
8979 S.InvalidOperands(Loc, LHS, RHS);
Richard Trieudd82a5c2011-09-02 02:55:45 +00008980 return true;
8981 }
8982
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008983 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
8984 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00008985 return false;
8986}
8987
8988static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00008989 ExprResult &LHS,
8990 ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00008991 bool IsError) {
8992 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
8993 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00008994 << LHS.get()->getType() << RHS.get()->getType()
8995 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00008996}
8997
Jordan Rosed49a33e2012-06-08 21:14:25 +00008998static bool isObjCObjectLiteral(ExprResult &E) {
Jordan Rosee2028132012-11-09 23:55:21 +00008999 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
Jordan Rosed49a33e2012-06-08 21:14:25 +00009000 case Stmt::ObjCArrayLiteralClass:
9001 case Stmt::ObjCDictionaryLiteralClass:
9002 case Stmt::ObjCStringLiteralClass:
9003 case Stmt::ObjCBoxedExprClass:
9004 return true;
9005 default:
9006 // Note that ObjCBoolLiteral is NOT an object literal!
9007 return false;
9008 }
9009}
9010
Jordan Rose7660f782012-07-17 17:46:40 +00009011static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
Benjamin Kramer25c05102013-02-15 15:17:50 +00009012 const ObjCObjectPointerType *Type =
9013 LHS->getType()->getAs<ObjCObjectPointerType>();
9014
9015 // If this is not actually an Objective-C object, bail out.
9016 if (!Type)
Jordan Rose7660f782012-07-17 17:46:40 +00009017 return false;
Benjamin Kramer25c05102013-02-15 15:17:50 +00009018
9019 // Get the LHS object's interface type.
9020 QualType InterfaceType = Type->getPointeeType();
Jordan Rose7660f782012-07-17 17:46:40 +00009021
9022 // If the RHS isn't an Objective-C object, bail out.
9023 if (!RHS->getType()->isObjCObjectPointerType())
9024 return false;
9025
9026 // Try to find the -isEqual: method.
9027 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9028 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9029 InterfaceType,
9030 /*instance=*/true);
9031 if (!Method) {
9032 if (Type->isObjCIdType()) {
9033 // For 'id', just check the global pool.
9034 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
Fariborz Jahanian890803f2015-04-15 17:26:21 +00009035 /*receiverId=*/true);
Jordan Rose7660f782012-07-17 17:46:40 +00009036 } else {
9037 // Check protocols.
Benjamin Kramer25c05102013-02-15 15:17:50 +00009038 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
Jordan Rose7660f782012-07-17 17:46:40 +00009039 /*instance=*/true);
9040 }
9041 }
9042
9043 if (!Method)
9044 return false;
9045
Alp Toker03376dc2014-07-07 09:02:20 +00009046 QualType T = Method->parameters()[0]->getType();
Jordan Rose7660f782012-07-17 17:46:40 +00009047 if (!T->isObjCObjectPointerType())
9048 return false;
Alp Toker314cc812014-01-25 16:55:45 +00009049
9050 QualType R = Method->getReturnType();
Jordan Rose7660f782012-07-17 17:46:40 +00009051 if (!R->isScalarType())
9052 return false;
9053
9054 return true;
9055}
9056
Ted Kremenek01a33f82012-12-21 21:59:36 +00009057Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9058 FromE = FromE->IgnoreParenImpCasts();
9059 switch (FromE->getStmtClass()) {
9060 default:
9061 break;
9062 case Stmt::ObjCStringLiteralClass:
9063 // "string literal"
9064 return LK_String;
9065 case Stmt::ObjCArrayLiteralClass:
9066 // "array literal"
9067 return LK_Array;
9068 case Stmt::ObjCDictionaryLiteralClass:
9069 // "dictionary literal"
9070 return LK_Dictionary;
Ted Kremenek64873352012-12-21 22:46:35 +00009071 case Stmt::BlockExprClass:
9072 return LK_Block;
Ted Kremenek01a33f82012-12-21 21:59:36 +00009073 case Stmt::ObjCBoxedExprClass: {
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009074 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
Ted Kremenek01a33f82012-12-21 21:59:36 +00009075 switch (Inner->getStmtClass()) {
9076 case Stmt::IntegerLiteralClass:
9077 case Stmt::FloatingLiteralClass:
9078 case Stmt::CharacterLiteralClass:
9079 case Stmt::ObjCBoolLiteralExprClass:
9080 case Stmt::CXXBoolLiteralExprClass:
9081 // "numeric literal"
9082 return LK_Numeric;
9083 case Stmt::ImplicitCastExprClass: {
9084 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9085 // Boolean literals can be represented by implicit casts.
9086 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9087 return LK_Numeric;
9088 break;
9089 }
9090 default:
9091 break;
9092 }
9093 return LK_Boxed;
9094 }
9095 }
9096 return LK_None;
9097}
9098
Jordan Rose7660f782012-07-17 17:46:40 +00009099static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9100 ExprResult &LHS, ExprResult &RHS,
9101 BinaryOperator::Opcode Opc){
Jordan Rose63ffaa82012-07-17 17:46:48 +00009102 Expr *Literal;
9103 Expr *Other;
9104 if (isObjCObjectLiteral(LHS)) {
9105 Literal = LHS.get();
9106 Other = RHS.get();
9107 } else {
9108 Literal = RHS.get();
9109 Other = LHS.get();
9110 }
9111
9112 // Don't warn on comparisons against nil.
9113 Other = Other->IgnoreParenCasts();
9114 if (Other->isNullPointerConstant(S.getASTContext(),
9115 Expr::NPC_ValueDependentIsNotNull))
9116 return;
Jordan Rosed49a33e2012-06-08 21:14:25 +00009117
Jordan Roseea70bf72012-07-17 17:46:44 +00009118 // This should be kept in sync with warn_objc_literal_comparison.
Ted Kremenek01a33f82012-12-21 21:59:36 +00009119 // LK_String should always be after the other literals, since it has its own
9120 // warning flag.
9121 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
Ted Kremenek64873352012-12-21 22:46:35 +00009122 assert(LiteralKind != Sema::LK_Block);
Ted Kremenek01a33f82012-12-21 21:59:36 +00009123 if (LiteralKind == Sema::LK_None) {
Jordan Rosed49a33e2012-06-08 21:14:25 +00009124 llvm_unreachable("Unknown Objective-C object literal kind");
9125 }
9126
Ted Kremenek01a33f82012-12-21 21:59:36 +00009127 if (LiteralKind == Sema::LK_String)
Jordan Roseea70bf72012-07-17 17:46:44 +00009128 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9129 << Literal->getSourceRange();
9130 else
9131 S.Diag(Loc, diag::warn_objc_literal_comparison)
9132 << LiteralKind << Literal->getSourceRange();
Jordan Rosed49a33e2012-06-08 21:14:25 +00009133
Jordan Rose7660f782012-07-17 17:46:40 +00009134 if (BinaryOperator::isEqualityOp(Opc) &&
9135 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9136 SourceLocation Start = LHS.get()->getLocStart();
Craig Topper07fa1762015-11-15 02:31:46 +00009137 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
Fariborz Jahanian4dca1d32013-02-01 20:04:49 +00009138 CharSourceRange OpRange =
Craig Topper07fa1762015-11-15 02:31:46 +00009139 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
Jordan Rosef9198032012-07-09 16:54:44 +00009140
Jordan Rose7660f782012-07-17 17:46:40 +00009141 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9142 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
Fariborz Jahanian4dca1d32013-02-01 20:04:49 +00009143 << FixItHint::CreateReplacement(OpRange, " isEqual:")
Jordan Rose7660f782012-07-17 17:46:40 +00009144 << FixItHint::CreateInsertion(End, "]");
Jordan Rosed49a33e2012-06-08 21:14:25 +00009145 }
Jordan Rosed49a33e2012-06-08 21:14:25 +00009146}
9147
Nico Weber44f6f2e2016-10-27 16:32:06 +00009148/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9149static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9150 ExprResult &RHS, SourceLocation Loc,
9151 BinaryOperatorKind Opc) {
Richard Trieubb4b8942013-06-10 18:52:07 +00009152 // Check that left hand side is !something.
Richard Trieu949abc32013-07-04 00:50:18 +00009153 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
Richard Trieubb4b8942013-06-10 18:52:07 +00009154 if (!UO || UO->getOpcode() != UO_LNot) return;
9155
9156 // Only check if the right hand side is non-bool arithmetic type.
Richard Trieu1cd076e2015-08-19 21:33:54 +00009157 if (RHS.get()->isKnownToHaveBooleanValue()) return;
Richard Trieubb4b8942013-06-10 18:52:07 +00009158
9159 // Make sure that the something in !something is not bool.
9160 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
Richard Trieu1cd076e2015-08-19 21:33:54 +00009161 if (SubExpr->isKnownToHaveBooleanValue()) return;
Richard Trieubb4b8942013-06-10 18:52:07 +00009162
9163 // Emit warning.
Nico Weber44f6f2e2016-10-27 16:32:06 +00009164 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9165 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9166 << Loc << IsBitwiseOp;
Richard Trieubb4b8942013-06-10 18:52:07 +00009167
9168 // First note suggest !(x < y)
9169 SourceLocation FirstOpen = SubExpr->getLocStart();
9170 SourceLocation FirstClose = RHS.get()->getLocEnd();
Craig Topper07fa1762015-11-15 02:31:46 +00009171 FirstClose = S.getLocForEndOfToken(FirstClose);
Eli Friedmanef0b4a32013-07-22 23:09:39 +00009172 if (FirstClose.isInvalid())
9173 FirstOpen = SourceLocation();
Richard Trieubb4b8942013-06-10 18:52:07 +00009174 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
Nico Weber44f6f2e2016-10-27 16:32:06 +00009175 << IsBitwiseOp
Richard Trieubb4b8942013-06-10 18:52:07 +00009176 << FixItHint::CreateInsertion(FirstOpen, "(")
9177 << FixItHint::CreateInsertion(FirstClose, ")");
9178
9179 // Second note suggests (!x) < y
9180 SourceLocation SecondOpen = LHS.get()->getLocStart();
9181 SourceLocation SecondClose = LHS.get()->getLocEnd();
Craig Topper07fa1762015-11-15 02:31:46 +00009182 SecondClose = S.getLocForEndOfToken(SecondClose);
Eli Friedmanef0b4a32013-07-22 23:09:39 +00009183 if (SecondClose.isInvalid())
9184 SecondOpen = SourceLocation();
Richard Trieubb4b8942013-06-10 18:52:07 +00009185 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9186 << FixItHint::CreateInsertion(SecondOpen, "(")
9187 << FixItHint::CreateInsertion(SecondClose, ")");
9188}
9189
Eli Friedman5a722e92013-09-06 03:13:09 +00009190// Get the decl for a simple expression: a reference to a variable,
9191// an implicit C++ field reference, or an implicit ObjC ivar reference.
9192static ValueDecl *getCompareDecl(Expr *E) {
9193 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9194 return DR->getDecl();
9195 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9196 if (Ivar->isFreeIvar())
9197 return Ivar->getDecl();
9198 }
9199 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9200 if (Mem->isImplicitAccess())
9201 return Mem->getMemberDecl();
9202 }
Craig Topperc3ec1492014-05-26 06:22:03 +00009203 return nullptr;
Eli Friedman5a722e92013-09-06 03:13:09 +00009204}
9205
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00009206// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00009207QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Craig Toppera92ffb02015-12-10 08:51:49 +00009208 SourceLocation Loc, BinaryOperatorKind Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009209 bool IsRelational) {
Richard Trieuf8916e12011-09-16 00:53:10 +00009210 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9211
Chris Lattner9a152e22009-12-05 05:40:13 +00009212 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00009213 if (LHS.get()->getType()->isVectorType() ||
9214 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00009215 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009216
Richard Trieub80728f2011-09-06 21:43:51 +00009217 QualType LHSType = LHS.get()->getType();
9218 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00009219
Richard Trieub80728f2011-09-06 21:43:51 +00009220 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9221 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00009222
Ted Kremenekf2ca8ec2013-01-30 19:10:21 +00009223 checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
Nico Weber44f6f2e2016-10-27 16:32:06 +00009224 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
Chandler Carruth712563b2011-02-17 08:37:06 +00009225
Richard Trieub80728f2011-09-06 21:43:51 +00009226 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuba63ce62011-09-09 01:45:06 +00009227 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieub80728f2011-09-06 21:43:51 +00009228 !LHS.get()->getLocStart().isMacroID() &&
Richard Trieu30bfa362013-11-02 02:11:23 +00009229 !RHS.get()->getLocStart().isMacroID() &&
9230 ActiveTemplateInstantiations.empty()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00009231 // For non-floating point types, check for self-comparisons of the form
9232 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
9233 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00009234 //
9235 // NOTE: Don't warn about comparison expressions resulting from macro
9236 // expansion. Also don't warn about comparisons which are only self
9237 // comparisons within a template specialization. The warnings should catch
9238 // obvious cases in the definition of the template anyways. The idea is to
9239 // warn when the typed comparison operator will always evaluate to the same
9240 // result.
Eli Friedman5a722e92013-09-06 03:13:09 +00009241 ValueDecl *DL = getCompareDecl(LHSStripped);
9242 ValueDecl *DR = getCompareDecl(RHSStripped);
9243 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009244 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
Eli Friedman5a722e92013-09-06 03:13:09 +00009245 << 0 // self-
9246 << (Opc == BO_EQ
9247 || Opc == BO_LE
9248 || Opc == BO_GE));
9249 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9250 !DL->getType()->isReferenceType() &&
9251 !DR->getType()->isReferenceType()) {
9252 // what is it always going to eval to?
9253 char always_evals_to;
9254 switch(Opc) {
9255 case BO_EQ: // e.g. array1 == array2
9256 always_evals_to = 0; // false
9257 break;
9258 case BO_NE: // e.g. array1 != array2
9259 always_evals_to = 1; // true
9260 break;
9261 default:
9262 // best we can say is 'a constant'
9263 always_evals_to = 2; // e.g. array1 <= array2
9264 break;
Douglas Gregorec170db2010-06-08 19:50:34 +00009265 }
Craig Topperc3ec1492014-05-26 06:22:03 +00009266 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
Eli Friedman5a722e92013-09-06 03:13:09 +00009267 << 1 // array
9268 << always_evals_to);
Chandler Carruth17773fc2010-07-10 12:30:03 +00009269 }
Mike Stump11289f42009-09-09 15:08:12 +00009270
Chris Lattner222b8bd2009-03-08 19:39:53 +00009271 if (isa<CastExpr>(LHSStripped))
9272 LHSStripped = LHSStripped->IgnoreParenCasts();
9273 if (isa<CastExpr>(RHSStripped))
9274 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00009275
Chris Lattner222b8bd2009-03-08 19:39:53 +00009276 // Warn about comparisons against a string constant (unless the other
9277 // operand is null), the user probably wants strcmp.
Craig Topperc3ec1492014-05-26 06:22:03 +00009278 Expr *literalString = nullptr;
9279 Expr *literalStringStripped = nullptr;
Chris Lattner222b8bd2009-03-08 19:39:53 +00009280 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009281 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00009282 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00009283 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00009284 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00009285 } else if ((isa<StringLiteral>(RHSStripped) ||
9286 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009287 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00009288 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00009289 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00009290 literalStringStripped = RHSStripped;
9291 }
9292
9293 if (literalString) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009294 DiagRuntimeBehavior(Loc, nullptr,
Douglas Gregor49862b82010-01-12 23:18:54 +00009295 PDiag(diag::warn_stringcompare)
9296 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00009297 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00009298 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00009299 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009300
Douglas Gregorec170db2010-06-08 19:50:34 +00009301 // C99 6.5.8p3 / C99 6.5.9p4
Eli Friedmane6d33952013-07-08 20:20:06 +00009302 UsualArithmeticConversions(LHS, RHS);
9303 if (LHS.isInvalid() || RHS.isInvalid())
9304 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00009305
Richard Trieub80728f2011-09-06 21:43:51 +00009306 LHSType = LHS.get()->getType();
9307 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00009308
Douglas Gregorca63811b2008-11-19 03:25:36 +00009309 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00009310 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00009311
Richard Trieuba63ce62011-09-09 01:45:06 +00009312 if (IsRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00009313 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00009314 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00009315 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00009316 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00009317 if (LHSType->hasFloatingRepresentation())
9318 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00009319
Richard Trieub80728f2011-09-06 21:43:51 +00009320 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00009321 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00009322 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009323
Richard Trieu3bb8b562014-02-26 02:36:06 +00009324 const Expr::NullPointerConstantKind LHSNullKind =
9325 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9326 const Expr::NullPointerConstantKind RHSNullKind =
9327 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9328 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9329 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9330
9331 if (!IsRelational && LHSIsNull != RHSIsNull) {
9332 bool IsEquality = Opc == BO_EQ;
9333 if (RHSIsNull)
9334 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9335 RHS.get()->getSourceRange());
9336 else
9337 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9338 LHS.get()->getSourceRange());
9339 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009340
Richard Smith5e9746f2016-10-21 22:00:42 +00009341 if ((LHSType->isIntegerType() && !LHSIsNull) ||
9342 (RHSType->isIntegerType() && !RHSIsNull)) {
9343 // Skip normal pointer conversion checks in this case; we have better
9344 // diagnostics for this below.
9345 } else if (getLangOpts().CPlusPlus) {
9346 // Equality comparison of a function pointer to a void pointer is invalid,
9347 // but we allow it as an extension.
9348 // FIXME: If we really want to allow this, should it be part of composite
9349 // pointer type computation so it works in conditionals too?
9350 if (!IsRelational &&
9351 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
9352 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
9353 // This is a gcc extension compatibility comparison.
9354 // In a SFINAE context, we treat this as a hard error to maintain
9355 // conformance with the C++ standard.
9356 diagnoseFunctionPointerToVoidComparison(
9357 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9358
9359 if (isSFINAEContext())
9360 return QualType();
9361
9362 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9363 return ResultTy;
9364 }
Richard Smith0c1c53e2016-10-21 02:36:37 +00009365
Richard Smith5e9746f2016-10-21 22:00:42 +00009366 // C++ [expr.eq]p2:
9367 // If at least one operand is a pointer [...] bring them to their
9368 // composite pointer type.
9369 // C++ [expr.rel]p2:
9370 // If both operands are pointers, [...] bring them to their composite
9371 // pointer type.
9372 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
9373 (IsRelational ? 2 : 1)) {
Renato Golin41189652016-10-21 08:03:49 +00009374 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9375 return QualType();
9376 else
9377 return ResultTy;
9378 }
Richard Smith5e9746f2016-10-21 22:00:42 +00009379 } else if (LHSType->isPointerType() &&
9380 RHSType->isPointerType()) { // C99 6.5.8p2
9381 // All of the following pointer-related warnings are GCC extensions, except
9382 // when handling null pointer constants.
9383 QualType LCanPointeeTy =
9384 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9385 QualType RCanPointeeTy =
9386 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9387
Eli Friedman16c209612009-08-23 00:27:47 +00009388 // C99 6.5.9p2 and C99 6.5.8p2
9389 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9390 RCanPointeeTy.getUnqualifiedType())) {
9391 // Valid unless a relational comparison of function pointers
Richard Trieuba63ce62011-09-09 01:45:06 +00009392 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman16c209612009-08-23 00:27:47 +00009393 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00009394 << LHSType << RHSType << LHS.get()->getSourceRange()
9395 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00009396 }
Richard Trieuba63ce62011-09-09 01:45:06 +00009397 } else if (!IsRelational &&
Eli Friedman16c209612009-08-23 00:27:47 +00009398 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9399 // Valid unless comparison between non-null pointer and function pointer
9400 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00009401 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00009402 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00009403 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00009404 } else {
9405 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00009406 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00009407 }
John McCall7684dde2011-03-11 04:25:25 +00009408 if (LCanPointeeTy != RCanPointeeTy) {
Anastasia Stulova2446b8b2015-12-11 17:41:19 +00009409 // Treat NULL constant as a special case in OpenCL.
9410 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
Anastasia Stulovae6e08232015-09-30 13:49:55 +00009411 const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9412 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9413 Diag(Loc,
9414 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9415 << LHSType << RHSType << 0 /* comparison */
9416 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9417 }
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00009418 }
David Tweede1468322013-12-11 13:39:46 +00009419 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9420 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9421 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9422 : CK_BitCast;
John McCall7684dde2011-03-11 04:25:25 +00009423 if (LHSIsNull && !RHSIsNull)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009424 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
John McCall7684dde2011-03-11 04:25:25 +00009425 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009426 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
John McCall7684dde2011-03-11 04:25:25 +00009427 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00009428 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00009429 }
Mike Stump11289f42009-09-09 15:08:12 +00009430
David Blaikiebbafb8a2012-03-11 07:00:24 +00009431 if (getLangOpts().CPlusPlus) {
Richard Smith5e9746f2016-10-21 22:00:42 +00009432 // C++ [expr.eq]p4:
9433 // Two operands of type std::nullptr_t or one operand of type
9434 // std::nullptr_t and the other a null pointer constant compare equal.
9435 if (!IsRelational && LHSIsNull && RHSIsNull) {
9436 if (LHSType->isNullPtrType()) {
9437 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9438 return ResultTy;
9439 }
9440 if (RHSType->isNullPtrType()) {
9441 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9442 return ResultTy;
9443 }
9444 }
9445
9446 // Comparison of Objective-C pointers and block pointers against nullptr_t.
9447 // These aren't covered by the composite pointer type rules.
9448 if (!IsRelational && RHSType->isNullPtrType() &&
9449 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
9450 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00009451 return ResultTy;
9452 }
Richard Smith5e9746f2016-10-21 22:00:42 +00009453 if (!IsRelational && LHSType->isNullPtrType() &&
9454 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
9455 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00009456 return ResultTy;
9457 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00009458
Richard Smith5e9746f2016-10-21 22:00:42 +00009459 if (IsRelational &&
9460 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
9461 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
9462 // HACK: Relational comparison of nullptr_t against a pointer type is
9463 // invalid per DR583, but we allow it within std::less<> and friends,
9464 // since otherwise common uses of it break.
9465 // FIXME: Consider removing this hack once LWG fixes std::less<> and
9466 // friends to have std::nullptr_t overload candidates.
9467 DeclContext *DC = CurContext;
9468 if (isa<FunctionDecl>(DC))
9469 DC = DC->getParent();
9470 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
9471 if (CTSD->isInStdNamespace() &&
9472 llvm::StringSwitch<bool>(CTSD->getName())
9473 .Cases("less", "less_equal", "greater", "greater_equal", true)
9474 .Default(false)) {
9475 if (RHSType->isNullPtrType())
9476 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9477 else
9478 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9479 return ResultTy;
9480 }
9481 }
9482 }
9483
9484 // C++ [expr.eq]p2:
9485 // If at least one operand is a pointer to member, [...] bring them to
9486 // their composite pointer type.
Richard Trieuba63ce62011-09-09 01:45:06 +00009487 if (!IsRelational &&
Richard Smith5e9746f2016-10-21 22:00:42 +00009488 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
Richard Trieub80728f2011-09-06 21:43:51 +00009489 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00009490 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00009491 else
9492 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00009493 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00009494
9495 // Handle scoped enumeration types specifically, since they don't promote
9496 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00009497 if (LHS.get()->getType()->isEnumeralType() &&
9498 Context.hasSameUnqualifiedType(LHS.get()->getType(),
9499 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00009500 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00009501 }
Mike Stump11289f42009-09-09 15:08:12 +00009502
Steve Naroff081c7422008-09-04 15:10:53 +00009503 // Handle block pointer types.
Richard Trieuba63ce62011-09-09 01:45:06 +00009504 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieub80728f2011-09-06 21:43:51 +00009505 RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00009506 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9507 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00009508
Steve Naroff081c7422008-09-04 15:10:53 +00009509 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00009510 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00009511 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00009512 << LHSType << RHSType << LHS.get()->getSourceRange()
9513 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00009514 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009515 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00009516 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00009517 }
John Wiegley01296292011-04-08 18:41:53 +00009518
Steve Naroffe18f94c2008-09-28 01:11:11 +00009519 // Allow block pointers to be compared with null pointer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00009520 if (!IsRelational
Richard Trieub80728f2011-09-06 21:43:51 +00009521 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9522 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00009523 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00009524 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00009525 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00009526 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00009527 ->getPointeeType()->isVoidType())))
9528 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00009529 << LHSType << RHSType << LHS.get()->getSourceRange()
9530 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00009531 }
John McCall7684dde2011-03-11 04:25:25 +00009532 if (LHSIsNull && !RHSIsNull)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009533 LHS = ImpCastExprToType(LHS.get(), RHSType,
John McCall9320b872011-09-09 05:25:32 +00009534 RHSType->isPointerType() ? CK_BitCast
9535 : CK_AnyPointerToBlockPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00009536 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009537 RHS = ImpCastExprToType(RHS.get(), LHSType,
John McCall9320b872011-09-09 05:25:32 +00009538 LHSType->isPointerType() ? CK_BitCast
9539 : CK_AnyPointerToBlockPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00009540 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00009541 }
Steve Naroff081c7422008-09-04 15:10:53 +00009542
Richard Trieub80728f2011-09-06 21:43:51 +00009543 if (LHSType->isObjCObjectPointerType() ||
9544 RHSType->isObjCObjectPointerType()) {
9545 const PointerType *LPT = LHSType->getAs<PointerType>();
9546 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00009547 if (LPT || RPT) {
9548 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9549 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009550
Steve Naroff753567f2008-11-17 19:49:16 +00009551 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00009552 !Context.typesAreCompatible(LHSType, RHSType)) {
9553 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00009554 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00009555 }
Fariborz Jahanian374089e2013-07-31 17:12:26 +00009556 if (LHSIsNull && !RHSIsNull) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009557 Expr *E = LHS.get();
Fariborz Jahanian374089e2013-07-31 17:12:26 +00009558 if (getLangOpts().ObjCAutoRefCount)
9559 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
9560 LHS = ImpCastExprToType(E, RHSType,
John McCall9320b872011-09-09 05:25:32 +00009561 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Fariborz Jahanian374089e2013-07-31 17:12:26 +00009562 }
9563 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009564 Expr *E = RHS.get();
Fariborz Jahanian374089e2013-07-31 17:12:26 +00009565 if (getLangOpts().ObjCAutoRefCount)
George Burgess IV60bc9722016-01-13 23:36:34 +00009566 CheckObjCARCConversion(SourceRange(), LHSType, E,
9567 CCK_ImplicitConversion, /*Diagnose=*/true,
9568 /*DiagnoseCFAudited=*/false, Opc);
Fariborz Jahanian374089e2013-07-31 17:12:26 +00009569 RHS = ImpCastExprToType(E, LHSType,
John McCall9320b872011-09-09 05:25:32 +00009570 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Fariborz Jahanian374089e2013-07-31 17:12:26 +00009571 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00009572 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00009573 }
Richard Trieub80728f2011-09-06 21:43:51 +00009574 if (LHSType->isObjCObjectPointerType() &&
9575 RHSType->isObjCObjectPointerType()) {
9576 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9577 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00009578 /*isError*/false);
Jordan Rosed49a33e2012-06-08 21:14:25 +00009579 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
Jordan Rose7660f782012-07-17 17:46:40 +00009580 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
Jordan Rosed49a33e2012-06-08 21:14:25 +00009581
John McCall7684dde2011-03-11 04:25:25 +00009582 if (LHSIsNull && !RHSIsNull)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009583 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00009584 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009585 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00009586 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00009587 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00009588 }
Richard Trieub80728f2011-09-06 21:43:51 +00009589 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9590 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00009591 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00009592 bool isError = false;
Douglas Gregor0064c592012-09-14 04:35:37 +00009593 if (LangOpts.DebuggerSupport) {
9594 // Under a debugger, allow the comparison of pointers to integers,
9595 // since users tend to want to compare addresses.
9596 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
Richard Smith5e9746f2016-10-21 22:00:42 +00009597 (RHSIsNull && RHSType->isIntegerType())) {
9598 if (IsRelational) {
9599 isError = getLangOpts().CPlusPlus;
9600 DiagID =
9601 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
9602 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9603 }
9604 } else if (getLangOpts().CPlusPlus) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00009605 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9606 isError = true;
Richard Smith5e9746f2016-10-21 22:00:42 +00009607 } else if (IsRelational)
9608 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9609 else
Chris Lattnerd99bd522009-08-23 00:03:44 +00009610 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00009611
Chris Lattnerd99bd522009-08-23 00:03:44 +00009612 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00009613 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00009614 << LHSType << RHSType << LHS.get()->getSourceRange()
9615 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00009616 if (isError)
9617 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00009618 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00009619
Richard Trieub80728f2011-09-06 21:43:51 +00009620 if (LHSType->isIntegerType())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009621 LHS = ImpCastExprToType(LHS.get(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00009622 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00009623 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009624 RHS = ImpCastExprToType(RHS.get(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00009625 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00009626 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00009627 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00009628
Steve Naroff4b191572008-09-04 16:56:14 +00009629 // Handle block pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00009630 if (!IsRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00009631 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009632 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00009633 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00009634 }
Richard Trieuba63ce62011-09-09 01:45:06 +00009635 if (!IsRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00009636 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009637 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00009638 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00009639 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00009640
Egor Churaev89831422016-12-23 14:55:49 +00009641 if (getLangOpts().OpenCLVersion >= 200) {
9642 if (LHSIsNull && RHSType->isQueueT()) {
9643 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9644 return ResultTy;
9645 }
9646
9647 if (LHSType->isQueueT() && RHSIsNull) {
9648 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9649 return ResultTy;
9650 }
9651 }
9652
Richard Trieub80728f2011-09-06 21:43:51 +00009653 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00009654}
9655
Tanya Lattner20248222012-01-16 21:02:28 +00009656
9657// Return a signed type that is of identical size and number of elements.
9658// For floating point vectors, return an integer type of identical size
9659// and number of elements.
9660QualType Sema::GetSignedVectorType(QualType V) {
9661 const VectorType *VTy = V->getAs<VectorType>();
9662 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9663 if (TypeSize == Context.getTypeSize(Context.CharTy))
9664 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9665 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9666 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9667 else if (TypeSize == Context.getTypeSize(Context.IntTy))
9668 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9669 else if (TypeSize == Context.getTypeSize(Context.LongTy))
9670 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9671 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9672 "Unhandled vector element size in vector compare");
9673 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9674}
9675
Nate Begeman191a6b12008-07-14 18:02:46 +00009676/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00009677/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00009678/// like a scalar comparison, a vector comparison produces a vector of integer
9679/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00009680QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00009681 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009682 bool IsRelational) {
Nate Begeman191a6b12008-07-14 18:02:46 +00009683 // Check to make sure we're operating on vectors of the same type and width,
9684 // Allowing one side to be a scalar of element type.
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00009685 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9686 /*AllowBothBool*/true,
9687 /*AllowBoolConversions*/getLangOpts().ZVector);
Nate Begeman191a6b12008-07-14 18:02:46 +00009688 if (vType.isNull())
9689 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009690
Richard Trieubcce2f72011-09-07 01:19:57 +00009691 QualType LHSType = LHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00009692
Anton Yartsev530deb92011-03-27 15:36:07 +00009693 // If AltiVec, the comparison results in a numeric type, i.e.
9694 // bool for C++, int for C
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00009695 if (getLangOpts().AltiVec &&
9696 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00009697 return Context.getLogicalOperationType();
9698
Nate Begeman191a6b12008-07-14 18:02:46 +00009699 // For non-floating point types, check for self-comparisons of the form
9700 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
9701 // often indicate logic errors in the program.
Richard Trieu30bfa362013-11-02 02:11:23 +00009702 if (!LHSType->hasFloatingRepresentation() &&
9703 ActiveTemplateInstantiations.empty()) {
Richard Smith508ebf32011-10-28 03:31:48 +00009704 if (DeclRefExpr* DRL
9705 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9706 if (DeclRefExpr* DRR
9707 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begeman191a6b12008-07-14 18:02:46 +00009708 if (DRL->getDecl() == DRR->getDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00009709 DiagRuntimeBehavior(Loc, nullptr,
Douglas Gregorec170db2010-06-08 19:50:34 +00009710 PDiag(diag::warn_comparison_always)
9711 << 0 // self-
9712 << 2 // "a constant"
9713 );
Nate Begeman191a6b12008-07-14 18:02:46 +00009714 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009715
Nate Begeman191a6b12008-07-14 18:02:46 +00009716 // Check for comparisons of floating point operands using != and ==.
Richard Trieuba63ce62011-09-09 01:45:06 +00009717 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikieca043222012-01-16 05:16:03 +00009718 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieubcce2f72011-09-07 01:19:57 +00009719 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00009720 }
Tanya Lattner20248222012-01-16 21:02:28 +00009721
9722 // Return a signed type for the vector.
Reid Klecknere1a16462016-04-14 21:03:38 +00009723 return GetSignedVectorType(vType);
Tanya Lattner20248222012-01-16 21:02:28 +00009724}
Mike Stump4e1f26a2009-02-19 03:04:26 +00009725
Tanya Lattner3dd33b22012-01-19 01:16:16 +00009726QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9727 SourceLocation Loc) {
Tanya Lattner20248222012-01-16 21:02:28 +00009728 // Ensure that either both operands are of the same vector type, or
9729 // one operand is of a vector type and the other is of its element type.
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00009730 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9731 /*AllowBothBool*/true,
9732 /*AllowBoolConversions*/false);
Joey Gouly7d00f002013-02-21 11:49:56 +00009733 if (vType.isNull())
9734 return InvalidOperands(Loc, LHS, RHS);
9735 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9736 vType->hasFloatingRepresentation())
Tanya Lattner20248222012-01-16 21:02:28 +00009737 return InvalidOperands(Loc, LHS, RHS);
9738
9739 return GetSignedVectorType(LHS.get()->getType());
Nate Begeman191a6b12008-07-14 18:02:46 +00009740}
9741
Nico Weber44f6f2e2016-10-27 16:32:06 +00009742inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
9743 SourceLocation Loc,
9744 BinaryOperatorKind Opc) {
Richard Trieuf8916e12011-09-16 00:53:10 +00009745 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9746
Nico Weber44f6f2e2016-10-27 16:32:06 +00009747 bool IsCompAssign =
9748 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
9749
Richard Trieubcce2f72011-09-07 01:19:57 +00009750 if (LHS.get()->getType()->isVectorType() ||
9751 RHS.get()->getType()->isVectorType()) {
9752 if (LHS.get()->getType()->hasIntegerRepresentation() &&
9753 RHS.get()->getType()->hasIntegerRepresentation())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00009754 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9755 /*AllowBothBool*/true,
9756 /*AllowBoolConversions*/getLangOpts().ZVector);
Richard Trieubcce2f72011-09-07 01:19:57 +00009757 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00009758 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00009759
Nico Weber44f6f2e2016-10-27 16:32:06 +00009760 if (Opc == BO_And)
9761 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9762
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009763 ExprResult LHSResult = LHS, RHSResult = RHS;
Richard Trieubcce2f72011-09-07 01:19:57 +00009764 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuba63ce62011-09-09 01:45:06 +00009765 IsCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00009766 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00009767 return QualType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009768 LHS = LHSResult.get();
9769 RHS = RHSResult.get();
Mike Stump4e1f26a2009-02-19 03:04:26 +00009770
Eli Friedman93ee5ca2012-06-16 02:19:17 +00009771 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00009772 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00009773 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00009774}
9775
Craig Toppera92ffb02015-12-10 08:51:49 +00009776// C99 6.5.[13,14]
9777inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9778 SourceLocation Loc,
9779 BinaryOperatorKind Opc) {
Tanya Lattner20248222012-01-16 21:02:28 +00009780 // Check vector operands differently.
9781 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9782 return CheckVectorLogicalOperands(LHS, RHS, Loc);
9783
Chris Lattner8406c512010-07-13 19:41:32 +00009784 // Diagnose cases where the user write a logical and/or but probably meant a
9785 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
9786 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00009787 if (LHS.get()->getType()->isIntegerType() &&
9788 !LHS.get()->getType()->isBooleanType() &&
9789 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00009790 // Don't warn in macros or template instantiations.
9791 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00009792 // If the RHS can be constant folded, and if it constant folds to something
9793 // that isn't 0 or 1 (which indicate a potential logical operation that
9794 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00009795 // Parens on the RHS are ignored.
Richard Smith00ab3ae2011-10-16 23:01:09 +00009796 llvm::APSInt Result;
9797 if (RHS.get()->EvaluateAsInt(Result, Context))
Argyrios Kyrtzidisd6eb2b92014-04-28 00:20:16 +00009798 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9799 !RHS.get()->getExprLoc().isMacroID()) ||
Richard Smith00ab3ae2011-10-16 23:01:09 +00009800 (Result != 0 && Result != 1)) {
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00009801 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00009802 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00009803 << (Opc == BO_LAnd ? "&&" : "||");
9804 // Suggest replacing the logical operator with the bitwise version
9805 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9806 << (Opc == BO_LAnd ? "&" : "|")
9807 << FixItHint::CreateReplacement(SourceRange(
Craig Topper07fa1762015-11-15 02:31:46 +00009808 Loc, getLocForEndOfToken(Loc)),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00009809 Opc == BO_LAnd ? "&" : "|");
9810 if (Opc == BO_LAnd)
9811 // Suggest replacing "Foo() && kNonZero" with "Foo()"
9812 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9813 << FixItHint::CreateRemoval(
Craig Topper07fa1762015-11-15 02:31:46 +00009814 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9815 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00009816 }
Chris Lattner938533d2010-07-24 01:10:11 +00009817 }
Joey Gouly7d00f002013-02-21 11:49:56 +00009818
David Blaikiebbafb8a2012-03-11 07:00:24 +00009819 if (!Context.getLangOpts().CPlusPlus) {
Joey Gouly7d00f002013-02-21 11:49:56 +00009820 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9821 // not operate on the built-in scalar and vector float types.
9822 if (Context.getLangOpts().OpenCL &&
9823 Context.getLangOpts().OpenCLVersion < 120) {
9824 if (LHS.get()->getType()->isFloatingType() ||
9825 RHS.get()->getType()->isFloatingType())
9826 return InvalidOperands(Loc, LHS, RHS);
9827 }
9828
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009829 LHS = UsualUnaryConversions(LHS.get());
Richard Trieubcce2f72011-09-07 01:19:57 +00009830 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00009831 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00009832
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009833 RHS = UsualUnaryConversions(RHS.get());
Richard Trieubcce2f72011-09-07 01:19:57 +00009834 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00009835 return QualType();
9836
Richard Trieubcce2f72011-09-07 01:19:57 +00009837 if (!LHS.get()->getType()->isScalarType() ||
9838 !RHS.get()->getType()->isScalarType())
9839 return InvalidOperands(Loc, LHS, RHS);
Fariborz Jahanian3365bfc2014-11-11 21:54:19 +00009840
Anders Carlsson2e7bc112009-11-23 21:47:44 +00009841 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00009842 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009843
John McCall4a2429a2010-06-04 00:29:51 +00009844 // The following is safe because we only use this method for
9845 // non-overloadable operands.
9846
Anders Carlsson2e7bc112009-11-23 21:47:44 +00009847 // C++ [expr.log.and]p1
9848 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00009849 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00009850 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9851 if (LHSRes.isInvalid())
9852 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009853 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00009854
Richard Trieubcce2f72011-09-07 01:19:57 +00009855 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9856 if (RHSRes.isInvalid())
9857 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009858 RHS = RHSRes;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009859
Anders Carlsson2e7bc112009-11-23 21:47:44 +00009860 // C++ [expr.log.and]p2
9861 // C++ [expr.log.or]p2
9862 // The result is a bool.
9863 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00009864}
9865
Fariborz Jahanian071caef2011-03-26 19:48:30 +00009866static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00009867 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9868 if (!ME) return false;
9869 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
Richard Smith4baaa5a2016-12-03 01:14:32 +00009870 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
9871 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
John McCall526ab472011-10-25 17:37:35 +00009872 if (!Base) return false;
Craig Topperc3ec1492014-05-26 06:22:03 +00009873 return Base->getMethodDecl() != nullptr;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00009874}
9875
John McCall5fa2ef42012-03-13 00:37:01 +00009876/// Is the given expression (which must be 'const') a reference to a
9877/// variable which was originally non-const, but which has become
9878/// 'const' due to being captured within a block?
9879enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9880static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9881 assert(E->isLValue() && E->getType().isConstQualified());
9882 E = E->IgnoreParens();
9883
9884 // Must be a reference to a declaration from an enclosing scope.
9885 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9886 if (!DRE) return NCCK_None;
Alexey Bataev19acc3d2015-01-12 10:17:46 +00009887 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
John McCall5fa2ef42012-03-13 00:37:01 +00009888
9889 // The declaration must be a variable which is not declared 'const'.
9890 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9891 if (!var) return NCCK_None;
9892 if (var->getType().isConstQualified()) return NCCK_None;
9893 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9894
9895 // Decide whether the first capture was for a block or a lambda.
Craig Topperc3ec1492014-05-26 06:22:03 +00009896 DeclContext *DC = S.CurContext, *Prev = nullptr;
Manman Renebe8cf52016-07-01 22:27:16 +00009897 // Decide whether the first capture was for a block or a lambda.
9898 while (DC) {
9899 // For init-capture, it is possible that the variable belongs to the
9900 // template pattern of the current context.
9901 if (auto *FD = dyn_cast<FunctionDecl>(DC))
9902 if (var->isInitCapture() &&
9903 FD->getTemplateInstantiationPattern() == var->getDeclContext())
9904 break;
9905 if (DC == var->getDeclContext())
9906 break;
Richard Smith75e3f692013-09-28 04:31:26 +00009907 Prev = DC;
John McCall5fa2ef42012-03-13 00:37:01 +00009908 DC = DC->getParent();
Richard Smith75e3f692013-09-28 04:31:26 +00009909 }
9910 // Unless we have an init-capture, we've gone one step too far.
9911 if (!var->isInitCapture())
9912 DC = Prev;
John McCall5fa2ef42012-03-13 00:37:01 +00009913 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9914}
9915
Richard Trieuaf7d76c2015-04-11 01:53:13 +00009916static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9917 Ty = Ty.getNonReferenceType();
9918 if (IsDereference && Ty->isPointerType())
9919 Ty = Ty->getPointeeType();
9920 return !Ty.isConstQualified();
9921}
9922
9923/// Emit the "read-only variable not assignable" error and print notes to give
9924/// more information about why the variable is not assignable, such as pointing
9925/// to the declaration of a const variable, showing that a method is const, or
9926/// that the function is returning a const reference.
9927static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9928 SourceLocation Loc) {
9929 // Update err_typecheck_assign_const and note_typecheck_assign_const
9930 // when this enum is changed.
9931 enum {
9932 ConstFunction,
9933 ConstVariable,
9934 ConstMember,
9935 ConstMethod,
9936 ConstUnknown, // Keep as last element
9937 };
9938
9939 SourceRange ExprRange = E->getSourceRange();
9940
9941 // Only emit one error on the first const found. All other consts will emit
9942 // a note to the error.
9943 bool DiagnosticEmitted = false;
9944
Vedant Kumare03e5952016-11-03 06:35:16 +00009945 // Track if the current expression is the result of a dereference, and if the
9946 // next checked expression is the result of a dereference.
Richard Trieuaf7d76c2015-04-11 01:53:13 +00009947 bool IsDereference = false;
9948 bool NextIsDereference = false;
9949
9950 // Loop to process MemberExpr chains.
9951 while (true) {
9952 IsDereference = NextIsDereference;
Richard Trieuaf7d76c2015-04-11 01:53:13 +00009953
Richard Smith4baaa5a2016-12-03 01:14:32 +00009954 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
Richard Trieuaf7d76c2015-04-11 01:53:13 +00009955 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9956 NextIsDereference = ME->isArrow();
9957 const ValueDecl *VD = ME->getMemberDecl();
9958 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9959 // Mutable fields can be modified even if the class is const.
9960 if (Field->isMutable()) {
9961 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9962 break;
9963 }
9964
9965 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9966 if (!DiagnosticEmitted) {
9967 S.Diag(Loc, diag::err_typecheck_assign_const)
9968 << ExprRange << ConstMember << false /*static*/ << Field
9969 << Field->getType();
9970 DiagnosticEmitted = true;
9971 }
9972 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9973 << ConstMember << false /*static*/ << Field << Field->getType()
9974 << Field->getSourceRange();
9975 }
9976 E = ME->getBase();
9977 continue;
9978 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
9979 if (VDecl->getType().isConstQualified()) {
9980 if (!DiagnosticEmitted) {
9981 S.Diag(Loc, diag::err_typecheck_assign_const)
9982 << ExprRange << ConstMember << true /*static*/ << VDecl
9983 << VDecl->getType();
9984 DiagnosticEmitted = true;
9985 }
9986 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9987 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
9988 << VDecl->getSourceRange();
9989 }
9990 // Static fields do not inherit constness from parents.
9991 break;
9992 }
9993 break;
9994 } // End MemberExpr
9995 break;
9996 }
9997
9998 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9999 // Function calls
10000 const FunctionDecl *FD = CE->getDirectCallee();
David Majnemerd39bcae2015-08-26 05:13:19 +000010001 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
Richard Trieuaf7d76c2015-04-11 01:53:13 +000010002 if (!DiagnosticEmitted) {
10003 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10004 << ConstFunction << FD;
10005 DiagnosticEmitted = true;
10006 }
10007 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10008 diag::note_typecheck_assign_const)
10009 << ConstFunction << FD << FD->getReturnType()
10010 << FD->getReturnTypeSourceRange();
10011 }
10012 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10013 // Point to variable declaration.
10014 if (const ValueDecl *VD = DRE->getDecl()) {
10015 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10016 if (!DiagnosticEmitted) {
10017 S.Diag(Loc, diag::err_typecheck_assign_const)
10018 << ExprRange << ConstVariable << VD << VD->getType();
10019 DiagnosticEmitted = true;
10020 }
10021 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10022 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10023 }
10024 }
10025 } else if (isa<CXXThisExpr>(E)) {
10026 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10027 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10028 if (MD->isConst()) {
10029 if (!DiagnosticEmitted) {
10030 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10031 << ConstMethod << MD;
10032 DiagnosticEmitted = true;
10033 }
10034 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10035 << ConstMethod << MD << MD->getSourceRange();
10036 }
10037 }
10038 }
10039 }
10040
10041 if (DiagnosticEmitted)
10042 return;
10043
10044 // Can't determine a more specific message, so display the generic error.
10045 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10046}
10047
Chris Lattner30bd3272008-11-18 01:22:49 +000010048/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
10049/// emit an error and return true. If so, return false.
10050static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianca5c5972012-04-10 17:30:10 +000010051 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Reid Klecknerf463a8a2016-04-29 00:37:43 +000010052
10053 S.CheckShadowingDeclModification(E, Loc);
10054
Daniel Dunbarc2223ab2009-04-15 00:08:05 +000010055 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +000010056 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +000010057 &Loc);
Eli Friedmanaa205c42013-06-27 01:36:36 +000010058 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
Fariborz Jahanian071caef2011-03-26 19:48:30 +000010059 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +000010060 if (IsLV == Expr::MLV_Valid)
10061 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +000010062
David Majnemer3e7743e2014-12-26 06:06:53 +000010063 unsigned DiagID = 0;
Chris Lattner30bd3272008-11-18 01:22:49 +000010064 bool NeedType = false;
10065 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +000010066 case Expr::MLV_ConstQualified:
John McCall5fa2ef42012-03-13 00:37:01 +000010067 // Use a specialized diagnostic when we're assigning to an object
10068 // from an enclosing function or block.
10069 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10070 if (NCCK == NCCK_Block)
David Majnemer3e7743e2014-12-26 06:06:53 +000010071 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
John McCall5fa2ef42012-03-13 00:37:01 +000010072 else
David Majnemer3e7743e2014-12-26 06:06:53 +000010073 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
John McCall5fa2ef42012-03-13 00:37:01 +000010074 break;
10075 }
10076
John McCalld4631322011-06-17 06:42:21 +000010077 // In ARC, use some specialized diagnostics for occasions where we
10078 // infer 'const'. These are always pseudo-strong variables.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010079 if (S.getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +000010080 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10081 if (declRef && isa<VarDecl>(declRef->getDecl())) {
10082 VarDecl *var = cast<VarDecl>(declRef->getDecl());
10083
John McCalld4631322011-06-17 06:42:21 +000010084 // Use the normal diagnostic if it's pseudo-__strong but the
10085 // user actually wrote 'const'.
10086 if (var->isARCPseudoStrong() &&
10087 (!var->getTypeSourceInfo() ||
10088 !var->getTypeSourceInfo()->getType().isConstQualified())) {
10089 // There are two pseudo-strong cases:
10090 // - self
John McCall31168b02011-06-15 23:02:42 +000010091 ObjCMethodDecl *method = S.getCurMethodDecl();
10092 if (method && var == method->getSelfDecl())
David Majnemer3e7743e2014-12-26 06:06:53 +000010093 DiagID = method->isClassMethod()
Ted Kremenek1fcdaa92011-11-14 21:59:25 +000010094 ? diag::err_typecheck_arc_assign_self_class_method
10095 : diag::err_typecheck_arc_assign_self;
John McCalld4631322011-06-17 06:42:21 +000010096
10097 // - fast enumeration variables
10098 else
David Majnemer3e7743e2014-12-26 06:06:53 +000010099 DiagID = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +000010100
John McCall31168b02011-06-15 23:02:42 +000010101 SourceRange Assign;
10102 if (Loc != OrigLoc)
10103 Assign = SourceRange(OrigLoc, OrigLoc);
David Majnemer3e7743e2014-12-26 06:06:53 +000010104 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
Richard Trieuaf7d76c2015-04-11 01:53:13 +000010105 // We need to preserve the AST regardless, so migration tool
John McCall31168b02011-06-15 23:02:42 +000010106 // can do its job.
10107 return false;
10108 }
10109 }
10110 }
10111
Richard Trieuaf7d76c2015-04-11 01:53:13 +000010112 // If none of the special cases above are triggered, then this is a
10113 // simple const assignment.
10114 if (DiagID == 0) {
10115 DiagnoseConstAssignment(S, E, Loc);
10116 return true;
10117 }
10118
John McCall31168b02011-06-15 23:02:42 +000010119 break;
Richard Smitha7bd4582015-05-22 01:14:39 +000010120 case Expr::MLV_ConstAddrSpace:
10121 DiagnoseConstAssignment(S, E, Loc);
10122 return true;
Mike Stump4e1f26a2009-02-19 03:04:26 +000010123 case Expr::MLV_ArrayType:
Richard Smitheb3cad52012-06-04 22:27:30 +000010124 case Expr::MLV_ArrayTemporary:
David Majnemer3e7743e2014-12-26 06:06:53 +000010125 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
Chris Lattner30bd3272008-11-18 01:22:49 +000010126 NeedType = true;
10127 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +000010128 case Expr::MLV_NotObjectType:
David Majnemer3e7743e2014-12-26 06:06:53 +000010129 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
Chris Lattner30bd3272008-11-18 01:22:49 +000010130 NeedType = true;
10131 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +000010132 case Expr::MLV_LValueCast:
David Majnemer3e7743e2014-12-26 06:06:53 +000010133 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
Chris Lattner30bd3272008-11-18 01:22:49 +000010134 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +000010135 case Expr::MLV_Valid:
10136 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +000010137 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +000010138 case Expr::MLV_MemberFunction:
10139 case Expr::MLV_ClassTemporary:
David Majnemer3e7743e2014-12-26 06:06:53 +000010140 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
Chris Lattner30bd3272008-11-18 01:22:49 +000010141 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +000010142 case Expr::MLV_IncompleteType:
10143 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +000010144 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010145 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner9bad62c2008-01-04 18:04:52 +000010146 case Expr::MLV_DuplicateVectorComponents:
David Majnemer3e7743e2014-12-26 06:06:53 +000010147 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
Chris Lattner30bd3272008-11-18 01:22:49 +000010148 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +000010149 case Expr::MLV_NoSetterProperty:
John McCall526ab472011-10-25 17:37:35 +000010150 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian071caef2011-03-26 19:48:30 +000010151 case Expr::MLV_InvalidMessageExpression:
Richard Smithf8812672016-12-02 22:38:31 +000010152 DiagID = diag::err_readonly_message_assignment;
Fariborz Jahanian071caef2011-03-26 19:48:30 +000010153 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +000010154 case Expr::MLV_SubObjCPropertySetting:
Richard Smithf8812672016-12-02 22:38:31 +000010155 DiagID = diag::err_no_subobject_property_setting;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +000010156 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +000010157 }
Steve Naroffad373bd2007-07-31 12:34:36 +000010158
Daniel Dunbarc2223ab2009-04-15 00:08:05 +000010159 SourceRange Assign;
10160 if (Loc != OrigLoc)
10161 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +000010162 if (NeedType)
David Majnemer3e7743e2014-12-26 06:06:53 +000010163 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +000010164 else
David Majnemer3e7743e2014-12-26 06:06:53 +000010165 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +000010166 return true;
10167}
10168
Nico Weberb8124d12012-07-03 02:03:06 +000010169static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10170 SourceLocation Loc,
10171 Sema &Sema) {
10172 // C / C++ fields
Nico Weber33fd5232012-06-28 23:53:12 +000010173 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10174 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10175 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10176 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
Nico Weberb8124d12012-07-03 02:03:06 +000010177 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
Nico Weber33fd5232012-06-28 23:53:12 +000010178 }
Chris Lattner30bd3272008-11-18 01:22:49 +000010179
Nico Weberb8124d12012-07-03 02:03:06 +000010180 // Objective-C instance variables
Nico Weber33fd5232012-06-28 23:53:12 +000010181 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10182 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10183 if (OL && OR && OL->getDecl() == OR->getDecl()) {
10184 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10185 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10186 if (RL && RR && RL->getDecl() == RR->getDecl())
Nico Weberb8124d12012-07-03 02:03:06 +000010187 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
Nico Weber33fd5232012-06-28 23:53:12 +000010188 }
10189}
Chris Lattner30bd3272008-11-18 01:22:49 +000010190
10191// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +000010192QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +000010193 SourceLocation Loc,
10194 QualType CompoundType) {
John McCall526ab472011-10-25 17:37:35 +000010195 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10196
Chris Lattner326f7572008-11-18 01:30:42 +000010197 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +000010198 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +000010199 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +000010200
Richard Trieuda4f43a62011-09-07 01:33:52 +000010201 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +000010202 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10203 CompoundType;
Yaxun Liu6aaa01b2016-09-19 14:54:41 +000010204 // OpenCL v1.2 s6.1.1.1 p2:
10205 // The half data type can only be used to declare a pointer to a buffer that
10206 // contains half values
Yaxun Liu5b746652016-12-18 05:18:55 +000010207 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
Yaxun Liu6aaa01b2016-09-19 14:54:41 +000010208 LHSType->isHalfType()) {
10209 Diag(Loc, diag::err_opencl_half_load_store) << 1
10210 << LHSType.getUnqualifiedType();
10211 return QualType();
10212 }
10213
Chris Lattner9bad62c2008-01-04 18:04:52 +000010214 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +000010215 if (CompoundType.isNull()) {
Nico Weber33fd5232012-06-28 23:53:12 +000010216 Expr *RHSCheck = RHS.get();
10217
Nico Weberb8124d12012-07-03 02:03:06 +000010218 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
Nico Weber33fd5232012-06-28 23:53:12 +000010219
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +000010220 QualType LHSTy(LHSType);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +000010221 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +000010222 if (RHS.isInvalid())
10223 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +000010224 // Special case of NSObject attributes on c-style pointer types.
10225 if (ConvTy == IncompatiblePointer &&
10226 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +000010227 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +000010228 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +000010229 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +000010230 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +000010231
John McCall7decc9e2010-11-18 06:31:45 +000010232 if (ConvTy == Compatible &&
Fariborz Jahaniane2a77762012-01-24 19:40:13 +000010233 LHSType->isObjCObjectType())
Fariborz Jahanian3c4225a2012-01-24 18:05:45 +000010234 Diag(Loc, diag::err_objc_object_assignment)
10235 << LHSType;
John McCall7decc9e2010-11-18 06:31:45 +000010236
Chris Lattnerea714382008-08-21 18:04:13 +000010237 // If the RHS is a unary plus or minus, check to see if they = and + are
10238 // right next to each other. If so, the user may have typo'd "x =+ 4"
10239 // instead of "x += 4".
Chris Lattnerea714382008-08-21 18:04:13 +000010240 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10241 RHSCheck = ICE->getSubExpr();
10242 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +000010243 if ((UO->getOpcode() == UO_Plus ||
10244 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +000010245 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +000010246 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +000010247 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner36c39c92009-03-08 06:51:10 +000010248 // And there is a space or other character before the subexpr of the
10249 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +000010250 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattnered9f14c2009-03-09 07:11:10 +000010251 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +000010252 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +000010253 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +000010254 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +000010255 }
Chris Lattnerea714382008-08-21 18:04:13 +000010256 }
John McCall31168b02011-06-15 23:02:42 +000010257
10258 if (ConvTy == Compatible) {
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010259 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10260 // Warn about retain cycles where a block captures the LHS, but
10261 // not if the LHS is a simple variable into which the block is
10262 // being stored...unless that variable can be captured by reference!
10263 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10264 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10265 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10266 checkRetainCycles(LHSExpr, RHS.get());
10267
Jordan Rosed3934582012-09-28 22:21:30 +000010268 // It is safe to assign a weak reference into a strong variable.
10269 // Although this code can still have problems:
10270 // id x = self.weakProp;
10271 // id y = self.weakProp;
10272 // we do not warn to warn spuriously when 'x' and 'y' are on separate
10273 // paths through the function. This should be revisited if
10274 // -Wrepeated-use-of-weak is made flow-sensitive.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010275 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10276 RHS.get()->getLocStart()))
Jordan Rosed3934582012-09-28 22:21:30 +000010277 getCurFunction()->markSafeWeakUse(RHS.get());
10278
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010279 } else if (getLangOpts().ObjCAutoRefCount) {
Richard Trieuda4f43a62011-09-07 01:33:52 +000010280 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010281 }
John McCall31168b02011-06-15 23:02:42 +000010282 }
Chris Lattnerea714382008-08-21 18:04:13 +000010283 } else {
10284 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +000010285 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +000010286 }
Chris Lattner9bad62c2008-01-04 18:04:52 +000010287
Chris Lattner326f7572008-11-18 01:30:42 +000010288 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +000010289 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +000010290 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +000010291
Richard Trieuda4f43a62011-09-07 01:33:52 +000010292 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010293
Steve Naroff98cf3e92007-06-06 18:38:38 +000010294 // C99 6.5.16p3: The type of an assignment expression is the type of the
10295 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +000010296 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +000010297 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10298 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +000010299 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +000010300 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010301 return (getLangOpts().CPlusPlus
John McCall01cbf2d2010-10-12 02:19:57 +000010302 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +000010303}
10304
Richard Trieufaca2d82016-02-18 23:58:40 +000010305// Only ignore explicit casts to void.
10306static bool IgnoreCommaOperand(const Expr *E) {
10307 E = E->IgnoreParens();
10308
10309 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10310 if (CE->getCastKind() == CK_ToVoid) {
10311 return true;
10312 }
10313 }
10314
10315 return false;
10316}
10317
10318// Look for instances where it is likely the comma operator is confused with
10319// another operator. There is a whitelist of acceptable expressions for the
10320// left hand side of the comma operator, otherwise emit a warning.
10321void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10322 // No warnings in macros
10323 if (Loc.isMacroID())
10324 return;
10325
10326 // Don't warn in template instantiations.
10327 if (!ActiveTemplateInstantiations.empty())
10328 return;
10329
10330 // Scope isn't fine-grained enough to whitelist the specific cases, so
10331 // instead, skip more than needed, then call back into here with the
10332 // CommaVisitor in SemaStmt.cpp.
10333 // The whitelisted locations are the initialization and increment portions
10334 // of a for loop. The additional checks are on the condition of
10335 // if statements, do/while loops, and for loops.
Richard Trieu54f82bf2016-02-19 00:15:50 +000010336 const unsigned ForIncrementFlags =
Richard Trieufaca2d82016-02-18 23:58:40 +000010337 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10338 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10339 const unsigned ScopeFlags = getCurScope()->getFlags();
10340 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10341 (ScopeFlags & ForInitFlags) == ForInitFlags)
10342 return;
10343
10344 // If there are multiple comma operators used together, get the RHS of the
10345 // of the comma operator as the LHS.
10346 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10347 if (BO->getOpcode() != BO_Comma)
10348 break;
10349 LHS = BO->getRHS();
10350 }
10351
10352 // Only allow some expressions on LHS to not warn.
10353 if (IgnoreCommaOperand(LHS))
10354 return;
10355
10356 Diag(Loc, diag::warn_comma_operator);
10357 Diag(LHS->getLocStart(), diag::note_cast_to_void)
10358 << LHS->getSourceRange()
10359 << FixItHint::CreateInsertion(LHS->getLocStart(),
10360 LangOpts.CPlusPlus ? "static_cast<void>("
10361 : "(void)(")
10362 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10363 ")");
10364}
10365
Chris Lattner326f7572008-11-18 01:30:42 +000010366// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +000010367static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +000010368 SourceLocation Loc) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010369 LHS = S.CheckPlaceholderExpr(LHS.get());
10370 RHS = S.CheckPlaceholderExpr(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +000010371 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +000010372 return QualType();
10373
John McCall73d36182010-10-12 07:14:40 +000010374 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10375 // operands, but not unary promotions.
10376 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +000010377
John McCall34376a62010-12-04 03:47:34 +000010378 // So we treat the LHS as a ignored value, and in C++ we allow the
10379 // containing site to determine what should be done with the RHS.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010380 LHS = S.IgnoredValueConversions(LHS.get());
John Wiegley01296292011-04-08 18:41:53 +000010381 if (LHS.isInvalid())
10382 return QualType();
John McCall34376a62010-12-04 03:47:34 +000010383
Eli Friedmanc11535c2012-05-24 00:47:05 +000010384 S.DiagnoseUnusedExprResult(LHS.get());
10385
David Blaikiebbafb8a2012-03-11 07:00:24 +000010386 if (!S.getLangOpts().CPlusPlus) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010387 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +000010388 if (RHS.isInvalid())
10389 return QualType();
10390 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +000010391 S.RequireCompleteType(Loc, RHS.get()->getType(),
10392 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +000010393 }
Eli Friedmanba961a92009-03-23 00:24:07 +000010394
Richard Trieufaca2d82016-02-18 23:58:40 +000010395 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10396 S.DiagnoseCommaOperator(LHS.get(), Loc);
10397
John Wiegley01296292011-04-08 18:41:53 +000010398 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +000010399}
10400
Steve Naroff7a5af782007-07-13 16:58:59 +000010401/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10402/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +000010403static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10404 ExprValueKind &VK,
David Majnemer74242432014-07-31 04:52:13 +000010405 ExprObjectKind &OK,
John McCall4bc41ae2010-11-18 19:01:18 +000010406 SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +000010407 bool IsInc, bool IsPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000010408 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +000010409 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000010410
Chris Lattner6b0cf142008-11-21 07:05:48 +000010411 QualType ResType = Op->getType();
David Chisnallfa35df62012-01-16 17:27:18 +000010412 // Atomic types can be used for increment / decrement where the non-atomic
10413 // versions can, so ignore the _Atomic() specifier for the purpose of
10414 // checking.
10415 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10416 ResType = ResAtomicType->getValueType();
10417
Chris Lattner6b0cf142008-11-21 07:05:48 +000010418 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +000010419
David Blaikiebbafb8a2012-03-11 07:00:24 +000010420 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +000010421 // Decrement of bool is not allowed.
Richard Trieuba63ce62011-09-09 01:45:06 +000010422 if (!IsInc) {
John McCall4bc41ae2010-11-18 19:01:18 +000010423 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +000010424 return QualType();
10425 }
10426 // Increment of bool sets it to true, but is deprecated.
Richard Smith4a0cd892015-11-26 02:16:37 +000010427 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10428 : diag::warn_increment_bool)
10429 << Op->getSourceRange();
Richard Trieu493df1a2013-08-08 01:50:23 +000010430 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10431 // Error on enum increments and decrements in C++ mode
10432 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10433 return QualType();
Sebastian Redle10c2c32008-12-20 09:35:34 +000010434 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +000010435 // OK!
John McCallf2538342012-07-31 05:14:30 +000010436 } else if (ResType->isPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +000010437 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +000010438 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +000010439 return QualType();
John McCallf2538342012-07-31 05:14:30 +000010440 } else if (ResType->isObjCObjectPointerType()) {
10441 // On modern runtimes, ObjC pointer arithmetic is forbidden.
10442 // Otherwise, we just need a complete type.
10443 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10444 checkArithmeticOnObjCPointer(S, OpLoc, Op))
10445 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +000010446 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +000010447 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +000010448 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +000010449 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +000010450 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +000010451 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +000010452 if (PR.isInvalid()) return QualType();
David Majnemer74242432014-07-31 04:52:13 +000010453 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +000010454 IsInc, IsPrefix);
David Blaikiebbafb8a2012-03-11 07:00:24 +000010455 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev85129b82011-02-07 02:17:30 +000010456 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Ulrich Weigand3c5038a2015-07-30 14:08:36 +000010457 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10458 (ResType->getAs<VectorType>()->getVectorKind() !=
10459 VectorType::AltiVecBool)) {
10460 // The z vector extensions allow ++ and -- for non-bool vectors.
David Tweed16574d82013-09-06 09:58:08 +000010461 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10462 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10463 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
Chris Lattner6b0cf142008-11-21 07:05:48 +000010464 } else {
John McCall4bc41ae2010-11-18 19:01:18 +000010465 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuba63ce62011-09-09 01:45:06 +000010466 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +000010467 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +000010468 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000010469 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +000010470 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +000010471 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +000010472 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +000010473 // In C++, a prefix increment is the same type as the operand. Otherwise
10474 // (in C or with postfix), the increment is the unqualified type of the
10475 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010476 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +000010477 VK = VK_LValue;
David Majnemer74242432014-07-31 04:52:13 +000010478 OK = Op->getObjectKind();
John McCall4bc41ae2010-11-18 19:01:18 +000010479 return ResType;
10480 } else {
10481 VK = VK_RValue;
10482 return ResType.getUnqualifiedType();
10483 }
Steve Naroff26c8ea52007-03-21 21:08:52 +000010484}
Fariborz Jahanian805b74e2010-09-14 23:02:38 +000010485
10486
Anders Carlsson806700f2008-02-01 07:15:58 +000010487/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +000010488/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +000010489/// where the declaration is needed for type checking. We only need to
10490/// handle cases when the expression references a function designator
10491/// or is an lvalue. Here are some examples:
10492/// - &(x) => x
10493/// - &*****f => f for f a function designator.
10494/// - &s.xx => s
10495/// - &s.zz[1].yy -> s, if zz is an array
10496/// - *(x + 1) -> x, if x is an array
10497/// - &"123"[2] -> 0
10498/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +000010499static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +000010500 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +000010501 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +000010502 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +000010503 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +000010504 // If this is an arrow operator, the address is an offset from
10505 // the base's value, so the object the base refers to is
10506 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +000010507 if (cast<MemberExpr>(E)->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +000010508 return nullptr;
Eli Friedman3a1e6922009-04-20 08:23:18 +000010509 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +000010510 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +000010511 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +000010512 // FIXME: This code shouldn't be necessary! We should catch the implicit
10513 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +000010514 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10515 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10516 if (ICE->getSubExpr()->getType()->isArrayType())
10517 return getPrimaryDecl(ICE->getSubExpr());
10518 }
Craig Topperc3ec1492014-05-26 06:22:03 +000010519 return nullptr;
Anders Carlsson806700f2008-02-01 07:15:58 +000010520 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +000010521 case Stmt::UnaryOperatorClass: {
10522 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +000010523
Daniel Dunbarb692ef42008-08-04 20:02:37 +000010524 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010525 case UO_Real:
10526 case UO_Imag:
10527 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +000010528 return getPrimaryDecl(UO->getSubExpr());
10529 default:
Craig Topperc3ec1492014-05-26 06:22:03 +000010530 return nullptr;
Daniel Dunbarb692ef42008-08-04 20:02:37 +000010531 }
10532 }
Steve Naroff47500512007-04-19 23:00:49 +000010533 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +000010534 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +000010535 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +000010536 // If the result of an implicit cast is an l-value, we care about
10537 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +000010538 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +000010539 default:
Craig Topperc3ec1492014-05-26 06:22:03 +000010540 return nullptr;
Steve Naroff47500512007-04-19 23:00:49 +000010541 }
10542}
10543
Richard Trieu5f376f62011-09-07 21:46:33 +000010544namespace {
10545 enum {
10546 AO_Bit_Field = 0,
10547 AO_Vector_Element = 1,
10548 AO_Property_Expansion = 2,
10549 AO_Register_Variable = 3,
10550 AO_No_Error = 4
10551 };
10552}
Richard Trieu3fd7bb82011-09-02 00:47:55 +000010553/// \brief Diagnose invalid operand for address of operations.
10554///
10555/// \param Type The type of operand which cannot have its address taken.
Richard Trieu3fd7bb82011-09-02 00:47:55 +000010556static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10557 Expr *E, unsigned Type) {
10558 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10559}
10560
Steve Naroff47500512007-04-19 23:00:49 +000010561/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +000010562/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +000010563/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +000010564/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +000010565/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +000010566/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +000010567/// we allow the '&' but retain the overloaded-function type.
Richard Smithaf9de912013-07-11 02:26:56 +000010568QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
John McCall526ab472011-10-25 17:37:35 +000010569 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10570 if (PTy->getKind() == BuiltinType::Overload) {
David Majnemer0f328442013-07-05 06:23:33 +000010571 Expr *E = OrigOp.get()->IgnoreParens();
10572 if (!isa<OverloadExpr>(E)) {
10573 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
Richard Smithaf9de912013-07-11 02:26:56 +000010574 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
John McCall526ab472011-10-25 17:37:35 +000010575 << OrigOp.get()->getSourceRange();
10576 return QualType();
10577 }
David Majnemer66ad5742013-06-11 03:56:29 +000010578
David Majnemer0f328442013-07-05 06:23:33 +000010579 OverloadExpr *Ovl = cast<OverloadExpr>(E);
David Majnemer66ad5742013-06-11 03:56:29 +000010580 if (isa<UnresolvedMemberExpr>(Ovl))
Richard Smithaf9de912013-07-11 02:26:56 +000010581 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10582 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
David Majnemer66ad5742013-06-11 03:56:29 +000010583 << OrigOp.get()->getSourceRange();
10584 return QualType();
10585 }
10586
Richard Smithaf9de912013-07-11 02:26:56 +000010587 return Context.OverloadTy;
John McCall526ab472011-10-25 17:37:35 +000010588 }
10589
10590 if (PTy->getKind() == BuiltinType::UnknownAny)
Richard Smithaf9de912013-07-11 02:26:56 +000010591 return Context.UnknownAnyTy;
John McCall526ab472011-10-25 17:37:35 +000010592
10593 if (PTy->getKind() == BuiltinType::BoundMember) {
Richard Smithaf9de912013-07-11 02:26:56 +000010594 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +000010595 << OrigOp.get()->getSourceRange();
Douglas Gregor668d3622011-10-09 19:10:41 +000010596 return QualType();
10597 }
John McCall526ab472011-10-25 17:37:35 +000010598
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010599 OrigOp = CheckPlaceholderExpr(OrigOp.get());
John McCall526ab472011-10-25 17:37:35 +000010600 if (OrigOp.isInvalid()) return QualType();
John McCall0009fcc2011-04-26 20:42:42 +000010601 }
John McCall8d08b9b2010-08-27 09:08:28 +000010602
John McCall526ab472011-10-25 17:37:35 +000010603 if (OrigOp.get()->isTypeDependent())
Richard Smithaf9de912013-07-11 02:26:56 +000010604 return Context.DependentTy;
John McCall526ab472011-10-25 17:37:35 +000010605
10606 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +000010607
John McCall8d08b9b2010-08-27 09:08:28 +000010608 // Make sure to ignore parentheses in subsequent checks
John McCall526ab472011-10-25 17:37:35 +000010609 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +000010610
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +000010611 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10612 if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10613 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10614 return QualType();
10615 }
10616
Richard Smithaf9de912013-07-11 02:26:56 +000010617 if (getLangOpts().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +000010618 // Implement C99-only parts of addressof rules.
10619 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +000010620 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +000010621 // Per C99 6.5.3.2, the address of a deref always returns a valid result
10622 // (assuming the deref expression is valid).
10623 return uOp->getSubExpr()->getType();
10624 }
10625 // Technically, there should be a check for array subscript
10626 // expressions here, but the result of one is always an lvalue anyway.
10627 }
John McCallf3a88602011-02-03 08:15:49 +000010628 ValueDecl *dcl = getPrimaryDecl(op);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010629
10630 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10631 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10632 op->getLocStart()))
10633 return QualType();
10634
Richard Smithaf9de912013-07-11 02:26:56 +000010635 Expr::LValueClassification lval = op->ClassifyLValue(Context);
Richard Trieu5f376f62011-09-07 21:46:33 +000010636 unsigned AddressOfError = AO_No_Error;
Nuno Lopes17f345f2008-12-16 22:59:47 +000010637
Richard Smithc084bd282013-02-02 02:14:45 +000010638 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
Richard Smithaf9de912013-07-11 02:26:56 +000010639 bool sfinae = (bool)isSFINAEContext();
10640 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10641 : diag::ext_typecheck_addrof_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +000010642 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +000010643 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +000010644 return QualType();
Richard Smith9f8400e2013-05-01 19:00:39 +000010645 // Materialize the temporary as an lvalue so that we can take its address.
Tim Shen4a05bb82016-06-21 20:29:17 +000010646 OrigOp = op =
10647 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
John McCall8d08b9b2010-08-27 09:08:28 +000010648 } else if (isa<ObjCSelectorExpr>(op)) {
Richard Smithaf9de912013-07-11 02:26:56 +000010649 return Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +000010650 } else if (lval == Expr::LV_MemberFunction) {
10651 // If it's an instance method, make a member pointer.
10652 // The expression must have exactly the form &A::foo.
10653
10654 // If the underlying expression isn't a decl ref, give up.
10655 if (!isa<DeclRefExpr>(op)) {
Richard Smithaf9de912013-07-11 02:26:56 +000010656 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +000010657 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +000010658 return QualType();
10659 }
10660 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10661 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10662
10663 // The id-expression was parenthesized.
John McCall526ab472011-10-25 17:37:35 +000010664 if (OrigOp.get() != DRE) {
Richard Smithaf9de912013-07-11 02:26:56 +000010665 Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +000010666 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +000010667
10668 // The method was named without a qualifier.
10669 } else if (!DRE->getQualifier()) {
David Blaikiec2ff8e12012-10-11 22:55:07 +000010670 if (MD->getParent()->getName().empty())
Richard Smithaf9de912013-07-11 02:26:56 +000010671 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
David Blaikiec2ff8e12012-10-11 22:55:07 +000010672 << op->getSourceRange();
10673 else {
10674 SmallString<32> Str;
10675 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
Richard Smithaf9de912013-07-11 02:26:56 +000010676 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
David Blaikiec2ff8e12012-10-11 22:55:07 +000010677 << op->getSourceRange()
10678 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10679 }
John McCall8d08b9b2010-08-27 09:08:28 +000010680 }
10681
Benjamin Kramer915d1692013-10-10 09:44:41 +000010682 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10683 if (isa<CXXDestructorDecl>(MD))
10684 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10685
David Majnemer1cdd96d2014-01-17 09:01:00 +000010686 QualType MPTy = Context.getMemberPointerType(
10687 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
Richard Smithdb0ac552015-12-18 22:40:25 +000010688 // Under the MS ABI, lock down the inheritance model now.
David Majnemer1cdd96d2014-01-17 09:01:00 +000010689 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
Richard Smithdb0ac552015-12-18 22:40:25 +000010690 (void)isCompleteType(OpLoc, MPTy);
David Majnemer1cdd96d2014-01-17 09:01:00 +000010691 return MPTy;
John McCall8d08b9b2010-08-27 09:08:28 +000010692 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +000010693 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +000010694 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +000010695 if (!op->getType()->isFunctionType()) {
John McCall526ab472011-10-25 17:37:35 +000010696 // Use a special diagnostic for loads from property references.
John McCallfe96e0b2011-11-06 09:01:30 +000010697 if (isa<PseudoObjectExpr>(op)) {
John McCall526ab472011-10-25 17:37:35 +000010698 AddressOfError = AO_Property_Expansion;
10699 } else {
Richard Smithaf9de912013-07-11 02:26:56 +000010700 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Richard Smithc084bd282013-02-02 02:14:45 +000010701 << op->getType() << op->getSourceRange();
John McCall526ab472011-10-25 17:37:35 +000010702 return QualType();
10703 }
Steve Naroff35d85152007-05-07 00:24:15 +000010704 }
John McCall086a4642010-11-24 05:12:34 +000010705 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +000010706 // The operand cannot be a bit-field
Richard Trieu5f376f62011-09-07 21:46:33 +000010707 AddressOfError = AO_Bit_Field;
John McCall086a4642010-11-24 05:12:34 +000010708 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +000010709 // The operand cannot be an element of a vector
Richard Trieu5f376f62011-09-07 21:46:33 +000010710 AddressOfError = AO_Vector_Element;
Steve Naroffb96e4ab62008-02-29 23:30:25 +000010711 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +000010712 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +000010713 // with the register storage-class specifier.
10714 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +000010715 // in C++ it is not error to take address of a register
10716 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +000010717 if (vd->getStorageClass() == SC_Register &&
Richard Smithaf9de912013-07-11 02:26:56 +000010718 !getLangOpts().CPlusPlus) {
Richard Trieu5f376f62011-09-07 21:46:33 +000010719 AddressOfError = AO_Register_Variable;
Steve Naroff35d85152007-05-07 00:24:15 +000010720 }
Reid Kleckner85c7e0a2015-02-24 20:29:40 +000010721 } else if (isa<MSPropertyDecl>(dcl)) {
10722 AddressOfError = AO_Property_Expansion;
John McCalld14a8642009-11-21 08:51:07 +000010723 } else if (isa<FunctionTemplateDecl>(dcl)) {
Richard Smithaf9de912013-07-11 02:26:56 +000010724 return Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +000010725 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +000010726 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +000010727 // Could be a pointer to member, though, if there is an explicit
10728 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +000010729 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +000010730 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +000010731 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +000010732 if (dcl->getType()->isReferenceType()) {
Richard Smithaf9de912013-07-11 02:26:56 +000010733 Diag(OpLoc,
10734 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +000010735 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +000010736 return QualType();
10737 }
Mike Stump11289f42009-09-09 15:08:12 +000010738
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +000010739 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10740 Ctx = Ctx->getParent();
David Majnemer1cdd96d2014-01-17 09:01:00 +000010741
10742 QualType MPTy = Context.getMemberPointerType(
10743 op->getType(),
10744 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Richard Smithdb0ac552015-12-18 22:40:25 +000010745 // Under the MS ABI, lock down the inheritance model now.
David Majnemer1cdd96d2014-01-17 09:01:00 +000010746 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
Richard Smithdb0ac552015-12-18 22:40:25 +000010747 (void)isCompleteType(OpLoc, MPTy);
David Majnemer1cdd96d2014-01-17 09:01:00 +000010748 return MPTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +000010749 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +000010750 }
Richard Smith7873de02016-08-11 22:25:46 +000010751 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
10752 !isa<BindingDecl>(dcl))
David Blaikie83d382b2011-09-23 05:06:16 +000010753 llvm_unreachable("Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +000010754 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +000010755
Richard Trieu5f376f62011-09-07 21:46:33 +000010756 if (AddressOfError != AO_No_Error) {
Richard Smithaf9de912013-07-11 02:26:56 +000010757 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
Richard Trieu5f376f62011-09-07 21:46:33 +000010758 return QualType();
10759 }
10760
Eli Friedmance7f9002009-05-16 23:27:50 +000010761 if (lval == Expr::LV_IncompleteVoidType) {
10762 // Taking the address of a void variable is technically illegal, but we
10763 // allow it in cases which are otherwise valid.
10764 // Example: "extern void x; void* y = &x;".
Richard Smithaf9de912013-07-11 02:26:56 +000010765 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +000010766 }
10767
Steve Naroff47500512007-04-19 23:00:49 +000010768 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +000010769 if (op->getType()->isObjCObjectType())
Richard Smithaf9de912013-07-11 02:26:56 +000010770 return Context.getObjCObjectPointerType(op->getType());
Xiuli Pan89307aa2016-02-24 04:29:36 +000010771
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010772 CheckAddressOfPackedMember(op);
10773
Richard Smithaf9de912013-07-11 02:26:56 +000010774 return Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +000010775}
10776
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010777static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10778 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10779 if (!DRE)
10780 return;
10781 const Decl *D = DRE->getDecl();
10782 if (!D)
10783 return;
10784 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10785 if (!Param)
10786 return;
10787 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
Aaron Ballman2521f362014-12-11 19:35:42 +000010788 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010789 return;
10790 if (FunctionScopeInfo *FD = S.getCurFunction())
10791 if (!FD->ModifiedNonNullParams.count(Param))
10792 FD->ModifiedNonNullParams.insert(Param);
10793}
10794
Chris Lattner9156f1b2010-07-05 19:17:26 +000010795/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +000010796static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10797 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000010798 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +000010799 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000010800
John Wiegley01296292011-04-08 18:41:53 +000010801 ExprResult ConvResult = S.UsualUnaryConversions(Op);
10802 if (ConvResult.isInvalid())
10803 return QualType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010804 Op = ConvResult.get();
Chris Lattner9156f1b2010-07-05 19:17:26 +000010805 QualType OpTy = Op->getType();
10806 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +000010807
10808 if (isa<CXXReinterpretCastExpr>(Op)) {
10809 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10810 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10811 Op->getSourceRange());
10812 }
10813
Chris Lattner9156f1b2010-07-05 19:17:26 +000010814 if (const PointerType *PT = OpTy->getAs<PointerType>())
Xiuli Pan89307aa2016-02-24 04:29:36 +000010815 {
Chris Lattner9156f1b2010-07-05 19:17:26 +000010816 Result = PT->getPointeeType();
Xiuli Pan89307aa2016-02-24 04:29:36 +000010817 }
Chris Lattner9156f1b2010-07-05 19:17:26 +000010818 else if (const ObjCObjectPointerType *OPT =
10819 OpTy->getAs<ObjCObjectPointerType>())
10820 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +000010821 else {
John McCall3aef3d82011-04-10 19:13:55 +000010822 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +000010823 if (PR.isInvalid()) return QualType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010824 if (PR.get() != Op)
10825 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +000010826 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000010827
Chris Lattner9156f1b2010-07-05 19:17:26 +000010828 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +000010829 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +000010830 << OpTy << Op->getSourceRange();
10831 return QualType();
10832 }
John McCall4bc41ae2010-11-18 19:01:18 +000010833
Richard Smith80877c22014-05-07 21:53:27 +000010834 // Note that per both C89 and C99, indirection is always legal, even if Result
10835 // is an incomplete type or void. It would be possible to warn about
10836 // dereferencing a void pointer, but it's completely well-defined, and such a
10837 // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10838 // for pointers to 'void' but is fine for any other pointer type:
10839 //
10840 // C++ [expr.unary.op]p1:
10841 // [...] the expression to which [the unary * operator] is applied shall
10842 // be a pointer to an object type, or a pointer to a function type
10843 if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10844 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10845 << OpTy << Op->getSourceRange();
10846
John McCall4bc41ae2010-11-18 19:01:18 +000010847 // Dereferences are usually l-values...
10848 VK = VK_LValue;
10849
10850 // ...except that certain expressions are never l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010851 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +000010852 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +000010853
10854 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +000010855}
Steve Naroff218bc2b2007-05-04 21:54:46 +000010856
Richard Smith0f0af192014-11-08 05:07:16 +000010857BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +000010858 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +000010859 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +000010860 default: llvm_unreachable("Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +000010861 case tok::periodstar: Opc = BO_PtrMemD; break;
10862 case tok::arrowstar: Opc = BO_PtrMemI; break;
10863 case tok::star: Opc = BO_Mul; break;
10864 case tok::slash: Opc = BO_Div; break;
10865 case tok::percent: Opc = BO_Rem; break;
10866 case tok::plus: Opc = BO_Add; break;
10867 case tok::minus: Opc = BO_Sub; break;
10868 case tok::lessless: Opc = BO_Shl; break;
10869 case tok::greatergreater: Opc = BO_Shr; break;
10870 case tok::lessequal: Opc = BO_LE; break;
10871 case tok::less: Opc = BO_LT; break;
10872 case tok::greaterequal: Opc = BO_GE; break;
10873 case tok::greater: Opc = BO_GT; break;
10874 case tok::exclaimequal: Opc = BO_NE; break;
10875 case tok::equalequal: Opc = BO_EQ; break;
10876 case tok::amp: Opc = BO_And; break;
10877 case tok::caret: Opc = BO_Xor; break;
10878 case tok::pipe: Opc = BO_Or; break;
10879 case tok::ampamp: Opc = BO_LAnd; break;
10880 case tok::pipepipe: Opc = BO_LOr; break;
10881 case tok::equal: Opc = BO_Assign; break;
10882 case tok::starequal: Opc = BO_MulAssign; break;
10883 case tok::slashequal: Opc = BO_DivAssign; break;
10884 case tok::percentequal: Opc = BO_RemAssign; break;
10885 case tok::plusequal: Opc = BO_AddAssign; break;
10886 case tok::minusequal: Opc = BO_SubAssign; break;
10887 case tok::lesslessequal: Opc = BO_ShlAssign; break;
10888 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
10889 case tok::ampequal: Opc = BO_AndAssign; break;
10890 case tok::caretequal: Opc = BO_XorAssign; break;
10891 case tok::pipeequal: Opc = BO_OrAssign; break;
10892 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +000010893 }
10894 return Opc;
10895}
10896
John McCalle3027922010-08-25 11:45:40 +000010897static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +000010898 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +000010899 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +000010900 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +000010901 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +000010902 case tok::plusplus: Opc = UO_PreInc; break;
10903 case tok::minusminus: Opc = UO_PreDec; break;
10904 case tok::amp: Opc = UO_AddrOf; break;
10905 case tok::star: Opc = UO_Deref; break;
10906 case tok::plus: Opc = UO_Plus; break;
10907 case tok::minus: Opc = UO_Minus; break;
10908 case tok::tilde: Opc = UO_Not; break;
10909 case tok::exclaim: Opc = UO_LNot; break;
10910 case tok::kw___real: Opc = UO_Real; break;
10911 case tok::kw___imag: Opc = UO_Imag; break;
10912 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +000010913 }
10914 return Opc;
10915}
10916
Chandler Carruthe0cee6a2011-01-04 06:52:15 +000010917/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
10918/// This warning is only emitted for builtin assignment operations. It is also
10919/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +000010920static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +000010921 SourceLocation OpLoc) {
10922 if (!S.ActiveTemplateInstantiations.empty())
10923 return;
10924 if (OpLoc.isInvalid() || OpLoc.isMacroID())
10925 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +000010926 LHSExpr = LHSExpr->IgnoreParenImpCasts();
10927 RHSExpr = RHSExpr->IgnoreParenImpCasts();
10928 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10929 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10930 if (!LHSDeclRef || !RHSDeclRef ||
10931 LHSDeclRef->getLocation().isMacroID() ||
10932 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +000010933 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +000010934 const ValueDecl *LHSDecl =
10935 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
10936 const ValueDecl *RHSDecl =
10937 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
10938 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +000010939 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +000010940 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +000010941 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +000010942 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +000010943 if (RefTy->getPointeeType().isVolatileQualified())
10944 return;
10945
10946 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +000010947 << LHSDeclRef->getType()
10948 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +000010949}
10950
Ted Kremenekebeabab2013-04-22 22:46:52 +000010951/// Check if a bitwise-& is performed on an Objective-C pointer. This
10952/// is usually indicative of introspection within the Objective-C pointer.
10953static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
10954 SourceLocation OpLoc) {
10955 if (!S.getLangOpts().ObjC1)
10956 return;
10957
Craig Topperc3ec1492014-05-26 06:22:03 +000010958 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
Ted Kremenekebeabab2013-04-22 22:46:52 +000010959 const Expr *LHS = L.get();
10960 const Expr *RHS = R.get();
10961
10962 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10963 ObjCPointerExpr = LHS;
10964 OtherExpr = RHS;
10965 }
10966 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10967 ObjCPointerExpr = RHS;
10968 OtherExpr = LHS;
10969 }
10970
10971 // This warning is deliberately made very specific to reduce false
10972 // positives with logic that uses '&' for hashing. This logic mainly
10973 // looks for code trying to introspect into tagged pointers, which
10974 // code should generally never do.
10975 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
Ted Kremenek009d61d2013-06-24 21:35:39 +000010976 unsigned Diag = diag::warn_objc_pointer_masking;
10977 // Determine if we are introspecting the result of performSelectorXXX.
10978 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
10979 // Special case messages to -performSelector and friends, which
10980 // can return non-pointer values boxed in a pointer value.
10981 // Some clients may wish to silence warnings in this subcase.
10982 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
10983 Selector S = ME->getSelector();
10984 StringRef SelArg0 = S.getNameForSlot(0);
10985 if (SelArg0.startswith("performSelector"))
10986 Diag = diag::warn_objc_pointer_masking_performSelector;
10987 }
10988
10989 S.Diag(OpLoc, Diag)
Ted Kremenekebeabab2013-04-22 22:46:52 +000010990 << ObjCPointerExpr->getSourceRange();
10991 }
10992}
10993
Kaelyn Takata7a503692015-01-27 22:01:39 +000010994static NamedDecl *getDeclFromExpr(Expr *E) {
10995 if (!E)
10996 return nullptr;
10997 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
10998 return DRE->getDecl();
10999 if (auto *ME = dyn_cast<MemberExpr>(E))
11000 return ME->getMemberDecl();
11001 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11002 return IRE->getDecl();
11003 return nullptr;
11004}
11005
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000011006/// CreateBuiltinBinOp - Creates a new built-in binary operation with
11007/// operator @p Opc at location @c TokLoc. This routine only supports
11008/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +000011009ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +000011010 BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +000011011 Expr *LHSExpr, Expr *RHSExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011012 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl67766732012-02-27 20:34:02 +000011013 // The syntax only allows initializer lists on the RHS of assignment,
11014 // so we don't need to worry about accepting invalid code for
11015 // non-assignment operators.
11016 // C++11 5.17p9:
11017 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11018 // of x = {} is x = T().
11019 InitializationKind Kind =
11020 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
11021 InitializedEntity Entity =
11022 InitializedEntity::InitializeTemporary(LHSExpr->getType());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011023 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011024 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
Sebastian Redl67766732012-02-27 20:34:02 +000011025 if (Init.isInvalid())
11026 return Init;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011027 RHSExpr = Init.get();
Sebastian Redl67766732012-02-27 20:34:02 +000011028 }
11029
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011030 ExprResult LHS = LHSExpr, RHS = RHSExpr;
Eli Friedman8b7b1b12009-03-28 01:22:36 +000011031 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +000011032 // The following two variables are used for compound assignment operators
11033 QualType CompLHSTy; // Type of LHS after promotions for computation
11034 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +000011035 ExprValueKind VK = VK_RValue;
11036 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000011037
Kaelyn Takata15867822014-11-21 18:48:04 +000011038 if (!getLangOpts().CPlusPlus) {
11039 // C cannot handle TypoExpr nodes on either side of a binop because it
11040 // doesn't handle dependent types properly, so make sure any TypoExprs have
11041 // been dealt with before checking the operands.
11042 LHS = CorrectDelayedTyposInExpr(LHSExpr);
Kaelyn Takata7a503692015-01-27 22:01:39 +000011043 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
11044 if (Opc != BO_Assign)
11045 return ExprResult(E);
11046 // Avoid correcting the RHS to the same Expr as the LHS.
11047 Decl *D = getDeclFromExpr(E);
11048 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11049 });
Kaelyn Takata15867822014-11-21 18:48:04 +000011050 if (!LHS.isUsable() || !RHS.isUsable())
11051 return ExprError();
11052 }
11053
Anastasia Stulovade0e4242015-09-30 13:18:52 +000011054 if (getLangOpts().OpenCL) {
Anastasia Stulova4d850032016-07-11 13:46:02 +000011055 QualType LHSTy = LHSExpr->getType();
11056 QualType RHSTy = RHSExpr->getType();
Anastasia Stulovade0e4242015-09-30 13:18:52 +000011057 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11058 // the ATOMIC_VAR_INIT macro.
Anastasia Stulova4d850032016-07-11 13:46:02 +000011059 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
Anastasia Stulovade0e4242015-09-30 13:18:52 +000011060 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11061 if (BO_Assign == Opc)
11062 Diag(OpLoc, diag::err_atomic_init_constant) << SR;
11063 else
11064 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11065 return ExprError();
11066 }
Anastasia Stulova4d850032016-07-11 13:46:02 +000011067
11068 // OpenCL special types - image, sampler, pipe, and blocks are to be used
11069 // only with a builtin functions and therefore should be disallowed here.
11070 if (LHSTy->isImageType() || RHSTy->isImageType() ||
11071 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11072 LHSTy->isPipeType() || RHSTy->isPipeType() ||
11073 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11074 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11075 return ExprError();
11076 }
Anastasia Stulovade0e4242015-09-30 13:18:52 +000011077 }
11078
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000011079 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +000011080 case BO_Assign:
Richard Trieu4a287fb2011-09-07 01:49:20 +000011081 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikiebbafb8a2012-03-11 07:00:24 +000011082 if (getLangOpts().CPlusPlus &&
Richard Trieu4a287fb2011-09-07 01:49:20 +000011083 LHS.get()->getObjectKind() != OK_ObjCProperty) {
11084 VK = LHS.get()->getValueKind();
11085 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +000011086 }
Richard Trieu17ddb822015-01-10 06:04:18 +000011087 if (!ResultTy.isNull()) {
Richard Trieu4a287fb2011-09-07 01:49:20 +000011088 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011089 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
Richard Trieu17ddb822015-01-10 06:04:18 +000011090 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011091 RecordModifiableNonNullParam(*this, LHS.get());
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000011092 break;
John McCalle3027922010-08-25 11:45:40 +000011093 case BO_PtrMemD:
11094 case BO_PtrMemI:
Richard Trieu4a287fb2011-09-07 01:49:20 +000011095 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +000011096 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +000011097 break;
John McCalle3027922010-08-25 11:45:40 +000011098 case BO_Mul:
11099 case BO_Div:
Richard Trieu4a287fb2011-09-07 01:49:20 +000011100 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +000011101 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000011102 break;
John McCalle3027922010-08-25 11:45:40 +000011103 case BO_Rem:
Richard Trieu4a287fb2011-09-07 01:49:20 +000011104 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000011105 break;
John McCalle3027922010-08-25 11:45:40 +000011106 case BO_Add:
Nico Weberccec40d2012-03-02 22:01:22 +000011107 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000011108 break;
John McCalle3027922010-08-25 11:45:40 +000011109 case BO_Sub:
Richard Trieu4a287fb2011-09-07 01:49:20 +000011110 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000011111 break;
John McCalle3027922010-08-25 11:45:40 +000011112 case BO_Shl:
11113 case BO_Shr:
Richard Trieu4a287fb2011-09-07 01:49:20 +000011114 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000011115 break;
John McCalle3027922010-08-25 11:45:40 +000011116 case BO_LE:
11117 case BO_LT:
11118 case BO_GE:
11119 case BO_GT:
Richard Trieu4a287fb2011-09-07 01:49:20 +000011120 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000011121 break;
John McCalle3027922010-08-25 11:45:40 +000011122 case BO_EQ:
11123 case BO_NE:
Richard Trieu4a287fb2011-09-07 01:49:20 +000011124 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000011125 break;
John McCalle3027922010-08-25 11:45:40 +000011126 case BO_And:
Ted Kremenekebeabab2013-04-22 22:46:52 +000011127 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
John McCalle3027922010-08-25 11:45:40 +000011128 case BO_Xor:
11129 case BO_Or:
Nico Weber44f6f2e2016-10-27 16:32:06 +000011130 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000011131 break;
John McCalle3027922010-08-25 11:45:40 +000011132 case BO_LAnd:
11133 case BO_LOr:
Richard Trieu4a287fb2011-09-07 01:49:20 +000011134 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000011135 break;
John McCalle3027922010-08-25 11:45:40 +000011136 case BO_MulAssign:
11137 case BO_DivAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +000011138 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +000011139 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +000011140 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +000011141 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11142 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000011143 break;
John McCalle3027922010-08-25 11:45:40 +000011144 case BO_RemAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +000011145 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +000011146 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +000011147 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11148 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000011149 break;
John McCalle3027922010-08-25 11:45:40 +000011150 case BO_AddAssign:
Nico Weberccec40d2012-03-02 22:01:22 +000011151 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu4a287fb2011-09-07 01:49:20 +000011152 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11153 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000011154 break;
John McCalle3027922010-08-25 11:45:40 +000011155 case BO_SubAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +000011156 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11157 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11158 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000011159 break;
John McCalle3027922010-08-25 11:45:40 +000011160 case BO_ShlAssign:
11161 case BO_ShrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +000011162 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +000011163 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +000011164 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11165 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000011166 break;
John McCalle3027922010-08-25 11:45:40 +000011167 case BO_AndAssign:
Nikola Smiljanic292b5ce2014-05-30 00:15:04 +000011168 case BO_OrAssign: // fallthrough
Craig Topperbd44cd92015-12-08 04:33:04 +000011169 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
John McCalle3027922010-08-25 11:45:40 +000011170 case BO_XorAssign:
Nico Weber44f6f2e2016-10-27 16:32:06 +000011171 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
Eli Friedman8b7b1b12009-03-28 01:22:36 +000011172 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +000011173 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11174 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000011175 break;
John McCalle3027922010-08-25 11:45:40 +000011176 case BO_Comma:
Richard Trieu4a287fb2011-09-07 01:49:20 +000011177 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikiebbafb8a2012-03-11 07:00:24 +000011178 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu4a287fb2011-09-07 01:49:20 +000011179 VK = RHS.get()->getValueKind();
11180 OK = RHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +000011181 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000011182 break;
11183 }
Richard Trieu4a287fb2011-09-07 01:49:20 +000011184 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +000011185 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011186
11187 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu4a287fb2011-09-07 01:49:20 +000011188 CheckArrayAccess(LHS.get());
11189 CheckArrayAccess(RHS.get());
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011190
Fariborz Jahanian06bb7f72013-03-28 19:50:55 +000011191 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11192 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11193 &Context.Idents.get("object_setClass"),
11194 SourceLocation(), LookupOrdinaryName);
11195 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
Craig Topper07fa1762015-11-15 02:31:46 +000011196 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
Fariborz Jahanian06bb7f72013-03-28 19:50:55 +000011197 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11198 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11199 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11200 FixItHint::CreateInsertion(RHSLocEnd, ")");
11201 }
11202 else
11203 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11204 }
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +000011205 else if (const ObjCIvarRefExpr *OIRE =
11206 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +000011207 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
Fariborz Jahanian3b602ce2013-03-28 23:39:11 +000011208
Eli Friedman8b7b1b12009-03-28 01:22:36 +000011209 if (CompResultTy.isNull())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011210 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11211 OK, OpLoc, FPFeatures.fp_contract);
David Blaikiebbafb8a2012-03-11 07:00:24 +000011212 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieucfc491d2011-08-02 04:35:43 +000011213 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +000011214 VK = VK_LValue;
Richard Trieu4a287fb2011-09-07 01:49:20 +000011215 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +000011216 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011217 return new (Context) CompoundAssignOperator(
11218 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11219 OpLoc, FPFeatures.fp_contract);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000011220}
11221
Sebastian Redl44615072009-10-27 12:10:02 +000011222/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11223/// operators are mixed in a way that suggests that the programmer forgot that
11224/// comparison operators have higher precedence. The most typical example of
11225/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +000011226static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +000011227 SourceLocation OpLoc, Expr *LHSExpr,
11228 Expr *RHSExpr) {
Eli Friedman37feb2d2012-11-15 00:29:07 +000011229 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11230 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +000011231
Craig Topperf942fde2015-12-12 06:30:48 +000011232 // Check that one of the sides is a comparison operator and the other isn't.
Eli Friedman37feb2d2012-11-15 00:29:07 +000011233 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11234 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
Craig Topperf942fde2015-12-12 06:30:48 +000011235 if (isLeftComp == isRightComp)
Sebastian Redl43028242009-10-26 15:24:15 +000011236 return;
11237
11238 // Bitwise operations are sometimes used as eager logical ops.
11239 // Don't diagnose this.
Eli Friedman37feb2d2012-11-15 00:29:07 +000011240 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11241 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
Craig Topperf942fde2015-12-12 06:30:48 +000011242 if (isLeftBitwise || isRightBitwise)
Sebastian Redl43028242009-10-26 15:24:15 +000011243 return;
11244
Richard Trieu4a287fb2011-09-07 01:49:20 +000011245 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11246 OpLoc)
11247 : SourceRange(OpLoc, RHSExpr->getLocEnd());
Eli Friedman37feb2d2012-11-15 00:29:07 +000011248 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
Richard Trieu73088052011-08-10 22:41:34 +000011249 SourceRange ParensRange = isLeftComp ?
Eli Friedman37feb2d2012-11-15 00:29:07 +000011250 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
Richard Trieu7ec1a312014-08-23 00:30:57 +000011251 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
Richard Trieu73088052011-08-10 22:41:34 +000011252
11253 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
Eli Friedman37feb2d2012-11-15 00:29:07 +000011254 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
Richard Trieu73088052011-08-10 22:41:34 +000011255 SuggestParentheses(Self, OpLoc,
David Blaikiedac86fd2012-10-08 01:19:49 +000011256 Self.PDiag(diag::note_precedence_silence) << OpStr,
Nico Webercdfb1ae2012-06-03 07:07:00 +000011257 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu73088052011-08-10 22:41:34 +000011258 SuggestParentheses(Self, OpLoc,
Eli Friedman37feb2d2012-11-15 00:29:07 +000011259 Self.PDiag(diag::note_precedence_bitwise_first)
11260 << BinaryOperator::getOpcodeStr(Opc),
Richard Trieu73088052011-08-10 22:41:34 +000011261 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +000011262}
11263
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +000011264/// \brief It accepts a '&&' expr that is inside a '||' one.
11265/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11266/// in parentheses.
11267static void
11268EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +000011269 BinaryOperator *Bop) {
11270 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +000011271 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11272 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +000011273 SuggestParentheses(Self, Bop->getOperatorLoc(),
David Blaikiedac86fd2012-10-08 01:19:49 +000011274 Self.PDiag(diag::note_precedence_silence)
11275 << Bop->getOpcodeStr(),
Chandler Carruthb00e8c02011-06-16 01:05:14 +000011276 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +000011277}
11278
11279/// \brief Returns true if the given expression can be evaluated as a constant
11280/// 'true'.
11281static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11282 bool Res;
Richard Smitha6c87032013-08-19 22:06:05 +000011283 return !E->isValueDependent() &&
11284 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +000011285}
11286
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +000011287/// \brief Returns true if the given expression can be evaluated as a constant
11288/// 'false'.
11289static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11290 bool Res;
Richard Smitha6c87032013-08-19 22:06:05 +000011291 return !E->isValueDependent() &&
11292 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +000011293}
11294
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +000011295/// \brief Look for '&&' in the left hand of a '||' expr.
11296static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +000011297 Expr *LHSExpr, Expr *RHSExpr) {
11298 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +000011299 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +000011300 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +000011301 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +000011302 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +000011303 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11304 if (!EvaluatesAsTrue(S, Bop->getLHS()))
11305 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11306 } else if (Bop->getOpcode() == BO_LOr) {
11307 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11308 // If it's "a || b && 1 || c" we didn't warn earlier for
11309 // "a || b && 1", but warn now.
11310 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11311 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11312 }
11313 }
11314 }
11315}
11316
11317/// \brief Look for '&&' in the right hand of a '||' expr.
11318static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +000011319 Expr *LHSExpr, Expr *RHSExpr) {
11320 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +000011321 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +000011322 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +000011323 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +000011324 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +000011325 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11326 if (!EvaluatesAsTrue(S, Bop->getRHS()))
11327 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +000011328 }
11329 }
11330}
11331
Craig Topper84543b02015-12-13 05:41:41 +000011332/// \brief Look for bitwise op in the left or right hand of a bitwise op with
11333/// lower precedence and emit a diagnostic together with a fixit hint that wraps
11334/// the '&' expression in parentheses.
11335static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11336 SourceLocation OpLoc, Expr *SubExpr) {
11337 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11338 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11339 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11340 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11341 << Bop->getSourceRange() << OpLoc;
11342 SuggestParentheses(S, Bop->getOperatorLoc(),
11343 S.PDiag(diag::note_precedence_silence)
11344 << Bop->getOpcodeStr(),
11345 Bop->getSourceRange());
11346 }
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +000011347 }
11348}
11349
David Blaikie15f17cb2012-10-05 00:41:03 +000011350static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
David Blaikie82d3ab92012-10-19 18:26:06 +000011351 Expr *SubExpr, StringRef Shift) {
David Blaikie15f17cb2012-10-05 00:41:03 +000011352 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11353 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
David Blaikiedac86fd2012-10-08 01:19:49 +000011354 StringRef Op = Bop->getOpcodeStr();
David Blaikie15f17cb2012-10-05 00:41:03 +000011355 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
David Blaikie82d3ab92012-10-19 18:26:06 +000011356 << Bop->getSourceRange() << OpLoc << Shift << Op;
David Blaikie15f17cb2012-10-05 00:41:03 +000011357 SuggestParentheses(S, Bop->getOperatorLoc(),
David Blaikiedac86fd2012-10-08 01:19:49 +000011358 S.PDiag(diag::note_precedence_silence) << Op,
David Blaikie15f17cb2012-10-05 00:41:03 +000011359 Bop->getSourceRange());
11360 }
11361 }
11362}
11363
Richard Trieufe042e62013-04-17 02:12:45 +000011364static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11365 Expr *LHSExpr, Expr *RHSExpr) {
11366 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11367 if (!OCE)
11368 return;
11369
11370 FunctionDecl *FD = OCE->getDirectCallee();
11371 if (!FD || !FD->isOverloadedOperator())
11372 return;
11373
11374 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11375 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11376 return;
11377
11378 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11379 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11380 << (Kind == OO_LessLess);
Richard Trieufe042e62013-04-17 02:12:45 +000011381 SuggestParentheses(S, OCE->getOperatorLoc(),
11382 S.PDiag(diag::note_precedence_silence)
11383 << (Kind == OO_LessLess ? "<<" : ">>"),
11384 OCE->getSourceRange());
Richard Trieue0894972013-04-18 01:04:37 +000011385 SuggestParentheses(S, OpLoc,
11386 S.PDiag(diag::note_evaluate_comparison_first),
11387 SourceRange(OCE->getArg(1)->getLocStart(),
11388 RHSExpr->getLocEnd()));
Richard Trieufe042e62013-04-17 02:12:45 +000011389}
11390
Sebastian Redl43028242009-10-26 15:24:15 +000011391/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +000011392/// precedence.
John McCalle3027922010-08-25 11:45:40 +000011393static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +000011394 SourceLocation OpLoc, Expr *LHSExpr,
11395 Expr *RHSExpr){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +000011396 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +000011397 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieuf9bd0f52011-09-07 02:02:10 +000011398 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +000011399
11400 // Diagnose "arg1 & arg2 | arg3"
Craig Topper84543b02015-12-13 05:41:41 +000011401 if ((Opc == BO_Or || Opc == BO_Xor) &&
11402 !OpLoc.isMacroID()/* Don't warn in macros. */) {
11403 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11404 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +000011405 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +000011406
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +000011407 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11408 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +000011409 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +000011410 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11411 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +000011412 }
David Blaikie15f17cb2012-10-05 00:41:03 +000011413
11414 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11415 || Opc == BO_Shr) {
David Blaikie82d3ab92012-10-19 18:26:06 +000011416 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11417 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11418 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
David Blaikie15f17cb2012-10-05 00:41:03 +000011419 }
Richard Trieufe042e62013-04-17 02:12:45 +000011420
11421 // Warn on overloaded shift operators and comparisons, such as:
11422 // cout << 5 == 4;
11423 if (BinaryOperator::isComparisonOp(Opc))
11424 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +000011425}
11426
Steve Naroff218bc2b2007-05-04 21:54:46 +000011427// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +000011428ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +000011429 tok::TokenKind Kind,
Richard Trieuf9bd0f52011-09-07 02:02:10 +000011430 Expr *LHSExpr, Expr *RHSExpr) {
John McCalle3027922010-08-25 11:45:40 +000011431 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Craig Topperc3ec1492014-05-26 06:22:03 +000011432 assert(LHSExpr && "ActOnBinOp(): missing left expression");
11433 assert(RHSExpr && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +000011434
Sebastian Redl43028242009-10-26 15:24:15 +000011435 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieuf9bd0f52011-09-07 02:02:10 +000011436 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +000011437
Richard Trieuf9bd0f52011-09-07 02:02:10 +000011438 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor5287f092009-11-05 00:51:44 +000011439}
11440
John McCall526ab472011-10-25 17:37:35 +000011441/// Build an overloaded binary operator expression in the given scope.
11442static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11443 BinaryOperatorKind Opc,
11444 Expr *LHS, Expr *RHS) {
11445 // Find all of the overloaded operators visible from this
11446 // point. We perform both an operator-name lookup from the local
11447 // scope and an argument-dependent lookup based on the types of
11448 // the arguments.
11449 UnresolvedSet<16> Functions;
11450 OverloadedOperatorKind OverOp
11451 = BinaryOperator::getOverloadedOperator(Opc);
Richard Smith0daabd72014-09-23 20:31:39 +000011452 if (Sc && OverOp != OO_None && OverOp != OO_Equal)
John McCall526ab472011-10-25 17:37:35 +000011453 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11454 RHS->getType(), Functions);
11455
11456 // Build the (potentially-overloaded, potentially-dependent)
11457 // binary operation.
11458 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11459}
11460
John McCalldadc5752010-08-24 06:29:42 +000011461ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +000011462 BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +000011463 Expr *LHSExpr, Expr *RHSExpr) {
John McCall9a43e122011-10-28 01:04:34 +000011464 // We want to end up calling one of checkPseudoObjectAssignment
11465 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11466 // both expressions are overloadable or either is type-dependent),
11467 // or CreateBuiltinBinOp (in any other case). We also want to get
11468 // any placeholder types out of the way.
11469
John McCall526ab472011-10-25 17:37:35 +000011470 // Handle pseudo-objects in the LHS.
11471 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11472 // Assignments with a pseudo-object l-value need special analysis.
11473 if (pty->getKind() == BuiltinType::PseudoObject &&
11474 BinaryOperator::isAssignmentOp(Opc))
11475 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11476
11477 // Don't resolve overloads if the other type is overloadable.
11478 if (pty->getKind() == BuiltinType::Overload) {
11479 // We can't actually test that if we still have a placeholder,
11480 // though. Fortunately, none of the exceptions we see in that
John McCall9a43e122011-10-28 01:04:34 +000011481 // code below are valid when the LHS is an overload set. Note
11482 // that an overload set can be dependently-typed, but it never
11483 // instantiates to having an overloadable type.
John McCall526ab472011-10-25 17:37:35 +000011484 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11485 if (resolvedRHS.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011486 RHSExpr = resolvedRHS.get();
John McCall526ab472011-10-25 17:37:35 +000011487
John McCall9a43e122011-10-28 01:04:34 +000011488 if (RHSExpr->isTypeDependent() ||
11489 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +000011490 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11491 }
11492
11493 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11494 if (LHS.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011495 LHSExpr = LHS.get();
John McCall526ab472011-10-25 17:37:35 +000011496 }
11497
11498 // Handle pseudo-objects in the RHS.
11499 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11500 // An overload in the RHS can potentially be resolved by the type
11501 // being assigned to.
John McCall9a43e122011-10-28 01:04:34 +000011502 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11503 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11504 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11505
Eli Friedman419b1ff2012-01-17 21:27:43 +000011506 if (LHSExpr->getType()->isOverloadableType())
11507 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11508
John McCall526ab472011-10-25 17:37:35 +000011509 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCall9a43e122011-10-28 01:04:34 +000011510 }
John McCall526ab472011-10-25 17:37:35 +000011511
11512 // Don't resolve overloads if the other type is overloadable.
11513 if (pty->getKind() == BuiltinType::Overload &&
11514 LHSExpr->getType()->isOverloadableType())
11515 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11516
11517 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11518 if (!resolvedRHS.isUsable()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011519 RHSExpr = resolvedRHS.get();
John McCall526ab472011-10-25 17:37:35 +000011520 }
11521
David Blaikiebbafb8a2012-03-11 07:00:24 +000011522 if (getLangOpts().CPlusPlus) {
John McCall9a43e122011-10-28 01:04:34 +000011523 // If either expression is type-dependent, always build an
11524 // overloaded op.
11525 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11526 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011527
John McCall9a43e122011-10-28 01:04:34 +000011528 // Otherwise, build an overloaded op if either expression has an
11529 // overloadable type.
11530 if (LHSExpr->getType()->isOverloadableType() ||
11531 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +000011532 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb5d49352009-01-19 22:31:54 +000011533 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011534
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +000011535 // Build a built-in binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +000011536 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Steve Naroff218bc2b2007-05-04 21:54:46 +000011537}
11538
John McCalldadc5752010-08-24 06:29:42 +000011539ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +000011540 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +000011541 Expr *InputExpr) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011542 ExprResult Input = InputExpr;
John McCall7decc9e2010-11-18 06:31:45 +000011543 ExprValueKind VK = VK_RValue;
11544 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +000011545 QualType resultType;
Anastasia Stulovade0e4242015-09-30 13:18:52 +000011546 if (getLangOpts().OpenCL) {
Anastasia Stulova4d850032016-07-11 13:46:02 +000011547 QualType Ty = InputExpr->getType();
Anastasia Stulovade0e4242015-09-30 13:18:52 +000011548 // The only legal unary operation for atomics is '&'.
Anastasia Stulova4d850032016-07-11 13:46:02 +000011549 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11550 // OpenCL special types - image, sampler, pipe, and blocks are to be used
11551 // only with a builtin functions and therefore should be disallowed here.
11552 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11553 || Ty->isBlockPointerType())) {
Anastasia Stulovade0e4242015-09-30 13:18:52 +000011554 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11555 << InputExpr->getType()
11556 << Input.get()->getSourceRange());
11557 }
11558 }
Steve Naroff35d85152007-05-07 00:24:15 +000011559 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +000011560 case UO_PreInc:
11561 case UO_PreDec:
11562 case UO_PostInc:
11563 case UO_PostDec:
David Majnemer74242432014-07-31 04:52:13 +000011564 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11565 OpLoc,
John McCalle3027922010-08-25 11:45:40 +000011566 Opc == UO_PreInc ||
11567 Opc == UO_PostInc,
11568 Opc == UO_PreInc ||
11569 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +000011570 break;
John McCalle3027922010-08-25 11:45:40 +000011571 case UO_AddrOf:
Richard Smithaf9de912013-07-11 02:26:56 +000011572 resultType = CheckAddressOfOperand(Input, OpLoc);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011573 RecordModifiableNonNullParam(*this, InputExpr);
Steve Naroff35d85152007-05-07 00:24:15 +000011574 break;
John McCall31996342011-04-07 08:22:57 +000011575 case UO_Deref: {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011576 Input = DefaultFunctionArrayLvalueConversion(Input.get());
Eli Friedman34866c72012-08-31 00:14:07 +000011577 if (Input.isInvalid()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011578 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +000011579 break;
John McCall31996342011-04-07 08:22:57 +000011580 }
John McCalle3027922010-08-25 11:45:40 +000011581 case UO_Plus:
11582 case UO_Minus:
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011583 Input = UsualUnaryConversions(Input.get());
John Wiegley01296292011-04-08 18:41:53 +000011584 if (Input.isInvalid()) return ExprError();
11585 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000011586 if (resultType->isDependentType())
11587 break;
Ulrich Weigand3c5038a2015-07-30 14:08:36 +000011588 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11589 break;
11590 else if (resultType->isVectorType() &&
11591 // The z vector extensions don't allow + or - with bool vectors.
11592 (!Context.getLangOpts().ZVector ||
11593 resultType->getAs<VectorType>()->getVectorKind() !=
11594 VectorType::AltiVecBool))
Douglas Gregord08452f2008-11-19 15:42:04 +000011595 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +000011596 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +000011597 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +000011598 resultType->isPointerType())
11599 break;
11600
Sebastian Redlc215cfc2009-01-19 00:08:26 +000011601 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +000011602 << resultType << Input.get()->getSourceRange());
11603
John McCalle3027922010-08-25 11:45:40 +000011604 case UO_Not: // bitwise complement
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011605 Input = UsualUnaryConversions(Input.get());
Joey Gouly7d00f002013-02-21 11:49:56 +000011606 if (Input.isInvalid())
11607 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011608 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000011609 if (resultType->isDependentType())
11610 break;
Chris Lattner0d707612008-07-25 23:52:49 +000011611 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11612 if (resultType->isComplexType() || resultType->isComplexIntegerType())
11613 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +000011614 Diag(OpLoc, diag::ext_integer_complement_complex)
Joey Gouly7d00f002013-02-21 11:49:56 +000011615 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +000011616 else if (resultType->hasIntegerRepresentation())
11617 break;
Joey Gouly7d00f002013-02-21 11:49:56 +000011618 else if (resultType->isExtVectorType()) {
11619 if (Context.getLangOpts().OpenCL) {
11620 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11621 // on vector float types.
11622 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11623 if (!T->isIntegerType())
11624 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11625 << resultType << Input.get()->getSourceRange());
11626 }
11627 break;
11628 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +000011629 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
Joey Gouly7d00f002013-02-21 11:49:56 +000011630 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +000011631 }
Steve Naroff35d85152007-05-07 00:24:15 +000011632 break;
John Wiegley01296292011-04-08 18:41:53 +000011633
John McCalle3027922010-08-25 11:45:40 +000011634 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +000011635 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011636 Input = DefaultFunctionArrayLvalueConversion(Input.get());
John Wiegley01296292011-04-08 18:41:53 +000011637 if (Input.isInvalid()) return ExprError();
11638 resultType = Input.get()->getType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000011639
11640 // Though we still have to promote half FP to float...
Joey Goulydd7f4562013-01-23 11:56:20 +000011641 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011642 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000011643 resultType = Context.FloatTy;
11644 }
11645
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000011646 if (resultType->isDependentType())
11647 break;
Alp Tokerc620cab2014-01-20 07:20:22 +000011648 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
Abramo Bagnara7ccce982011-04-07 09:26:19 +000011649 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikiebbafb8a2012-03-11 07:00:24 +000011650 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara7ccce982011-04-07 09:26:19 +000011651 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11652 // operand contextually converted to bool.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011653 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
John Wiegley01296292011-04-08 18:41:53 +000011654 ScalarTypeToBooleanCastKind(resultType));
Joey Gouly7d00f002013-02-21 11:49:56 +000011655 } else if (Context.getLangOpts().OpenCL &&
11656 Context.getLangOpts().OpenCLVersion < 120) {
11657 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11658 // operate on scalar float types.
11659 if (!resultType->isIntegerType())
11660 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11661 << resultType << Input.get()->getSourceRange());
Abramo Bagnara7ccce982011-04-07 09:26:19 +000011662 }
Tanya Lattner3dd33b22012-01-19 01:16:16 +000011663 } else if (resultType->isExtVectorType()) {
Joey Gouly7d00f002013-02-21 11:49:56 +000011664 if (Context.getLangOpts().OpenCL &&
11665 Context.getLangOpts().OpenCLVersion < 120) {
11666 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11667 // operate on vector float types.
11668 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11669 if (!T->isIntegerType())
11670 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11671 << resultType << Input.get()->getSourceRange());
11672 }
Tanya Lattner20248222012-01-16 21:02:28 +000011673 // Vector logical not returns the signed variant of the operand type.
11674 resultType = GetSignedVectorType(resultType);
11675 break;
John McCall36226622010-10-12 02:09:17 +000011676 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +000011677 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +000011678 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +000011679 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +000011680
Chris Lattnerbe31ed82007-06-02 19:11:33 +000011681 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +000011682 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +000011683 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +000011684 break;
John McCalle3027922010-08-25 11:45:40 +000011685 case UO_Real:
11686 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +000011687 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smith0b6b8e42012-02-18 20:53:32 +000011688 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11689 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley01296292011-04-08 18:41:53 +000011690 if (Input.isInvalid()) return ExprError();
Richard Smith0b6b8e42012-02-18 20:53:32 +000011691 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11692 if (Input.get()->getValueKind() != VK_RValue &&
11693 Input.get()->getObjectKind() == OK_Ordinary)
11694 VK = Input.get()->getValueKind();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011695 } else if (!getLangOpts().CPlusPlus) {
Richard Smith0b6b8e42012-02-18 20:53:32 +000011696 // In C, a volatile scalar is read by __imag. In C++, it is not.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011697 Input = DefaultLvalueConversion(Input.get());
Richard Smith0b6b8e42012-02-18 20:53:32 +000011698 }
Chris Lattner30b5dd02007-08-24 21:16:53 +000011699 break;
John McCalle3027922010-08-25 11:45:40 +000011700 case UO_Extension:
Richard Smith9f690bd2015-10-27 06:02:45 +000011701 case UO_Coawait:
John Wiegley01296292011-04-08 18:41:53 +000011702 resultType = Input.get()->getType();
11703 VK = Input.get()->getValueKind();
11704 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +000011705 break;
Steve Naroff35d85152007-05-07 00:24:15 +000011706 }
John Wiegley01296292011-04-08 18:41:53 +000011707 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +000011708 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +000011709
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011710 // Check for array bounds violations in the operand of the UnaryOperator,
11711 // except for the '*' and '&' operators that have to be handled specially
11712 // by CheckArrayAccess (as there are special cases like &array[arraysize]
11713 // that are explicitly defined as valid by the standard).
11714 if (Opc != UO_AddrOf && Opc != UO_Deref)
11715 CheckArrayAccess(Input.get());
11716
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011717 return new (Context)
11718 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +000011719}
Chris Lattnereefa10e2007-05-28 06:56:27 +000011720
Douglas Gregor72341032011-12-14 21:23:13 +000011721/// \brief Determine whether the given expression is a qualified member
11722/// access expression, of a form that could be turned into a pointer to member
11723/// with the address-of operator.
11724static bool isQualifiedMemberAccess(Expr *E) {
11725 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11726 if (!DRE->getQualifier())
11727 return false;
11728
11729 ValueDecl *VD = DRE->getDecl();
11730 if (!VD->isCXXClassMember())
11731 return false;
11732
11733 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11734 return true;
11735 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11736 return Method->isInstance();
11737
11738 return false;
11739 }
11740
11741 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11742 if (!ULE->getQualifier())
11743 return false;
11744
Craig Topperdfe29ae2015-12-21 06:35:56 +000011745 for (NamedDecl *D : ULE->decls()) {
11746 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor72341032011-12-14 21:23:13 +000011747 if (Method->isInstance())
11748 return true;
11749 } else {
11750 // Overload set does not contain methods.
11751 break;
11752 }
11753 }
11754
11755 return false;
11756 }
11757
11758 return false;
11759}
11760
John McCalldadc5752010-08-24 06:29:42 +000011761ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +000011762 UnaryOperatorKind Opc, Expr *Input) {
John McCall526ab472011-10-25 17:37:35 +000011763 // First things first: handle placeholders so that the
11764 // overloaded-operator check considers the right type.
11765 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11766 // Increment and decrement of pseudo-object references.
11767 if (pty->getKind() == BuiltinType::PseudoObject &&
11768 UnaryOperator::isIncrementDecrementOp(Opc))
11769 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11770
11771 // extension is always a builtin operator.
11772 if (Opc == UO_Extension)
11773 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11774
11775 // & gets special logic for several kinds of placeholder.
11776 // The builtin code knows what to do.
11777 if (Opc == UO_AddrOf &&
11778 (pty->getKind() == BuiltinType::Overload ||
11779 pty->getKind() == BuiltinType::UnknownAny ||
11780 pty->getKind() == BuiltinType::BoundMember))
11781 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11782
11783 // Anything else needs to be handled now.
11784 ExprResult Result = CheckPlaceholderExpr(Input);
11785 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011786 Input = Result.get();
John McCall526ab472011-10-25 17:37:35 +000011787 }
11788
David Blaikiebbafb8a2012-03-11 07:00:24 +000011789 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregor72341032011-12-14 21:23:13 +000011790 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11791 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregor084d8552009-03-13 23:49:33 +000011792 // Find all of the overloaded operators visible from this
11793 // point. We perform both an operator-name lookup from the local
11794 // scope and an argument-dependent lookup based on the types of
11795 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +000011796 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +000011797 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +000011798 if (S && OverOp != OO_None)
11799 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11800 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011801
John McCallb268a282010-08-23 23:25:46 +000011802 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011803 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011804
John McCallb268a282010-08-23 23:25:46 +000011805 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011806}
11807
Douglas Gregor5287f092009-11-05 00:51:44 +000011808// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +000011809ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +000011810 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +000011811 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +000011812}
11813
Steve Naroff66356bd2007-09-16 14:56:35 +000011814/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +000011815ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +000011816 LabelDecl *TheDecl) {
Eli Friedman276dd182013-09-05 00:02:25 +000011817 TheDecl->markUsed(Context);
Chris Lattnereefa10e2007-05-28 06:56:27 +000011818 // Create the AST node. The address of a label always has type 'void*'.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011819 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11820 Context.getPointerType(Context.VoidTy));
Chris Lattnereefa10e2007-05-28 06:56:27 +000011821}
11822
John McCall31168b02011-06-15 23:02:42 +000011823/// Given the last statement in a statement-expression, check whether
11824/// the result is a producing expression (like a call to an
11825/// ns_returns_retained function) and, if so, rebuild it to hoist the
11826/// release out of the full-expression. Otherwise, return null.
11827/// Cannot fail.
Richard Trieuba63ce62011-09-09 01:45:06 +000011828static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCall31168b02011-06-15 23:02:42 +000011829 // Should always be wrapped with one of these.
Richard Trieuba63ce62011-09-09 01:45:06 +000011830 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
Craig Topperc3ec1492014-05-26 06:22:03 +000011831 if (!cleanups) return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011832
11833 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall2d637d22011-09-10 06:18:15 +000011834 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
Craig Topperc3ec1492014-05-26 06:22:03 +000011835 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011836
11837 // Splice out the cast. This shouldn't modify any interesting
11838 // features of the statement.
11839 Expr *producer = cast->getSubExpr();
11840 assert(producer->getType() == cast->getType());
11841 assert(producer->getValueKind() == cast->getValueKind());
11842 cleanups->setSubExpr(producer);
11843 return cleanups;
11844}
11845
John McCall3abee492012-04-04 01:27:53 +000011846void Sema::ActOnStartStmtExpr() {
11847 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11848}
11849
11850void Sema::ActOnStmtExprError() {
John McCalled7b2782012-04-06 18:20:53 +000011851 // Note that function is also called by TreeTransform when leaving a
11852 // StmtExpr scope without rebuilding anything.
11853
John McCall3abee492012-04-04 01:27:53 +000011854 DiscardCleanupsInEvaluationContext();
11855 PopExpressionEvaluationContext();
11856}
11857
John McCalldadc5752010-08-24 06:29:42 +000011858ExprResult
John McCallb268a282010-08-23 23:25:46 +000011859Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +000011860 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +000011861 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11862 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11863
John McCall3abee492012-04-04 01:27:53 +000011864 if (hasAnyUnrecoverableErrorsInThisFunction())
11865 DiscardCleanupsInEvaluationContext();
Tim Shen4a05bb82016-06-21 20:29:17 +000011866 assert(!Cleanup.exprNeedsCleanups() &&
11867 "cleanups within StmtExpr not correctly bound!");
John McCall3abee492012-04-04 01:27:53 +000011868 PopExpressionEvaluationContext();
11869
Chris Lattner366727f2007-07-24 16:58:17 +000011870 // FIXME: there are a variety of strange constraints to enforce here, for
11871 // example, it is not possible to goto into a stmt expression apparently.
11872 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +000011873
Alp Toker028ed912013-12-06 17:56:43 +000011874 // If there are sub-stmts in the compound stmt, take the type of the last one
Chris Lattner366727f2007-07-24 16:58:17 +000011875 // as the type of the stmtexpr.
11876 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +000011877 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +000011878 if (!Compound->body_empty()) {
11879 Stmt *LastStmt = Compound->body_back();
Craig Topperc3ec1492014-05-26 06:22:03 +000011880 LabelStmt *LastLabelStmt = nullptr;
Chris Lattner944d3062008-07-26 19:51:01 +000011881 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +000011882 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11883 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +000011884 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +000011885 }
John McCall31168b02011-06-15 23:02:42 +000011886
John Wiegley01296292011-04-08 18:41:53 +000011887 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +000011888 // Do function/array conversion on the last expression, but not
11889 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +000011890 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11891 if (LastExpr.isInvalid())
11892 return ExprError();
11893 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +000011894
John Wiegley01296292011-04-08 18:41:53 +000011895 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +000011896 // In ARC, if the final expression ends in a consume, splice
11897 // the consume out and bind it later. In the alternate case
11898 // (when dealing with a retainable type), the result
11899 // initialization will create a produce. In both cases the
11900 // result will be +1, and we'll need to balance that out with
11901 // a bind.
11902 if (Expr *rebuiltLastStmt
11903 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11904 LastExpr = rebuiltLastStmt;
11905 } else {
11906 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +000011907 InitializedEntity::InitializeResult(LPLoc,
11908 Ty,
11909 false),
11910 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +000011911 LastExpr);
11912 }
11913
John Wiegley01296292011-04-08 18:41:53 +000011914 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +000011915 return ExprError();
Craig Topperc3ec1492014-05-26 06:22:03 +000011916 if (LastExpr.get() != nullptr) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +000011917 if (!LastLabelStmt)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011918 Compound->setLastStmt(LastExpr.get());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +000011919 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011920 LastLabelStmt->setSubStmt(LastExpr.get());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +000011921 StmtExprMayBindToTemp = true;
11922 }
11923 }
11924 }
Chris Lattner944d3062008-07-26 19:51:01 +000011925 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000011926
Eli Friedmanba961a92009-03-23 00:24:07 +000011927 // FIXME: Check that expression type is complete/non-abstract; statement
11928 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +000011929 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
11930 if (StmtExprMayBindToTemp)
11931 return MaybeBindToTemporary(ResStmtExpr);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011932 return ResStmtExpr;
Chris Lattner366727f2007-07-24 16:58:17 +000011933}
Steve Naroff78864672007-08-01 22:05:33 +000011934
John McCalldadc5752010-08-24 06:29:42 +000011935ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +000011936 TypeSourceInfo *TInfo,
Craig Topperb5518242015-10-22 04:59:59 +000011937 ArrayRef<OffsetOfComponent> Components,
John McCall36226622010-10-12 02:09:17 +000011938 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +000011939 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000011940 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000011941 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +000011942
Chris Lattnerf17bd422007-08-30 17:45:32 +000011943 // We must have at least one component that refers to the type, and the first
11944 // one is known to be a field designator. Verify that the ArgTy represents
11945 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000011946 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +000011947 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
11948 << ArgTy << TypeRange);
11949
11950 // Type must be complete per C99 7.17p3 because a declaring a variable
11951 // with an incomplete type would be ill-formed.
11952 if (!Dependent
11953 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011954 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor882211c2010-04-28 22:16:22 +000011955 return ExprError();
11956
Chris Lattner78502cf2007-08-31 21:49:13 +000011957 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
11958 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +000011959 // FIXME: This diagnostic isn't actually visible because the location is in
11960 // a system header!
Craig Topperb5518242015-10-22 04:59:59 +000011961 if (Components.size() != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +000011962 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
Craig Topperb5518242015-10-22 04:59:59 +000011963 << SourceRange(Components[1].LocStart, Components.back().LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +000011964
11965 bool DidWarnAboutNonPOD = false;
11966 QualType CurrentType = ArgTy;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011967 SmallVector<OffsetOfNode, 4> Comps;
11968 SmallVector<Expr*, 4> Exprs;
Craig Topperb5518242015-10-22 04:59:59 +000011969 for (const OffsetOfComponent &OC : Components) {
Douglas Gregor882211c2010-04-28 22:16:22 +000011970 if (OC.isBrackets) {
11971 // Offset of an array sub-field. TODO: Should we allow vector elements?
11972 if (!CurrentType->isDependentType()) {
11973 const ArrayType *AT = Context.getAsArrayType(CurrentType);
11974 if(!AT)
11975 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
11976 << CurrentType);
11977 CurrentType = AT->getElementType();
11978 } else
11979 CurrentType = Context.DependentTy;
11980
Richard Smith9fcc5c32011-10-17 23:29:39 +000011981 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
11982 if (IdxRval.isInvalid())
11983 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011984 Expr *Idx = IdxRval.get();
Richard Smith9fcc5c32011-10-17 23:29:39 +000011985
Douglas Gregor882211c2010-04-28 22:16:22 +000011986 // The expression must be an integral expression.
11987 // FIXME: An integral constant expression?
Douglas Gregor882211c2010-04-28 22:16:22 +000011988 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
11989 !Idx->getType()->isIntegerType())
11990 return ExprError(Diag(Idx->getLocStart(),
11991 diag::err_typecheck_subscript_not_integer)
11992 << Idx->getSourceRange());
Richard Smitheda612882011-10-17 05:48:07 +000011993
Douglas Gregor882211c2010-04-28 22:16:22 +000011994 // Record this array index.
11995 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smith9fcc5c32011-10-17 23:29:39 +000011996 Exprs.push_back(Idx);
Douglas Gregor882211c2010-04-28 22:16:22 +000011997 continue;
11998 }
11999
12000 // Offset of a field.
12001 if (CurrentType->isDependentType()) {
12002 // We have the offset of a field, but we can't look into the dependent
12003 // type. Just record the identifier of the field.
12004 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
12005 CurrentType = Context.DependentTy;
12006 continue;
12007 }
12008
12009 // We need to have a complete type to look into.
12010 if (RequireCompleteType(OC.LocStart, CurrentType,
12011 diag::err_offsetof_incomplete_type))
12012 return ExprError();
12013
12014 // Look for the designated field.
12015 const RecordType *RC = CurrentType->getAs<RecordType>();
12016 if (!RC)
12017 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12018 << CurrentType);
12019 RecordDecl *RD = RC->getDecl();
12020
12021 // C++ [lib.support.types]p5:
12022 // The macro offsetof accepts a restricted set of type arguments in this
12023 // International Standard. type shall be a POD structure or a POD union
12024 // (clause 9).
Benjamin Kramer9e7876b2012-04-28 11:14:51 +000012025 // C++11 [support.types]p4:
12026 // If type is not a standard-layout class (Clause 9), the results are
12027 // undefined.
Douglas Gregor882211c2010-04-28 22:16:22 +000012028 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012029 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
Benjamin Kramer9e7876b2012-04-28 11:14:51 +000012030 unsigned DiagID =
Richard Smith1b98ccc2014-07-19 01:39:17 +000012031 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
12032 : diag::ext_offsetof_non_pod_type;
Benjamin Kramer9e7876b2012-04-28 11:14:51 +000012033
12034 if (!IsSafe && !DidWarnAboutNonPOD &&
Craig Topperc3ec1492014-05-26 06:22:03 +000012035 DiagRuntimeBehavior(BuiltinLoc, nullptr,
Benjamin Kramer9e7876b2012-04-28 11:14:51 +000012036 PDiag(DiagID)
Craig Topperb5518242015-10-22 04:59:59 +000012037 << SourceRange(Components[0].LocStart, OC.LocEnd)
Douglas Gregor882211c2010-04-28 22:16:22 +000012038 << CurrentType))
12039 DidWarnAboutNonPOD = true;
12040 }
12041
12042 // Look for the field.
12043 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
12044 LookupQualifiedName(R, RD);
12045 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Craig Topperc3ec1492014-05-26 06:22:03 +000012046 IndirectFieldDecl *IndirectMemberDecl = nullptr;
Francois Pichet783dd6e2010-11-21 06:08:52 +000012047 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +000012048 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +000012049 MemberDecl = IndirectMemberDecl->getAnonField();
12050 }
12051
Douglas Gregor882211c2010-04-28 22:16:22 +000012052 if (!MemberDecl)
12053 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
12054 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
12055 OC.LocEnd));
12056
Douglas Gregor10982ea2010-04-28 22:36:06 +000012057 // C99 7.17p3:
12058 // (If the specified member is a bit-field, the behavior is undefined.)
12059 //
12060 // We diagnose this as an error.
Richard Smithcaf33902011-10-10 18:28:20 +000012061 if (MemberDecl->isBitField()) {
Douglas Gregor10982ea2010-04-28 22:36:06 +000012062 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
12063 << MemberDecl->getDeclName()
12064 << SourceRange(BuiltinLoc, RParenLoc);
12065 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
12066 return ExprError();
12067 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +000012068
12069 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +000012070 if (IndirectMemberDecl)
12071 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +000012072
Douglas Gregord1702062010-04-29 00:18:15 +000012073 // If the member was found in a base class, introduce OffsetOfNodes for
12074 // the base class indirections.
David Majnemerff17f832013-10-15 06:28:23 +000012075 CXXBasePaths Paths;
Richard Smith0f59cb32015-12-18 21:45:41 +000012076 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
12077 Paths)) {
David Majnemerff17f832013-10-15 06:28:23 +000012078 if (Paths.getDetectedVirtual()) {
12079 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
12080 << MemberDecl->getDeclName()
12081 << SourceRange(BuiltinLoc, RParenLoc);
12082 return ExprError();
12083 }
12084
Douglas Gregord1702062010-04-29 00:18:15 +000012085 CXXBasePath &Path = Paths.front();
Craig Topperdfe29ae2015-12-21 06:35:56 +000012086 for (const CXXBasePathElement &B : Path)
12087 Comps.push_back(OffsetOfNode(B.Base));
Douglas Gregord1702062010-04-29 00:18:15 +000012088 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +000012089
Francois Pichet783dd6e2010-11-21 06:08:52 +000012090 if (IndirectMemberDecl) {
Aaron Ballman29c94602014-03-07 18:36:15 +000012091 for (auto *FI : IndirectMemberDecl->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +000012092 assert(isa<FieldDecl>(FI));
Francois Pichet783dd6e2010-11-21 06:08:52 +000012093 Comps.push_back(OffsetOfNode(OC.LocStart,
Aaron Ballman13916082014-03-07 18:11:58 +000012094 cast<FieldDecl>(FI), OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +000012095 }
12096 } else
Douglas Gregor882211c2010-04-28 22:16:22 +000012097 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +000012098
Douglas Gregor882211c2010-04-28 22:16:22 +000012099 CurrentType = MemberDecl->getType().getNonReferenceType();
12100 }
12101
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012102 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
12103 Comps, Exprs, RParenLoc);
Douglas Gregor882211c2010-04-28 22:16:22 +000012104}
Mike Stump4e1f26a2009-02-19 03:04:26 +000012105
John McCalldadc5752010-08-24 06:29:42 +000012106ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +000012107 SourceLocation BuiltinLoc,
12108 SourceLocation TypeLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +000012109 ParsedType ParsedArgTy,
Craig Topperb5518242015-10-22 04:59:59 +000012110 ArrayRef<OffsetOfComponent> Components,
Richard Trieuba63ce62011-09-09 01:45:06 +000012111 SourceLocation RParenLoc) {
John McCall36226622010-10-12 02:09:17 +000012112
Douglas Gregor882211c2010-04-28 22:16:22 +000012113 TypeSourceInfo *ArgTInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +000012114 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor882211c2010-04-28 22:16:22 +000012115 if (ArgTy.isNull())
12116 return ExprError();
12117
Eli Friedman06dcfd92010-08-05 10:15:45 +000012118 if (!ArgTInfo)
12119 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12120
Craig Topperb5518242015-10-22 04:59:59 +000012121 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +000012122}
12123
12124
John McCalldadc5752010-08-24 06:29:42 +000012125ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +000012126 Expr *CondExpr,
12127 Expr *LHSExpr, Expr *RHSExpr,
12128 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +000012129 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12130
John McCall7decc9e2010-11-18 06:31:45 +000012131 ExprValueKind VK = VK_RValue;
12132 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000012133 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +000012134 bool ValueDependent = false;
Eli Friedman75807f22013-07-20 00:40:58 +000012135 bool CondIsTrue = false;
Douglas Gregor0df91122009-05-19 22:43:30 +000012136 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000012137 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +000012138 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000012139 } else {
12140 // The conditional expression is required to be a constant expression.
12141 llvm::APSInt condEval(32);
Douglas Gregore2b37442012-05-04 22:38:52 +000012142 ExprResult CondICE
12143 = VerifyIntegerConstantExpression(CondExpr, &condEval,
12144 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smithf4c51d92012-02-04 09:53:13 +000012145 if (CondICE.isInvalid())
12146 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012147 CondExpr = CondICE.get();
Eli Friedman75807f22013-07-20 00:40:58 +000012148 CondIsTrue = condEval.getZExtValue();
Steve Naroff9efdabc2007-08-03 21:21:27 +000012149
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000012150 // If the condition is > zero, then the AST type is the same as the LSHExpr.
Eli Friedman75807f22013-07-20 00:40:58 +000012151 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
John McCall7decc9e2010-11-18 06:31:45 +000012152
12153 resType = ActiveExpr->getType();
12154 ValueDependent = ActiveExpr->isValueDependent();
12155 VK = ActiveExpr->getValueKind();
12156 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +000012157 }
12158
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012159 return new (Context)
12160 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12161 CondIsTrue, resType->isDependentType(), ValueDependent);
Steve Naroff9efdabc2007-08-03 21:21:27 +000012162}
12163
Steve Naroffc540d662008-09-03 18:15:37 +000012164//===----------------------------------------------------------------------===//
12165// Clang Extensions.
12166//===----------------------------------------------------------------------===//
12167
12168/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuba63ce62011-09-09 01:45:06 +000012169void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +000012170 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Eli Friedman7e346a82013-07-01 20:22:57 +000012171
Eli Friedman4ef077a2013-09-12 22:36:24 +000012172 if (LangOpts.CPlusPlus) {
Eli Friedman7e346a82013-07-01 20:22:57 +000012173 Decl *ManglingContextDecl;
12174 if (MangleNumberingContext *MCtx =
12175 getCurrentMangleNumberContext(Block->getDeclContext(),
12176 ManglingContextDecl)) {
12177 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12178 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12179 }
12180 }
12181
Richard Trieuba63ce62011-09-09 01:45:06 +000012182 PushBlockScope(CurScope, Block);
Douglas Gregor9a28e842010-03-01 23:15:13 +000012183 CurContext->addDecl(Block);
Richard Trieuba63ce62011-09-09 01:45:06 +000012184 if (CurScope)
12185 PushDeclContext(CurScope, Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +000012186 else
12187 CurContext = Block;
John McCallf1a3c2a2011-11-11 03:19:12 +000012188
Eli Friedman34b49062012-01-26 03:00:14 +000012189 getCurBlock()->HasImplicitReturnType = true;
12190
John McCallf1a3c2a2011-11-11 03:19:12 +000012191 // Enter a new evaluation context to insulate the block from any
12192 // cleanups from the enclosing full-expression.
12193 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff1d95e5a2008-10-10 01:28:17 +000012194}
12195
Douglas Gregor7efd007c2012-06-15 16:59:29 +000012196void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12197 Scope *CurScope) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012198 assert(ParamInfo.getIdentifier() == nullptr &&
12199 "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +000012200 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +000012201 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000012202
John McCall8cb7bdf2010-06-04 23:28:52 +000012203 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +000012204 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +000012205
Douglas Gregor7efd007c2012-06-15 16:59:29 +000012206 // FIXME: We should allow unexpanded parameter packs here, but that would,
12207 // in turn, make the block expression contain unexpanded parameter packs.
12208 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12209 // Drop the parameters.
12210 FunctionProtoType::ExtProtoInfo EPI;
12211 EPI.HasTrailingReturn = false;
12212 EPI.TypeQuals |= DeclSpec::TQ_const;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012213 T = Context.getFunctionType(Context.DependentTy, None, EPI);
Douglas Gregor7efd007c2012-06-15 16:59:29 +000012214 Sig = Context.getTrivialTypeSourceInfo(T);
12215 }
12216
John McCall3882ace2011-01-05 12:14:39 +000012217 // GetTypeForDeclarator always produces a function type for a block
12218 // literal signature. Furthermore, it is always a FunctionProtoType
12219 // unless the function was written with a typedef.
12220 assert(T->isFunctionType() &&
12221 "GetTypeForDeclarator made a non-function block signature");
12222
12223 // Look for an explicit signature in that function type.
12224 FunctionProtoTypeLoc ExplicitSignature;
12225
12226 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +000012227 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
John McCall3882ace2011-01-05 12:14:39 +000012228
12229 // Check whether that explicit signature was synthesized by
12230 // GetTypeForDeclarator. If so, don't save that as part of the
12231 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012232 if (ExplicitSignature.getLocalRangeBegin() ==
12233 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +000012234 // This would be much cheaper if we stored TypeLocs instead of
12235 // TypeSourceInfos.
Alp Toker42a16a62014-01-25 23:51:36 +000012236 TypeLoc Result = ExplicitSignature.getReturnLoc();
John McCall3882ace2011-01-05 12:14:39 +000012237 unsigned Size = Result.getFullDataSize();
12238 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12239 Sig->getTypeLoc().initializeFullCopy(Result, Size);
12240
12241 ExplicitSignature = FunctionProtoTypeLoc();
12242 }
John McCalla3ccba02010-06-04 11:21:44 +000012243 }
Mike Stump11289f42009-09-09 15:08:12 +000012244
John McCall3882ace2011-01-05 12:14:39 +000012245 CurBlock->TheDecl->setSignatureAsWritten(Sig);
12246 CurBlock->FunctionType = T;
12247
12248 const FunctionType *Fn = T->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +000012249 QualType RetTy = Fn->getReturnType();
John McCall3882ace2011-01-05 12:14:39 +000012250 bool isVariadic =
12251 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12252
John McCall8e346702010-06-04 19:02:56 +000012253 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +000012254
John McCalla3ccba02010-06-04 11:21:44 +000012255 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +000012256 // return type. TODO: what should we do with declarators like:
12257 // ^ * { ... }
12258 // If the answer is "apply template argument deduction"....
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +000012259 if (RetTy != Context.DependentTy) {
John McCalla3ccba02010-06-04 11:21:44 +000012260 CurBlock->ReturnType = RetTy;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +000012261 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman34b49062012-01-26 03:00:14 +000012262 CurBlock->HasImplicitReturnType = false;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +000012263 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000012264
John McCalla3ccba02010-06-04 11:21:44 +000012265 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012266 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +000012267 if (ExplicitSignature) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012268 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12269 ParmVarDecl *Param = ExplicitSignature.getParam(I);
Craig Topperc3ec1492014-05-26 06:22:03 +000012270 if (Param->getIdentifier() == nullptr &&
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +000012271 !Param->isImplicit() &&
12272 !Param->isInvalidDecl() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000012273 !getLangOpts().CPlusPlus)
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +000012274 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +000012275 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +000012276 }
John McCalla3ccba02010-06-04 11:21:44 +000012277
12278 // Fake up parameter variables if we have a typedef, like
12279 // ^ fntype { ... }
12280 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +000012281 for (const auto &I : Fn->param_types()) {
12282 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12283 CurBlock->TheDecl, ParamInfo.getLocStart(), I);
John McCall8e346702010-06-04 19:02:56 +000012284 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +000012285 }
Steve Naroffc540d662008-09-03 18:15:37 +000012286 }
John McCalla3ccba02010-06-04 11:21:44 +000012287
John McCall8e346702010-06-04 19:02:56 +000012288 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +000012289 if (!Params.empty()) {
David Blaikie9c70e042011-09-21 18:16:56 +000012290 CurBlock->TheDecl->setParams(Params);
David Majnemer59f77922016-06-24 04:05:48 +000012291 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
Douglas Gregorb524d902010-11-01 18:37:59 +000012292 /*CheckParameterNames=*/false);
12293 }
12294
John McCalla3ccba02010-06-04 11:21:44 +000012295 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +000012296 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +000012297
Eli Friedman7e346a82013-07-01 20:22:57 +000012298 // Put the parameter variables in scope.
David Majnemer59f77922016-06-24 04:05:48 +000012299 for (auto AI : CurBlock->TheDecl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +000012300 AI->setOwningFunction(CurBlock->TheDecl);
John McCallf7b2fb52010-01-22 00:28:27 +000012301
Steve Naroff1d95e5a2008-10-10 01:28:17 +000012302 // If this has an identifier, add it to the scope stack.
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +000012303 if (AI->getIdentifier()) {
12304 CheckShadow(CurBlock->TheScope, AI);
John McCalldf8b37c2010-03-22 09:20:08 +000012305
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +000012306 PushOnScopeChains(AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +000012307 }
John McCallf7b2fb52010-01-22 00:28:27 +000012308 }
Steve Naroffc540d662008-09-03 18:15:37 +000012309}
12310
12311/// ActOnBlockError - If there is an error parsing a block, this callback
12312/// is invoked to pop the information about the block from the action impl.
12313void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCallf1a3c2a2011-11-11 03:19:12 +000012314 // Leave the expression-evaluation context.
12315 DiscardCleanupsInEvaluationContext();
12316 PopExpressionEvaluationContext();
12317
Steve Naroffc540d662008-09-03 18:15:37 +000012318 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +000012319 PopDeclContext();
Eli Friedman71c80552012-01-05 03:35:19 +000012320 PopFunctionScopeInfo();
Steve Naroffc540d662008-09-03 18:15:37 +000012321}
12322
12323/// ActOnBlockStmtExpr - This is called when the body of a block statement
12324/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +000012325ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +000012326 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +000012327 // If blocks are disabled, emit an error.
12328 if (!LangOpts.Blocks)
Yaxun Liu18e3fd32016-06-14 21:43:01 +000012329 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
Mike Stump11289f42009-09-09 15:08:12 +000012330
John McCallf1a3c2a2011-11-11 03:19:12 +000012331 // Leave the expression-evaluation context.
John McCall85110b42012-03-08 22:00:17 +000012332 if (hasAnyUnrecoverableErrorsInThisFunction())
12333 DiscardCleanupsInEvaluationContext();
Tim Shen4a05bb82016-06-21 20:29:17 +000012334 assert(!Cleanup.exprNeedsCleanups() &&
12335 "cleanups within block not correctly bound!");
John McCallf1a3c2a2011-11-11 03:19:12 +000012336 PopExpressionEvaluationContext();
12337
Douglas Gregor9a28e842010-03-01 23:15:13 +000012338 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Jordan Rosed39e5f12012-07-02 21:19:23 +000012339
12340 if (BSI->HasImplicitReturnType)
12341 deduceClosureReturnType(*BSI);
12342
Steve Naroff1d95e5a2008-10-10 01:28:17 +000012343 PopDeclContext();
12344
Steve Naroffc540d662008-09-03 18:15:37 +000012345 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +000012346 if (!BSI->ReturnType.isNull())
12347 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +000012348
Aaron Ballman9ead1242013-12-19 02:39:40 +000012349 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +000012350 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +000012351
John McCallc63de662011-02-02 13:00:07 +000012352 // Set the captured variables on the block.
Eli Friedman20139d32012-01-11 02:36:31 +000012353 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12354 SmallVector<BlockDecl::Capture, 4> Captures;
Craig Topperdfe29ae2015-12-21 06:35:56 +000012355 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
Eli Friedman20139d32012-01-11 02:36:31 +000012356 if (Cap.isThisCapture())
12357 continue;
Eli Friedman24af8502012-02-03 22:47:37 +000012358 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Richard Smithba71c082013-05-16 06:20:58 +000012359 Cap.isNested(), Cap.getInitExpr());
Eli Friedman20139d32012-01-11 02:36:31 +000012360 Captures.push_back(NewCap);
12361 }
Benjamin Kramerb40e4af2015-08-05 09:40:35 +000012362 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
John McCallc63de662011-02-02 13:00:07 +000012363
John McCall8e346702010-06-04 19:02:56 +000012364 // If the user wrote a function type in some form, try to use that.
12365 if (!BSI->FunctionType.isNull()) {
12366 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12367
12368 FunctionType::ExtInfo Ext = FTy->getExtInfo();
12369 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12370
12371 // Turn protoless block types into nullary block types.
12372 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +000012373 FunctionProtoType::ExtProtoInfo EPI;
12374 EPI.ExtInfo = Ext;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012375 BlockTy = Context.getFunctionType(RetTy, None, EPI);
John McCall8e346702010-06-04 19:02:56 +000012376
12377 // Otherwise, if we don't need to change anything about the function type,
12378 // preserve its sugar structure.
Alp Toker314cc812014-01-25 16:55:45 +000012379 } else if (FTy->getReturnType() == RetTy &&
John McCall8e346702010-06-04 19:02:56 +000012380 (!NoReturn || FTy->getNoReturnAttr())) {
12381 BlockTy = BSI->FunctionType;
12382
12383 // Otherwise, make the minimal modifications to the function type.
12384 } else {
12385 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +000012386 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12387 EPI.TypeQuals = 0; // FIXME: silently?
12388 EPI.ExtInfo = Ext;
Alp Toker9cacbab2014-01-20 20:26:09 +000012389 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
John McCall8e346702010-06-04 19:02:56 +000012390 }
12391
12392 // If we don't have a function type, just build one from nothing.
12393 } else {
John McCalldb40c7f2010-12-14 08:05:40 +000012394 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +000012395 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012396 BlockTy = Context.getFunctionType(RetTy, None, EPI);
John McCall8e346702010-06-04 19:02:56 +000012397 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000012398
David Majnemer59f77922016-06-24 04:05:48 +000012399 DiagnoseUnusedParameters(BSI->TheDecl->parameters());
Steve Naroffc540d662008-09-03 18:15:37 +000012400 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +000012401
Chris Lattner45542ea2009-04-19 05:28:12 +000012402 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +000012403 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor5d944db2012-08-17 05:12:08 +000012404 !PP.isCodeCompletionEnabled())
John McCallb268a282010-08-23 23:25:46 +000012405 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +000012406
Chris Lattner60f84492011-02-17 23:58:47 +000012407 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000012408
Jordan Rosed39e5f12012-07-02 21:19:23 +000012409 // Try to apply the named return value optimization. We have to check again
12410 // if we can do this, though, because blocks keep return statements around
12411 // to deduce an implicit return type.
12412 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12413 !BSI->TheDecl->isDependentContext())
Argyrios Kyrtzidisea75aad2014-04-26 18:29:13 +000012414 computeNRVO(Body, BSI);
Douglas Gregor49695f02011-09-06 20:46:03 +000012415
Benjamin Kramera4fb8362011-07-12 14:11:05 +000012416 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
David Blaikie43472b32013-09-03 21:40:15 +000012417 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedman71c80552012-01-05 03:35:19 +000012418 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramera4fb8362011-07-12 14:11:05 +000012419
John McCall28fc7092011-11-10 05:35:25 +000012420 // If the block isn't obviously global, i.e. it captures anything at
John McCalld2393872012-04-13 01:08:17 +000012421 // all, then we need to do a few things in the surrounding context:
John McCall28fc7092011-11-10 05:35:25 +000012422 if (Result->getBlockDecl()->hasCaptures()) {
John McCalld2393872012-04-13 01:08:17 +000012423 // First, this expression has a new cleanup object.
John McCall28fc7092011-11-10 05:35:25 +000012424 ExprCleanupObjects.push_back(Result->getBlockDecl());
Tim Shen4a05bb82016-06-21 20:29:17 +000012425 Cleanup.setExprNeedsCleanups(true);
John McCalld2393872012-04-13 01:08:17 +000012426
12427 // It also gets a branch-protected scope if any of the captured
12428 // variables needs destruction.
Aaron Ballman9371dd22014-03-14 18:34:04 +000012429 for (const auto &CI : Result->getBlockDecl()->captures()) {
12430 const VarDecl *var = CI.getVariable();
John McCalld2393872012-04-13 01:08:17 +000012431 if (var->getType().isDestructedType() != QualType::DK_none) {
12432 getCurFunction()->setHasBranchProtectedScope();
12433 break;
12434 }
12435 }
John McCall28fc7092011-11-10 05:35:25 +000012436 }
Fariborz Jahanian197c68c2012-03-06 18:41:35 +000012437
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012438 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +000012439}
12440
Justin Lebar6644e362016-01-20 00:27:00 +000012441ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12442 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +000012443 TypeSourceInfo *TInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +000012444 GetTypeFromParser(Ty, &TInfo);
12445 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +000012446}
12447
John McCalldadc5752010-08-24 06:29:42 +000012448ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +000012449 Expr *E, TypeSourceInfo *TInfo,
12450 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +000012451 Expr *OrigExpr = E;
Charles Davisc7d5c942015-09-17 20:55:33 +000012452 bool IsMS = false;
12453
Justin Lebar6644e362016-01-20 00:27:00 +000012454 // CUDA device code does not support varargs.
12455 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12456 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12457 CUDAFunctionTarget T = IdentifyCUDATarget(F);
12458 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12459 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12460 }
12461 }
12462
Charles Davisc7d5c942015-09-17 20:55:33 +000012463 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12464 // as Microsoft ABI on an actual Microsoft platform, where
12465 // __builtin_ms_va_list and __builtin_va_list are the same.)
12466 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12467 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12468 QualType MSVaListType = Context.getBuiltinMSVaListType();
12469 if (Context.hasSameType(MSVaListType, E->getType())) {
12470 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12471 return ExprError();
12472 IsMS = true;
12473 }
12474 }
Mike Stump11289f42009-09-09 15:08:12 +000012475
Eli Friedman121ba0c2008-08-09 23:32:40 +000012476 // Get the va_list type
12477 QualType VaListType = Context.getBuiltinVaListType();
Charles Davisc7d5c942015-09-17 20:55:33 +000012478 if (!IsMS) {
12479 if (VaListType->isArrayType()) {
12480 // Deal with implicit array decay; for example, on x86-64,
12481 // va_list is an array, but it's supposed to decay to
12482 // a pointer for va_arg.
12483 VaListType = Context.getArrayDecayedType(VaListType);
12484 // Make sure the input expression also decays appropriately.
12485 ExprResult Result = UsualUnaryConversions(E);
12486 if (Result.isInvalid())
12487 return ExprError();
12488 E = Result.get();
12489 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12490 // If va_list is a record type and we are compiling in C++ mode,
12491 // check the argument using reference binding.
12492 InitializedEntity Entity = InitializedEntity::InitializeParameter(
12493 Context, Context.getLValueReferenceType(VaListType), false);
12494 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12495 if (Init.isInvalid())
12496 return ExprError();
12497 E = Init.getAs<Expr>();
12498 } else {
12499 // Otherwise, the va_list argument must be an l-value because
12500 // it is modified by va_arg.
12501 if (!E->isTypeDependent() &&
12502 CheckForModifiableLvalue(E, BuiltinLoc, *this))
12503 return ExprError();
12504 }
Eli Friedmane2cad652009-05-16 12:46:54 +000012505 }
Eli Friedman121ba0c2008-08-09 23:32:40 +000012506
Charles Davisc7d5c942015-09-17 20:55:33 +000012507 if (!IsMS && !E->isTypeDependent() &&
12508 !Context.hasSameType(VaListType, E->getType()))
Sebastian Redl6d4256c2009-03-15 17:47:39 +000012509 return ExprError(Diag(E->getLocStart(),
12510 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +000012511 << OrigExpr->getType() << E->getSourceRange());
Mike Stump4e1f26a2009-02-19 03:04:26 +000012512
David Majnemerc75d1a12011-06-14 05:17:32 +000012513 if (!TInfo->getType()->isDependentType()) {
12514 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012515 diag::err_second_parameter_to_va_arg_incomplete,
12516 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +000012517 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +000012518
David Majnemerc75d1a12011-06-14 05:17:32 +000012519 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregorae298422012-05-04 17:09:59 +000012520 TInfo->getType(),
12521 diag::err_second_parameter_to_va_arg_abstract,
12522 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +000012523 return ExprError();
12524
Douglas Gregor7e1eb932011-07-30 06:45:27 +000012525 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +000012526 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +000012527 TInfo->getType()->isObjCLifetimeType()
12528 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12529 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +000012530 << TInfo->getType()
12531 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +000012532 }
Eli Friedman6290ae42011-07-11 21:45:59 +000012533
12534 // Check for va_arg where arguments of the given type will be promoted
12535 // (i.e. this va_arg is guaranteed to have undefined behavior).
12536 QualType PromoteType;
12537 if (TInfo->getType()->isPromotableIntegerType()) {
12538 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12539 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12540 PromoteType = QualType();
12541 }
12542 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12543 PromoteType = Context.DoubleTy;
12544 if (!PromoteType.isNull())
Ted Kremeneka0461692013-01-08 01:50:40 +000012545 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12546 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12547 << TInfo->getType()
12548 << PromoteType
12549 << TInfo->getTypeLoc().getSourceRange());
David Majnemerc75d1a12011-06-14 05:17:32 +000012550 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000012551
Abramo Bagnara27db2392010-08-10 10:06:15 +000012552 QualType T = TInfo->getType().getNonLValueExprType(Context);
Charles Davisc7d5c942015-09-17 20:55:33 +000012553 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
Anders Carlsson7e13ab82007-10-15 20:28:48 +000012554}
12555
John McCalldadc5752010-08-24 06:29:42 +000012556ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +000012557 // The type of __null will be int or long, depending on the size of
12558 // pointers on the target.
12559 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +000012560 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12561 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +000012562 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +000012563 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +000012564 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +000012565 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +000012566 Ty = Context.LongLongTy;
12567 else {
David Blaikie83d382b2011-09-23 05:06:16 +000012568 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +000012569 }
Douglas Gregor3be4b122008-11-29 04:51:27 +000012570
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012571 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregor3be4b122008-11-29 04:51:27 +000012572}
12573
George Burgess IV60bc9722016-01-13 23:36:34 +000012574bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12575 bool Diagnose) {
Fariborz Jahanianbd714e92013-12-17 19:33:43 +000012576 if (!getLangOpts().ObjC1)
Fariborz Jahanian283bf892013-12-18 21:04:43 +000012577 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000012578
Anders Carlssonace5d072009-11-10 04:46:30 +000012579 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12580 if (!PT)
Fariborz Jahanian283bf892013-12-18 21:04:43 +000012581 return false;
Anders Carlssonace5d072009-11-10 04:46:30 +000012582
Anders Carlssonace5d072009-11-10 04:46:30 +000012583 if (!PT->isObjCIdType()) {
12584 // Check if the destination is the 'NSString' interface.
12585 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12586 if (!ID || !ID->getIdentifier()->isStr("NSString"))
Fariborz Jahanian283bf892013-12-18 21:04:43 +000012587 return false;
Anders Carlssonace5d072009-11-10 04:46:30 +000012588 }
Fariborz Jahanian283bf892013-12-18 21:04:43 +000012589
John McCallfe96e0b2011-11-06 09:01:30 +000012590 // Ignore any parens, implicit casts (should only be
12591 // array-to-pointer decays), and not-so-opaque values. The last is
12592 // important for making this trigger for property assignments.
Fariborz Jahanian283bf892013-12-18 21:04:43 +000012593 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
John McCallfe96e0b2011-11-06 09:01:30 +000012594 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12595 if (OV->getSourceExpr())
12596 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12597
12598 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregorfb65e592011-07-27 05:40:30 +000012599 if (!SL || !SL->isAscii())
Fariborz Jahanian283bf892013-12-18 21:04:43 +000012600 return false;
Bob Wilsonf5c53b82016-02-13 01:41:41 +000012601 if (Diagnose) {
George Burgess IV60bc9722016-01-13 23:36:34 +000012602 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12603 << FixItHint::CreateInsertion(SL->getLocStart(), "@");
Bob Wilsonf5c53b82016-02-13 01:41:41 +000012604 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12605 }
Fariborz Jahanian283bf892013-12-18 21:04:43 +000012606 return true;
Anders Carlssonace5d072009-11-10 04:46:30 +000012607}
12608
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000012609static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12610 const Expr *SrcExpr) {
12611 if (!DstType->isFunctionPointerType() ||
12612 !SrcExpr->getType()->isFunctionType())
12613 return false;
12614
12615 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12616 if (!DRE)
12617 return false;
12618
12619 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12620 if (!FD)
12621 return false;
12622
12623 return !S.checkAddressOfFunctionIsAvailable(FD,
12624 /*Complain=*/true,
12625 SrcExpr->getLocStart());
12626}
12627
Chris Lattner9bad62c2008-01-04 18:04:52 +000012628bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12629 SourceLocation Loc,
12630 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +000012631 Expr *SrcExpr, AssignmentAction Action,
12632 bool *Complained) {
12633 if (Complained)
12634 *Complained = false;
12635
Chris Lattner9bad62c2008-01-04 18:04:52 +000012636 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +000012637 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +000012638 bool isInvalid = false;
Eli Friedman381f4312012-02-29 20:59:56 +000012639 unsigned DiagKind = 0;
Douglas Gregora771f462010-03-31 17:46:05 +000012640 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +000012641 ConversionFixItGenerator ConvHints;
12642 bool MayHaveConvFixit = false;
Richard Trieucaff2472011-11-23 22:32:32 +000012643 bool MayHaveFunctionDiff = false;
Fariborz Jahaniand3296742014-06-19 23:05:46 +000012644 const ObjCInterfaceDecl *IFace = nullptr;
12645 const ObjCProtocolDecl *PDecl = nullptr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000012646
Chris Lattner9bad62c2008-01-04 18:04:52 +000012647 switch (ConvTy) {
Fariborz Jahanian268fec12012-07-17 18:00:08 +000012648 case Compatible:
Joerg Sonnenberger05bd2da2013-11-19 13:38:38 +000012649 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12650 return false;
Fariborz Jahanian268fec12012-07-17 18:00:08 +000012651
Chris Lattner940cfeb2008-01-04 18:22:42 +000012652 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +000012653 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +000012654 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12655 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +000012656 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +000012657 case IntToPointer:
12658 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +000012659 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12660 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +000012661 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +000012662 case IncompatiblePointer:
Bruno Cardoso Lopesd9b7dfe2016-07-18 20:37:06 +000012663 if (Action == AA_Passing_CFAudited)
12664 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
12665 else if (SrcType->isFunctionPointerType() &&
12666 DstType->isFunctionPointerType())
12667 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
12668 else
12669 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
12670
Douglas Gregor33823722011-06-11 01:09:30 +000012671 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12672 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +000012673 if (Hint.isNull() && !CheckInferredResultType) {
12674 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12675 }
Fariborz Jahanian3beec202013-04-30 00:30:48 +000012676 else if (CheckInferredResultType) {
12677 SrcType = SrcType.getUnqualifiedType();
12678 DstType = DstType.getUnqualifiedType();
12679 }
Anna Zaks3b402712011-07-28 19:51:27 +000012680 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +000012681 break;
Eli Friedman80160bd2009-03-22 23:59:44 +000012682 case IncompatiblePointerSign:
12683 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12684 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +000012685 case FunctionVoidPointer:
12686 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12687 break;
John McCall4fff8f62011-02-01 00:10:29 +000012688 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +000012689 // Perform array-to-pointer decay if necessary.
12690 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12691
John McCall4fff8f62011-02-01 00:10:29 +000012692 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12693 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12694 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12695 DiagKind = diag::err_typecheck_incompatible_address_space;
12696 break;
John McCall31168b02011-06-15 23:02:42 +000012697
12698
12699 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +000012700 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +000012701 break;
John McCall4fff8f62011-02-01 00:10:29 +000012702 }
12703
12704 llvm_unreachable("unknown error case for discarding qualifiers!");
12705 // fallthrough
12706 }
Chris Lattner9bad62c2008-01-04 18:04:52 +000012707 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +000012708 // If the qualifiers lost were because we were applying the
12709 // (deprecated) C++ conversion from a string literal to a char*
12710 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
12711 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +000012712 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +000012713 // bit of refactoring (so that the second argument is an
12714 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +000012715 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +000012716 // C++ semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012717 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +000012718 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12719 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +000012720 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12721 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +000012722 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +000012723 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +000012724 break;
Steve Naroff081c7422008-09-04 15:10:53 +000012725 case IntToBlockPointer:
12726 DiagKind = diag::err_int_to_block_pointer;
12727 break;
12728 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +000012729 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +000012730 break;
Fariborz Jahaniand3296742014-06-19 23:05:46 +000012731 case IncompatibleObjCQualifiedId: {
12732 if (SrcType->isObjCQualifiedIdType()) {
12733 const ObjCObjectPointerType *srcOPT =
12734 SrcType->getAs<ObjCObjectPointerType>();
12735 for (auto *srcProto : srcOPT->quals()) {
12736 PDecl = srcProto;
12737 break;
12738 }
12739 if (const ObjCInterfaceType *IFaceT =
12740 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12741 IFace = IFaceT->getDecl();
12742 }
12743 else if (DstType->isObjCQualifiedIdType()) {
12744 const ObjCObjectPointerType *dstOPT =
12745 DstType->getAs<ObjCObjectPointerType>();
12746 for (auto *dstProto : dstOPT->quals()) {
12747 PDecl = dstProto;
12748 break;
12749 }
12750 if (const ObjCInterfaceType *IFaceT =
12751 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12752 IFace = IFaceT->getDecl();
12753 }
Steve Naroff8afa9892008-10-14 22:18:38 +000012754 DiagKind = diag::warn_incompatible_qualified_id;
12755 break;
Fariborz Jahaniand3296742014-06-19 23:05:46 +000012756 }
Anders Carlssondb5a9b62009-01-30 23:17:46 +000012757 case IncompatibleVectors:
12758 DiagKind = diag::warn_incompatible_vectors;
12759 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +000012760 case IncompatibleObjCWeakRef:
12761 DiagKind = diag::err_arc_weak_unavailable_assign;
12762 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +000012763 case Incompatible:
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000012764 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12765 if (Complained)
12766 *Complained = true;
12767 return true;
12768 }
12769
Chris Lattner9bad62c2008-01-04 18:04:52 +000012770 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +000012771 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12772 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +000012773 isInvalid = true;
Richard Trieucaff2472011-11-23 22:32:32 +000012774 MayHaveFunctionDiff = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +000012775 break;
12776 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000012777
Douglas Gregorc68e1402010-04-09 00:35:39 +000012778 QualType FirstType, SecondType;
12779 switch (Action) {
12780 case AA_Assigning:
12781 case AA_Initializing:
12782 // The destination type comes first.
12783 FirstType = DstType;
12784 SecondType = SrcType;
12785 break;
Alexis Huntc46382e2010-04-28 23:02:27 +000012786
Douglas Gregorc68e1402010-04-09 00:35:39 +000012787 case AA_Returning:
12788 case AA_Passing:
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +000012789 case AA_Passing_CFAudited:
Douglas Gregorc68e1402010-04-09 00:35:39 +000012790 case AA_Converting:
12791 case AA_Sending:
12792 case AA_Casting:
12793 // The source type comes first.
12794 FirstType = SrcType;
12795 SecondType = DstType;
12796 break;
12797 }
Alexis Huntc46382e2010-04-28 23:02:27 +000012798
Anna Zaks3b402712011-07-28 19:51:27 +000012799 PartialDiagnostic FDiag = PDiag(DiagKind);
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +000012800 if (Action == AA_Passing_CFAudited)
Fariborz Jahanian68e18672014-09-10 18:23:34 +000012801 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +000012802 else
12803 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
Anna Zaks3b402712011-07-28 19:51:27 +000012804
12805 // If we can fix the conversion, suggest the FixIts.
12806 assert(ConvHints.isNull() || Hint.isNull());
12807 if (!ConvHints.isNull()) {
Craig Topperdfe29ae2015-12-21 06:35:56 +000012808 for (FixItHint &H : ConvHints.Hints)
12809 FDiag << H;
Anna Zaks3b402712011-07-28 19:51:27 +000012810 } else {
12811 FDiag << Hint;
12812 }
12813 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12814
Richard Trieucaff2472011-11-23 22:32:32 +000012815 if (MayHaveFunctionDiff)
12816 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12817
Anna Zaks3b402712011-07-28 19:51:27 +000012818 Diag(Loc, FDiag);
Fariborz Jahaniand3296742014-06-19 23:05:46 +000012819 if (DiagKind == diag::warn_incompatible_qualified_id &&
12820 PDecl && IFace && !IFace->hasDefinition())
Richard Smith01d96982016-12-02 23:00:28 +000012821 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
Fariborz Jahaniand3296742014-06-19 23:05:46 +000012822 << IFace->getName() << PDecl->getName();
12823
Richard Trieucaff2472011-11-23 22:32:32 +000012824 if (SecondType == Context.OverloadTy)
12825 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
George Burgess IV5f21c712015-10-12 19:57:04 +000012826 FirstType, /*TakingAddress=*/true);
Richard Trieucaff2472011-11-23 22:32:32 +000012827
Douglas Gregor33823722011-06-11 01:09:30 +000012828 if (CheckInferredResultType)
12829 EmitRelatedResultTypeNote(SrcExpr);
John McCall5ec7e7d2013-03-19 07:04:25 +000012830
12831 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12832 EmitRelatedResultTypeNoteForReturn(DstType);
Douglas Gregor33823722011-06-11 01:09:30 +000012833
Douglas Gregor4f4946a2010-04-22 00:20:18 +000012834 if (Complained)
12835 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +000012836 return isInvalid;
12837}
Anders Carlssone54e8a12008-11-30 19:50:32 +000012838
Richard Smithf4c51d92012-02-04 09:53:13 +000012839ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12840 llvm::APSInt *Result) {
Douglas Gregore2b37442012-05-04 22:38:52 +000012841 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12842 public:
Craig Toppere14c0f82014-03-12 04:55:44 +000012843 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +000012844 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12845 }
12846 } Diagnoser;
12847
12848 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12849}
12850
12851ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12852 llvm::APSInt *Result,
12853 unsigned DiagID,
12854 bool AllowFold) {
12855 class IDDiagnoser : public VerifyICEDiagnoser {
12856 unsigned DiagID;
12857
12858 public:
12859 IDDiagnoser(unsigned DiagID)
12860 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12861
Craig Toppere14c0f82014-03-12 04:55:44 +000012862 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +000012863 S.Diag(Loc, DiagID) << SR;
12864 }
12865 } Diagnoser(DiagID);
12866
12867 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12868}
12869
12870void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12871 SourceRange SR) {
12872 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smithf4c51d92012-02-04 09:53:13 +000012873}
12874
Benjamin Kramer33adaae2012-04-18 14:22:41 +000012875ExprResult
12876Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregore2b37442012-05-04 22:38:52 +000012877 VerifyICEDiagnoser &Diagnoser,
12878 bool AllowFold) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012879 SourceLocation DiagLoc = E->getLocStart();
Richard Smithf4c51d92012-02-04 09:53:13 +000012880
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012881 if (getLangOpts().CPlusPlus11) {
Richard Smithf4c51d92012-02-04 09:53:13 +000012882 // C++11 [expr.const]p5:
12883 // If an expression of literal class type is used in a context where an
12884 // integral constant expression is required, then that class type shall
12885 // have a single non-explicit conversion function to an integral or
12886 // unscoped enumeration type
12887 ExprResult Converted;
Richard Smithccc11812013-05-21 19:05:48 +000012888 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12889 public:
12890 CXX11ConvertDiagnoser(bool Silent)
12891 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12892 Silent, true) {}
Douglas Gregore2b37442012-05-04 22:38:52 +000012893
Craig Toppere14c0f82014-03-12 04:55:44 +000012894 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12895 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +000012896 return S.Diag(Loc, diag::err_ice_not_integral) << T;
12897 }
12898
Craig Toppere14c0f82014-03-12 04:55:44 +000012899 SemaDiagnosticBuilder diagnoseIncomplete(
12900 Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +000012901 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12902 }
12903
Craig Toppere14c0f82014-03-12 04:55:44 +000012904 SemaDiagnosticBuilder diagnoseExplicitConv(
12905 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +000012906 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12907 }
12908
Craig Toppere14c0f82014-03-12 04:55:44 +000012909 SemaDiagnosticBuilder noteExplicitConv(
12910 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +000012911 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12912 << ConvTy->isEnumeralType() << ConvTy;
12913 }
12914
Craig Toppere14c0f82014-03-12 04:55:44 +000012915 SemaDiagnosticBuilder diagnoseAmbiguous(
12916 Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +000012917 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
12918 }
12919
Craig Toppere14c0f82014-03-12 04:55:44 +000012920 SemaDiagnosticBuilder noteAmbiguous(
12921 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +000012922 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12923 << ConvTy->isEnumeralType() << ConvTy;
12924 }
12925
Craig Toppere14c0f82014-03-12 04:55:44 +000012926 SemaDiagnosticBuilder diagnoseConversion(
12927 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +000012928 llvm_unreachable("conversion functions are permitted");
12929 }
12930 } ConvertDiagnoser(Diagnoser.Suppress);
12931
12932 Converted = PerformContextualImplicitConversion(DiagLoc, E,
12933 ConvertDiagnoser);
Richard Smithf4c51d92012-02-04 09:53:13 +000012934 if (Converted.isInvalid())
12935 return Converted;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012936 E = Converted.get();
Richard Smithf4c51d92012-02-04 09:53:13 +000012937 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
12938 return ExprError();
12939 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12940 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregore2b37442012-05-04 22:38:52 +000012941 if (!Diagnoser.Suppress)
12942 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithf4c51d92012-02-04 09:53:13 +000012943 return ExprError();
12944 }
12945
Richard Smith902ca212011-12-14 23:32:26 +000012946 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
12947 // in the non-ICE case.
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012948 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
Richard Smithf4c51d92012-02-04 09:53:13 +000012949 if (Result)
12950 *Result = E->EvaluateKnownConstInt(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012951 return E;
Eli Friedmanbb967cc2009-04-25 22:26:58 +000012952 }
12953
Anders Carlssone54e8a12008-11-30 19:50:32 +000012954 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012955 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith92b1ce02011-12-12 09:28:41 +000012956 EvalResult.Diag = &Notes;
Anders Carlssone54e8a12008-11-30 19:50:32 +000012957
Richard Smith902ca212011-12-14 23:32:26 +000012958 // Try to evaluate the expression, and produce diagnostics explaining why it's
12959 // not a constant expression as a side-effect.
12960 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
12961 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
12962
12963 // In C++11, we can rely on diagnostics being produced for any expression
12964 // which is not a constant expression. If no diagnostics were produced, then
12965 // this is a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012966 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
Richard Smith902ca212011-12-14 23:32:26 +000012967 if (Result)
12968 *Result = EvalResult.Val.getInt();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012969 return E;
Richard Smithf4c51d92012-02-04 09:53:13 +000012970 }
12971
12972 // If our only note is the usual "invalid subexpression" note, just point
12973 // the caret at its location rather than producing an essentially
12974 // redundant note.
12975 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12976 diag::note_invalid_subexpr_in_const_expr) {
12977 DiagLoc = Notes[0].first;
12978 Notes.clear();
Richard Smith902ca212011-12-14 23:32:26 +000012979 }
12980
12981 if (!Folded || !AllowFold) {
Douglas Gregore2b37442012-05-04 22:38:52 +000012982 if (!Diagnoser.Suppress) {
12983 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Craig Topperdfe29ae2015-12-21 06:35:56 +000012984 for (const PartialDiagnosticAt &Note : Notes)
12985 Diag(Note.first, Note.second);
Anders Carlssone54e8a12008-11-30 19:50:32 +000012986 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000012987
Richard Smithf4c51d92012-02-04 09:53:13 +000012988 return ExprError();
Anders Carlssone54e8a12008-11-30 19:50:32 +000012989 }
12990
Douglas Gregore2b37442012-05-04 22:38:52 +000012991 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Craig Topperdfe29ae2015-12-21 06:35:56 +000012992 for (const PartialDiagnosticAt &Note : Notes)
12993 Diag(Note.first, Note.second);
Mike Stump4e1f26a2009-02-19 03:04:26 +000012994
Anders Carlssone54e8a12008-11-30 19:50:32 +000012995 if (Result)
12996 *Result = EvalResult.Val.getInt();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012997 return E;
Anders Carlssone54e8a12008-11-30 19:50:32 +000012998}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000012999
Eli Friedman456f0182012-01-20 01:26:23 +000013000namespace {
13001 // Handle the case where we conclude a expression which we speculatively
13002 // considered to be unevaluated is actually evaluated.
13003 class TransformToPE : public TreeTransform<TransformToPE> {
13004 typedef TreeTransform<TransformToPE> BaseTransform;
13005
13006 public:
13007 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
13008
13009 // Make sure we redo semantic analysis
13010 bool AlwaysRebuild() { return true; }
13011
Eli Friedman5f0ca242012-02-06 23:29:57 +000013012 // Make sure we handle LabelStmts correctly.
13013 // FIXME: This does the right thing, but maybe we need a more general
13014 // fix to TreeTransform?
13015 StmtResult TransformLabelStmt(LabelStmt *S) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013016 S->getDecl()->setStmt(nullptr);
Eli Friedman5f0ca242012-02-06 23:29:57 +000013017 return BaseTransform::TransformLabelStmt(S);
13018 }
13019
Eli Friedman456f0182012-01-20 01:26:23 +000013020 // We need to special-case DeclRefExprs referring to FieldDecls which
13021 // are not part of a member pointer formation; normal TreeTransforming
13022 // doesn't catch this case because of the way we represent them in the AST.
13023 // FIXME: This is a bit ugly; is it really the best way to handle this
13024 // case?
13025 //
13026 // Error on DeclRefExprs referring to FieldDecls.
13027 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
13028 if (isa<FieldDecl>(E->getDecl()) &&
David Blaikie131fcb42012-08-06 22:47:24 +000013029 !SemaRef.isUnevaluatedContext())
Eli Friedman456f0182012-01-20 01:26:23 +000013030 return SemaRef.Diag(E->getLocation(),
13031 diag::err_invalid_non_static_member_use)
13032 << E->getDecl() << E->getSourceRange();
13033
13034 return BaseTransform::TransformDeclRefExpr(E);
13035 }
13036
13037 // Exception: filter out member pointer formation
13038 ExprResult TransformUnaryOperator(UnaryOperator *E) {
13039 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
13040 return E;
13041
13042 return BaseTransform::TransformUnaryOperator(E);
13043 }
13044
Douglas Gregor89625492012-02-09 08:14:43 +000013045 ExprResult TransformLambdaExpr(LambdaExpr *E) {
13046 // Lambdas never need to be transformed.
13047 return E;
13048 }
Eli Friedman456f0182012-01-20 01:26:23 +000013049 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000013050}
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000013051
Benjamin Kramerd81108f2012-11-14 15:08:31 +000013052ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
John McCallf413f5e2013-05-03 00:10:13 +000013053 assert(isUnevaluatedContext() &&
Eli Friedmane4f22df2012-02-29 04:03:55 +000013054 "Should only transform unevaluated expressions");
Eli Friedman456f0182012-01-20 01:26:23 +000013055 ExprEvalContexts.back().Context =
13056 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
John McCallf413f5e2013-05-03 00:10:13 +000013057 if (isUnevaluatedContext())
Eli Friedman456f0182012-01-20 01:26:23 +000013058 return E;
13059 return TransformToPE(*this).TransformExpr(E);
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000013060}
13061
Douglas Gregorff790f12009-11-26 00:44:06 +000013062void
Douglas Gregor7fcbd902012-02-21 00:37:24 +000013063Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smithfd555f62012-02-22 02:04:18 +000013064 Decl *LambdaContextDecl,
13065 bool IsDecltype) {
Tim Shen4a05bb82016-06-21 20:29:17 +000013066 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
13067 LambdaContextDecl, IsDecltype);
13068 Cleanup.reset();
Eli Friedman3bda6b12012-02-02 23:15:15 +000013069 if (!MaybeODRUseExprs.empty())
13070 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +000013071}
13072
Eli Friedman15681d62012-09-26 04:34:21 +000013073void
13074Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13075 ReuseLambdaContextDecl_t,
13076 bool IsDecltype) {
Eli Friedman7e346a82013-07-01 20:22:57 +000013077 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
13078 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
Eli Friedman15681d62012-09-26 04:34:21 +000013079}
13080
Richard Trieucfc491d2011-08-02 04:35:43 +000013081void Sema::PopExpressionEvaluationContext() {
Eli Friedmanfa0df832012-02-02 03:46:19 +000013082 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Kaelyn Takata6c759512014-10-27 18:07:37 +000013083 unsigned NumTypos = Rec.NumTypos;
Douglas Gregor0b6a6242009-06-22 20:57:11 +000013084
Douglas Gregor89625492012-02-09 08:14:43 +000013085 if (!Rec.Lambdas.empty()) {
David Majnemer9adc3612013-10-25 09:12:52 +000013086 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
13087 unsigned D;
13088 if (Rec.isUnevaluated()) {
13089 // C++11 [expr.prim.lambda]p2:
13090 // A lambda-expression shall not appear in an unevaluated operand
13091 // (Clause 5).
13092 D = diag::err_lambda_unevaluated_operand;
13093 } else {
13094 // C++1y [expr.const]p2:
13095 // A conditional-expression e is a core constant expression unless the
13096 // evaluation of e, following the rules of the abstract machine, would
13097 // evaluate [...] a lambda-expression.
13098 D = diag::err_lambda_in_constant_expression;
13099 }
Aaron Ballmanae2144e2014-10-16 17:53:07 +000013100 for (const auto *L : Rec.Lambdas)
13101 Diag(L->getLocStart(), D);
Douglas Gregor89625492012-02-09 08:14:43 +000013102 } else {
13103 // Mark the capture expressions odr-used. This was deferred
13104 // during lambda expression creation.
Aaron Ballmanae2144e2014-10-16 17:53:07 +000013105 for (auto *Lambda : Rec.Lambdas) {
13106 for (auto *C : Lambda->capture_inits())
13107 MarkDeclarationsReferencedInExpr(C);
Douglas Gregor89625492012-02-09 08:14:43 +000013108 }
13109 }
13110 }
13111
Douglas Gregorff790f12009-11-26 00:44:06 +000013112 // When are coming out of an unevaluated context, clear out any
13113 // temporaries that we may have created as part of the evaluation of
13114 // the expression in that context: they aren't relevant because they
13115 // will never be constructed.
John McCallf413f5e2013-05-03 00:10:13 +000013116 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
John McCall28fc7092011-11-10 05:35:25 +000013117 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13118 ExprCleanupObjects.end());
Tim Shen4a05bb82016-06-21 20:29:17 +000013119 Cleanup = Rec.ParentCleanup;
Eli Friedman3bda6b12012-02-02 23:15:15 +000013120 CleanupVarDeclMarking();
13121 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCall31168b02011-06-15 23:02:42 +000013122 // Otherwise, merge the contexts together.
13123 } else {
Tim Shen4a05bb82016-06-21 20:29:17 +000013124 Cleanup.mergeFrom(Rec.ParentCleanup);
Eli Friedman3bda6b12012-02-02 23:15:15 +000013125 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13126 Rec.SavedMaybeODRUseExprs.end());
John McCall31168b02011-06-15 23:02:42 +000013127 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000013128
13129 // Pop the current expression evaluation context off the stack.
13130 ExprEvalContexts.pop_back();
Kaelyn Takata6c759512014-10-27 18:07:37 +000013131
13132 if (!ExprEvalContexts.empty())
13133 ExprEvalContexts.back().NumTypos += NumTypos;
13134 else
13135 assert(NumTypos == 0 && "There are outstanding typos after popping the "
13136 "last ExpressionEvaluationContextRecord");
Douglas Gregor0b6a6242009-06-22 20:57:11 +000013137}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000013138
John McCall31168b02011-06-15 23:02:42 +000013139void Sema::DiscardCleanupsInEvaluationContext() {
John McCall28fc7092011-11-10 05:35:25 +000013140 ExprCleanupObjects.erase(
13141 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13142 ExprCleanupObjects.end());
Tim Shen4a05bb82016-06-21 20:29:17 +000013143 Cleanup.reset();
Eli Friedman3bda6b12012-02-02 23:15:15 +000013144 MaybeODRUseExprs.clear();
John McCall31168b02011-06-15 23:02:42 +000013145}
13146
Eli Friedmane0afc982012-01-21 01:01:51 +000013147ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13148 if (!E->getType()->isVariablyModifiedType())
13149 return E;
Benjamin Kramerd81108f2012-11-14 15:08:31 +000013150 return TransformToPotentiallyEvaluated(E);
Eli Friedmane0afc982012-01-21 01:01:51 +000013151}
13152
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +000013153static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000013154 // Do not mark anything as "used" within a dependent context; wait for
13155 // an instantiation.
Eli Friedmanfa0df832012-02-02 03:46:19 +000013156 if (SemaRef.CurContext->isDependentContext())
13157 return false;
Mike Stump11289f42009-09-09 15:08:12 +000013158
Eli Friedmanfa0df832012-02-02 03:46:19 +000013159 switch (SemaRef.ExprEvalContexts.back().Context) {
13160 case Sema::Unevaluated:
John McCallf413f5e2013-05-03 00:10:13 +000013161 case Sema::UnevaluatedAbstract:
Douglas Gregor0b6a6242009-06-22 20:57:11 +000013162 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman02b58512012-01-21 04:44:06 +000013163 // (Depending on how you read the standard, we actually do need to do
13164 // something here for null pointer constants, but the standard's
13165 // definition of a null pointer constant is completely crazy.)
Eli Friedmanfa0df832012-02-02 03:46:19 +000013166 return false;
Mike Stump11289f42009-09-09 15:08:12 +000013167
Richard Smithb130fe72016-06-23 19:16:49 +000013168 case Sema::DiscardedStatement:
13169 // These are technically a potentially evaluated but they have the effect
13170 // of suppressing use marking.
13171 return false;
13172
Eli Friedmanfa0df832012-02-02 03:46:19 +000013173 case Sema::ConstantEvaluated:
13174 case Sema::PotentiallyEvaluated:
Eli Friedman02b58512012-01-21 04:44:06 +000013175 // We are in a potentially evaluated expression (or a constant-expression
13176 // in C++03); we need to do implicit template instantiation, implicitly
13177 // define class members, and mark most declarations as used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000013178 return true;
Mike Stump11289f42009-09-09 15:08:12 +000013179
Eli Friedmanfa0df832012-02-02 03:46:19 +000013180 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000013181 // Referenced declarations will only be used if the construct in the
13182 // containing expression is used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000013183 return false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +000013184 }
Matt Beaumont-Gay248bc722012-02-02 18:35:35 +000013185 llvm_unreachable("Invalid context");
Eli Friedmanfa0df832012-02-02 03:46:19 +000013186}
13187
13188/// \brief Mark a function referenced, and check whether it is odr-used
13189/// (C++ [basic.def.odr]p2, C99 6.9p3)
Nico Weber8bf410f2014-08-27 17:04:39 +000013190void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
Richard Smith0e32c522016-03-25 22:29:27 +000013191 bool MightBeOdrUse) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000013192 assert(Func && "No function?");
13193
13194 Func->setReferenced();
13195
Richard Smithe10d3042012-11-07 01:14:25 +000013196 // C++11 [basic.def.odr]p3:
13197 // A function whose name appears as a potentially-evaluated expression is
13198 // odr-used if it is the unique lookup result or the selected member of a
13199 // set of overloaded functions [...].
13200 //
13201 // We (incorrectly) mark overload resolution as an unevaluated context, so we
Richard Smith6739a102016-05-05 00:56:12 +000013202 // can just check that here.
Richard Smith0e32c522016-03-25 22:29:27 +000013203 bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this);
Richard Smith6739a102016-05-05 00:56:12 +000013204
13205 // Determine whether we require a function definition to exist, per
13206 // C++11 [temp.inst]p3:
13207 // Unless a function template specialization has been explicitly
13208 // instantiated or explicitly specialized, the function template
13209 // specialization is implicitly instantiated when the specialization is
13210 // referenced in a context that requires a function definition to exist.
13211 //
13212 // We consider constexpr function templates to be referenced in a context
13213 // that requires a definition to exist whenever they are referenced.
13214 //
13215 // FIXME: This instantiates constexpr functions too frequently. If this is
13216 // really an unevaluated context (and we're not just in the definition of a
13217 // function template or overload resolution or other cases which we
13218 // incorrectly consider to be unevaluated contexts), and we're not in a
13219 // subexpression which we actually need to evaluate (for instance, a
13220 // template argument, array bound or an expression in a braced-init-list),
13221 // we are not permitted to instantiate this constexpr function definition.
13222 //
13223 // FIXME: This also implicitly defines special members too frequently. They
13224 // are only supposed to be implicitly defined if they are odr-used, but they
13225 // are not odr-used from constant expressions in unevaluated contexts.
13226 // However, they cannot be referenced if they are deleted, and they are
13227 // deleted whenever the implicit definition of the special member would
13228 // fail (with very few exceptions).
13229 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13230 bool NeedDefinition =
13231 OdrUse || (Func->isConstexpr() && (Func->isImplicitlyInstantiable() ||
13232 (MD && !MD->isUserProvided())));
13233
13234 // C++14 [temp.expl.spec]p6:
13235 // If a template [...] is explicitly specialized then that specialization
13236 // shall be declared before the first use of that specialization that would
13237 // cause an implicit instantiation to take place, in every translation unit
13238 // in which such a use occurs
13239 if (NeedDefinition &&
13240 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13241 Func->getMemberSpecializationInfo()))
13242 checkSpecializationVisibility(Loc, Func);
13243
Richard Smith84a0b6d2016-10-18 23:39:12 +000013244 // C++14 [except.spec]p17:
13245 // An exception-specification is considered to be needed when:
13246 // - the function is odr-used or, if it appears in an unevaluated operand,
13247 // would be odr-used if the expression were potentially-evaluated;
13248 //
13249 // Note, we do this even if MightBeOdrUse is false. That indicates that the
13250 // function is a pure virtual function we're calling, and in that case the
13251 // function was selected by overload resolution and we need to resolve its
13252 // exception specification for a different reason.
13253 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13254 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13255 ResolveExceptionSpec(Loc, FPT);
13256
Richard Smith6739a102016-05-05 00:56:12 +000013257 // If we don't need to mark the function as used, and we don't need to
13258 // try to provide a definition, there's nothing more to do.
13259 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13260 (!NeedDefinition || Func->getBody()))
13261 return;
Mike Stump11289f42009-09-09 15:08:12 +000013262
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000013263 // Note that this declaration has been used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000013264 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smithab44d5b2013-12-10 08:25:00 +000013265 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
Richard Smith273c4e92012-02-26 07:51:39 +000013266 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000013267 if (Constructor->isDefaultConstructor()) {
Hans Wennborg853ae942014-05-30 16:59:42 +000013268 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
Sebastian Redl22653ba2011-08-30 19:58:05 +000013269 return;
Richard Smithab44d5b2013-12-10 08:25:00 +000013270 DefineImplicitDefaultConstructor(Loc, Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000013271 } else if (Constructor->isCopyConstructor()) {
Richard Smithab44d5b2013-12-10 08:25:00 +000013272 DefineImplicitCopyConstructor(Loc, Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000013273 } else if (Constructor->isMoveConstructor()) {
Richard Smithab44d5b2013-12-10 08:25:00 +000013274 DefineImplicitMoveConstructor(Loc, Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000013275 }
Richard Smithc2bc61b2013-03-18 21:12:30 +000013276 } else if (Constructor->getInheritedConstructor()) {
Richard Smithab44d5b2013-12-10 08:25:00 +000013277 DefineInheritingConstructor(Loc, Constructor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +000013278 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000013279 } else if (CXXDestructorDecl *Destructor =
13280 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smithab44d5b2013-12-10 08:25:00 +000013281 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
Nico Weber55905142015-03-06 06:01:06 +000013282 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13283 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13284 return;
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000013285 DefineImplicitDestructor(Loc, Destructor);
Nico Weber55905142015-03-06 06:01:06 +000013286 }
Nico Weberb3a99782015-01-26 06:23:36 +000013287 if (Destructor->isVirtual() && getLangOpts().AppleKext)
Douglas Gregor88d292c2010-05-13 16:44:06 +000013288 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +000013289 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smithab44d5b2013-12-10 08:25:00 +000013290 if (MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +000013291 MethodDecl->getOverloadedOperator() == OO_Equal) {
Richard Smithab44d5b2013-12-10 08:25:00 +000013292 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13293 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000013294 if (MethodDecl->isCopyAssignmentOperator())
13295 DefineImplicitCopyAssignment(Loc, MethodDecl);
Erik Pilkington71a7d912016-06-20 20:04:15 +000013296 else if (MethodDecl->isMoveAssignmentOperator())
Sebastian Redl22653ba2011-08-30 19:58:05 +000013297 DefineImplicitMoveAssignment(Loc, MethodDecl);
13298 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000013299 } else if (isa<CXXConversionDecl>(MethodDecl) &&
13300 MethodDecl->getParent()->isLambda()) {
Richard Smithab44d5b2013-12-10 08:25:00 +000013301 CXXConversionDecl *Conversion =
13302 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
Douglas Gregord3b672c2012-02-16 01:06:16 +000013303 if (Conversion->isLambdaToBlockPointerConversion())
13304 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13305 else
13306 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Nico Weberb3a99782015-01-26 06:23:36 +000013307 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
Douglas Gregor88d292c2010-05-13 16:44:06 +000013308 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000013309 }
John McCall83779672011-02-19 02:53:41 +000013310
Eli Friedmanfa0df832012-02-02 03:46:19 +000013311 // Recursive functions should be marked when used from another function.
13312 // FIXME: Is this really right?
13313 if (CurContext == Func) return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000013314
Eli Friedmanfa0df832012-02-02 03:46:19 +000013315 // Implicit instantiation of function templates and member functions of
13316 // class templates.
13317 if (Func->isImplicitlyInstantiable()) {
13318 bool AlreadyInstantiated = false;
Richard Smith4a941e22012-02-14 22:25:15 +000013319 SourceLocation PointOfInstantiation = Loc;
Eli Friedmanfa0df832012-02-02 03:46:19 +000013320 if (FunctionTemplateSpecializationInfo *SpecInfo
13321 = Func->getTemplateSpecializationInfo()) {
13322 if (SpecInfo->getPointOfInstantiation().isInvalid())
13323 SpecInfo->setPointOfInstantiation(Loc);
13324 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000013325 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000013326 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000013327 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13328 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000013329 } else if (MemberSpecializationInfo *MSInfo
13330 = Func->getMemberSpecializationInfo()) {
13331 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregor06db9f52009-10-12 20:18:28 +000013332 MSInfo->setPointOfInstantiation(Loc);
Eli Friedmanfa0df832012-02-02 03:46:19 +000013333 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000013334 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000013335 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000013336 PointOfInstantiation = MSInfo->getPointOfInstantiation();
13337 }
Douglas Gregor06db9f52009-10-12 20:18:28 +000013338 }
Mike Stump11289f42009-09-09 15:08:12 +000013339
David Majnemerc85ed7e2013-10-23 21:31:20 +000013340 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000013341 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
Faisal Vali18d35982013-06-26 02:34:24 +000013342 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13343 ActiveTemplateInstantiations.size())
Richard Smith4a941e22012-02-14 22:25:15 +000013344 PendingLocalImplicitInstantiations.push_back(
13345 std::make_pair(Func, PointOfInstantiation));
David Majnemerc85ed7e2013-10-23 21:31:20 +000013346 else if (Func->isConstexpr())
Eli Friedmanfa0df832012-02-02 03:46:19 +000013347 // Do not defer instantiations of constexpr functions, to avoid the
13348 // expression evaluator needing to call back into Sema if it sees a
13349 // call to such a function.
Richard Smith4a941e22012-02-14 22:25:15 +000013350 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000013351 else {
Richard Smith4a941e22012-02-14 22:25:15 +000013352 PendingInstantiations.push_back(std::make_pair(Func,
13353 PointOfInstantiation));
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000013354 // Notify the consumer that a function was implicitly instantiated.
13355 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13356 }
John McCall83779672011-02-19 02:53:41 +000013357 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000013358 } else {
13359 // Walk redefinitions, as some of them may be instantiable.
Aaron Ballman86c93902014-03-06 23:45:36 +000013360 for (auto i : Func->redecls()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000013361 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Richard Smith0e32c522016-03-25 22:29:27 +000013362 MarkFunctionReferenced(Loc, i, OdrUse);
Eli Friedmanfa0df832012-02-02 03:46:19 +000013363 }
Sam Weinigbae69142009-09-11 03:29:30 +000013364 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000013365
Richard Smith0e32c522016-03-25 22:29:27 +000013366 if (!OdrUse) return;
13367
Eli Friedmanfa0df832012-02-02 03:46:19 +000013368 // Keep track of used but undefined functions.
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +000013369 if (!Func->isDefined()) {
Rafael Espindola0e0d0092013-03-14 03:07:35 +000013370 if (mightHaveNonExternalLinkage(Func))
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +000013371 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13372 else if (Func->getMostRecentDecl()->isInlined() &&
Peter Collingbourne470d9422015-05-13 22:07:22 +000013373 !LangOpts.GNUInline &&
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +000013374 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13375 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
Eli Friedmanfa0df832012-02-02 03:46:19 +000013376 }
13377
Vassil Vassilev928c8252016-04-28 14:13:28 +000013378 Func->markUsed(Context);
Eli Friedmanfa0df832012-02-02 03:46:19 +000013379}
13380
Eli Friedman9bb33f52012-02-03 02:04:35 +000013381static void
13382diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
Richard Smith1879f102016-08-15 02:34:23 +000013383 ValueDecl *var, DeclContext *DC) {
Eli Friedmandd053f62012-02-07 00:15:00 +000013384 DeclContext *VarDC = var->getDeclContext();
13385
Eli Friedman9bb33f52012-02-03 02:04:35 +000013386 // If the parameter still belongs to the translation unit, then
13387 // we're actually just using one parameter in the declaration of
13388 // the next.
13389 if (isa<ParmVarDecl>(var) &&
Eli Friedmandd053f62012-02-07 00:15:00 +000013390 isa<TranslationUnitDecl>(VarDC))
Eli Friedman9bb33f52012-02-03 02:04:35 +000013391 return;
13392
Eli Friedmandd053f62012-02-07 00:15:00 +000013393 // For C code, don't diagnose about capture if we're not actually in code
13394 // right now; it's impossible to write a non-constant expression outside of
13395 // function context, so we'll get other (more useful) diagnostics later.
13396 //
13397 // For C++, things get a bit more nasty... it would be nice to suppress this
13398 // diagnostic for certain cases like using a local variable in an array bound
13399 // for a member of a local class, but the correct predicate is not obvious.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013400 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman9bb33f52012-02-03 02:04:35 +000013401 return;
13402
Richard Smith1879f102016-08-15 02:34:23 +000013403 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
13404 unsigned ContextKind = 3; // unknown
Eli Friedmandd053f62012-02-07 00:15:00 +000013405 if (isa<CXXMethodDecl>(VarDC) &&
13406 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
Richard Smith1879f102016-08-15 02:34:23 +000013407 ContextKind = 2;
13408 } else if (isa<FunctionDecl>(VarDC)) {
13409 ContextKind = 0;
Eli Friedmandd053f62012-02-07 00:15:00 +000013410 } else if (isa<BlockDecl>(VarDC)) {
Richard Smith1879f102016-08-15 02:34:23 +000013411 ContextKind = 1;
Eli Friedmandd053f62012-02-07 00:15:00 +000013412 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000013413
Richard Smith1879f102016-08-15 02:34:23 +000013414 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
13415 << var << ValueKind << ContextKind << VarDC;
Alp Toker2afa8782014-05-28 12:20:14 +000013416 S.Diag(var->getLocation(), diag::note_entity_declared_at)
Richard Smith1879f102016-08-15 02:34:23 +000013417 << var;
Eli Friedmandd053f62012-02-07 00:15:00 +000013418
13419 // FIXME: Add additional diagnostic info about class etc. which prevents
13420 // capture.
Eli Friedman9bb33f52012-02-03 02:04:35 +000013421}
13422
Faisal Valiad090d82013-10-07 05:13:48 +000013423
13424static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
13425 bool &SubCapturesAreNested,
13426 QualType &CaptureType,
13427 QualType &DeclRefType) {
13428 // Check whether we've already captured it.
13429 if (CSI->CaptureMap.count(Var)) {
13430 // If we found a capture, any subcaptures are nested.
13431 SubCapturesAreNested = true;
13432
13433 // Retrieve the capture type for this variable.
13434 CaptureType = CSI->getCapture(Var).getCaptureType();
13435
13436 // Compute the type of an expression that refers to this variable.
13437 DeclRefType = CaptureType.getNonReferenceType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +000013438
13439 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13440 // are mutable in the sense that user can change their value - they are
13441 // private instances of the captured declarations.
Faisal Valiad090d82013-10-07 05:13:48 +000013442 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13443 if (Cap.isCopyCapture() &&
Samuel Antao4af1b7b2015-12-02 17:44:43 +000013444 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13445 !(isa<CapturedRegionScopeInfo>(CSI) &&
13446 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
Faisal Valiad090d82013-10-07 05:13:48 +000013447 DeclRefType.addConst();
13448 return true;
13449 }
13450 return false;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000013451}
13452
Faisal Valiad090d82013-10-07 05:13:48 +000013453// Only block literals, captured statements, and lambda expressions can
13454// capture; other scopes don't work.
13455static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
13456 SourceLocation Loc,
13457 const bool Diagnose, Sema &S) {
Faisal Valia17d19f2013-11-07 05:17:06 +000013458 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13459 return getLambdaAwareParentOfDeclContext(DC);
Alexey Bataevf841bd92014-12-16 07:00:22 +000013460 else if (Var->hasLocalStorage()) {
Faisal Valiad090d82013-10-07 05:13:48 +000013461 if (Diagnose)
13462 diagnoseUncapturableValueReference(S, Loc, Var, DC);
13463 }
Craig Topperc3ec1492014-05-26 06:22:03 +000013464 return nullptr;
Faisal Valiad090d82013-10-07 05:13:48 +000013465}
13466
13467// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13468// certain types of variables (unnamed, variably modified types etc.)
13469// so check for eligibility.
13470static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
13471 SourceLocation Loc,
13472 const bool Diagnose, Sema &S) {
13473
13474 bool IsBlock = isa<BlockScopeInfo>(CSI);
13475 bool IsLambda = isa<LambdaScopeInfo>(CSI);
13476
13477 // Lambdas are not allowed to capture unnamed variables
13478 // (e.g. anonymous unions).
13479 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13480 // assuming that's the intent.
13481 if (IsLambda && !Var->getDeclName()) {
13482 if (Diagnose) {
13483 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13484 S.Diag(Var->getLocation(), diag::note_declared_at);
13485 }
13486 return false;
13487 }
13488
Alexey Bataev39c81e22014-08-28 04:28:19 +000013489 // Prohibit variably-modified types in blocks; they're difficult to deal with.
13490 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
Faisal Valiad090d82013-10-07 05:13:48 +000013491 if (Diagnose) {
Alexey Bataev39c81e22014-08-28 04:28:19 +000013492 S.Diag(Loc, diag::err_ref_vm_type);
Faisal Valiad090d82013-10-07 05:13:48 +000013493 S.Diag(Var->getLocation(), diag::note_previous_decl)
13494 << Var->getDeclName();
13495 }
13496 return false;
13497 }
13498 // Prohibit structs with flexible array members too.
13499 // We cannot capture what is in the tail end of the struct.
13500 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13501 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13502 if (Diagnose) {
13503 if (IsBlock)
13504 S.Diag(Loc, diag::err_ref_flexarray_type);
13505 else
13506 S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13507 << Var->getDeclName();
13508 S.Diag(Var->getLocation(), diag::note_previous_decl)
13509 << Var->getDeclName();
13510 }
13511 return false;
13512 }
13513 }
13514 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13515 // Lambdas and captured statements are not allowed to capture __block
13516 // variables; they don't support the expected semantics.
13517 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13518 if (Diagnose) {
13519 S.Diag(Loc, diag::err_capture_block_variable)
13520 << Var->getDeclName() << !IsLambda;
13521 S.Diag(Var->getLocation(), diag::note_previous_decl)
13522 << Var->getDeclName();
13523 }
13524 return false;
13525 }
13526
13527 return true;
13528}
13529
13530// Returns true if the capture by block was successful.
13531static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
13532 SourceLocation Loc,
13533 const bool BuildAndDiagnose,
13534 QualType &CaptureType,
13535 QualType &DeclRefType,
13536 const bool Nested,
13537 Sema &S) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013538 Expr *CopyExpr = nullptr;
Faisal Valiad090d82013-10-07 05:13:48 +000013539 bool ByRef = false;
13540
13541 // Blocks are not allowed to capture arrays.
13542 if (CaptureType->isArrayType()) {
13543 if (BuildAndDiagnose) {
13544 S.Diag(Loc, diag::err_ref_array_type);
13545 S.Diag(Var->getLocation(), diag::note_previous_decl)
13546 << Var->getDeclName();
13547 }
13548 return false;
13549 }
13550
13551 // Forbid the block-capture of autoreleasing variables.
13552 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13553 if (BuildAndDiagnose) {
13554 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13555 << /*block*/ 0;
13556 S.Diag(Var->getLocation(), diag::note_previous_decl)
13557 << Var->getDeclName();
13558 }
13559 return false;
13560 }
Akira Hatanakac81708e2016-10-24 21:45:54 +000013561
13562 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
13563 if (auto *PT = dyn_cast<PointerType>(CaptureType)) {
13564 QualType PointeeTy = PT->getPointeeType();
13565 if (isa<ObjCObjectPointerType>(PointeeTy.getCanonicalType()) &&
13566 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
13567 !isa<AttributedType>(PointeeTy)) {
13568 if (BuildAndDiagnose) {
13569 SourceLocation VarLoc = Var->getLocation();
13570 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
13571 S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing) <<
13572 FixItHint::CreateInsertion(VarLoc, "__autoreleasing");
13573 S.Diag(VarLoc, diag::note_declare_parameter_strong);
13574 }
13575 }
13576 }
13577
Faisal Valiad090d82013-10-07 05:13:48 +000013578 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013579 if (HasBlocksAttr || CaptureType->isReferenceType() ||
13580 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
Faisal Valiad090d82013-10-07 05:13:48 +000013581 // Block capture by reference does not change the capture or
13582 // declaration reference types.
13583 ByRef = true;
13584 } else {
13585 // Block capture by copy introduces 'const'.
13586 CaptureType = CaptureType.getNonReferenceType().withConst();
13587 DeclRefType = CaptureType;
13588
13589 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13590 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13591 // The capture logic needs the destructor, so make sure we mark it.
13592 // Usually this is unnecessary because most local variables have
13593 // their destructors marked at declaration time, but parameters are
13594 // an exception because it's technically only the call site that
13595 // actually requires the destructor.
13596 if (isa<ParmVarDecl>(Var))
13597 S.FinalizeVarWithDestructor(Var, Record);
13598
13599 // Enter a new evaluation context to insulate the copy
13600 // full-expression.
13601 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
13602
13603 // According to the blocks spec, the capture of a variable from
13604 // the stack requires a const copy constructor. This is not true
13605 // of the copy/move done to move a __block variable to the heap.
13606 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13607 DeclRefType.withConst(),
13608 VK_LValue, Loc);
13609
13610 ExprResult Result
13611 = S.PerformCopyInitialization(
13612 InitializedEntity::InitializeBlock(Var->getLocation(),
13613 CaptureType, false),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000013614 Loc, DeclRef);
Faisal Valiad090d82013-10-07 05:13:48 +000013615
13616 // Build a full-expression copy expression if initialization
13617 // succeeded and used a non-trivial constructor. Recover from
13618 // errors by pretending that the copy isn't necessary.
13619 if (!Result.isInvalid() &&
13620 !cast<CXXConstructExpr>(Result.get())->getConstructor()
13621 ->isTrivial()) {
13622 Result = S.MaybeCreateExprWithCleanups(Result);
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013623 CopyExpr = Result.get();
Faisal Valiad090d82013-10-07 05:13:48 +000013624 }
13625 }
13626 }
13627 }
13628
13629 // Actually capture the variable.
13630 if (BuildAndDiagnose)
13631 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
13632 SourceLocation(), CaptureType, CopyExpr);
13633
13634 return true;
13635
13636}
13637
13638
13639/// \brief Capture the given variable in the captured region.
13640static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13641 VarDecl *Var,
13642 SourceLocation Loc,
13643 const bool BuildAndDiagnose,
13644 QualType &CaptureType,
13645 QualType &DeclRefType,
Alexey Bataev07649fb2014-12-16 08:01:48 +000013646 const bool RefersToCapturedVariable,
Faisal Valiad090d82013-10-07 05:13:48 +000013647 Sema &S) {
Faisal Valiad090d82013-10-07 05:13:48 +000013648 // By default, capture variables by reference.
13649 bool ByRef = true;
13650 // Using an LValue reference type is consistent with Lambdas (see below).
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013651 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000013652 if (S.IsOpenMPCapturedDecl(Var))
Samuel Antao4af1b7b2015-12-02 17:44:43 +000013653 DeclRefType = DeclRefType.getUnqualifiedType();
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013654 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
Samuel Antao4af1b7b2015-12-02 17:44:43 +000013655 }
13656
13657 if (ByRef)
13658 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13659 else
13660 CaptureType = DeclRefType;
13661
Craig Topperc3ec1492014-05-26 06:22:03 +000013662 Expr *CopyExpr = nullptr;
Faisal Valiad090d82013-10-07 05:13:48 +000013663 if (BuildAndDiagnose) {
13664 // The current implementation assumes that all variables are captured
Nico Weber83ea0122014-05-03 21:57:40 +000013665 // by references. Since there is no capture by copy, no expression
13666 // evaluation will be needed.
Faisal Valiad090d82013-10-07 05:13:48 +000013667 RecordDecl *RD = RSI->TheRecordDecl;
13668
13669 FieldDecl *Field
Craig Topperc3ec1492014-05-26 06:22:03 +000013670 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
Faisal Valiad090d82013-10-07 05:13:48 +000013671 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
Craig Topperc3ec1492014-05-26 06:22:03 +000013672 nullptr, false, ICIS_NoInit);
Faisal Valiad090d82013-10-07 05:13:48 +000013673 Field->setImplicit(true);
13674 Field->setAccess(AS_private);
13675 RD->addDecl(Field);
13676
Alexey Bataev07649fb2014-12-16 08:01:48 +000013677 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
Faisal Valiad090d82013-10-07 05:13:48 +000013678 DeclRefType, VK_LValue, Loc);
13679 Var->setReferenced(true);
13680 Var->markUsed(S.Context);
13681 }
13682
13683 // Actually capture the variable.
13684 if (BuildAndDiagnose)
Alexey Bataev07649fb2014-12-16 08:01:48 +000013685 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
Faisal Valiad090d82013-10-07 05:13:48 +000013686 SourceLocation(), CaptureType, CopyExpr);
13687
13688
13689 return true;
13690}
13691
13692/// \brief Create a field within the lambda class for the variable
Richard Smithc38498f2015-04-27 21:27:54 +000013693/// being captured.
Faisal Vali084c9122016-03-23 17:39:51 +000013694static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
Richard Smithc38498f2015-04-27 21:27:54 +000013695 QualType FieldType, QualType DeclRefType,
13696 SourceLocation Loc,
13697 bool RefersToCapturedVariable) {
Douglas Gregor81495f32012-02-12 18:42:33 +000013698 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregor81495f32012-02-12 18:42:33 +000013699
Douglas Gregorabecb9c2012-02-09 01:56:40 +000013700 // Build the non-static data member.
13701 FieldDecl *Field
Craig Topperc3ec1492014-05-26 06:22:03 +000013702 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
Douglas Gregorabecb9c2012-02-09 01:56:40 +000013703 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Craig Topperc3ec1492014-05-26 06:22:03 +000013704 nullptr, false, ICIS_NoInit);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000013705 Field->setImplicit(true);
13706 Field->setAccess(AS_private);
Douglas Gregor3d23f7882012-02-09 02:12:34 +000013707 Lambda->addDecl(Field);
Douglas Gregor199cec72012-02-09 02:45:47 +000013708}
Douglas Gregorabecb9c2012-02-09 01:56:40 +000013709
Faisal Valiad090d82013-10-07 05:13:48 +000013710/// \brief Capture the given variable in the lambda.
13711static bool captureInLambda(LambdaScopeInfo *LSI,
13712 VarDecl *Var,
13713 SourceLocation Loc,
13714 const bool BuildAndDiagnose,
13715 QualType &CaptureType,
13716 QualType &DeclRefType,
Alexey Bataev07649fb2014-12-16 08:01:48 +000013717 const bool RefersToCapturedVariable,
Faisal Valiad090d82013-10-07 05:13:48 +000013718 const Sema::TryCaptureKind Kind,
13719 SourceLocation EllipsisLoc,
13720 const bool IsTopScope,
13721 Sema &S) {
13722
13723 // Determine whether we are capturing by reference or by value.
13724 bool ByRef = false;
13725 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13726 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13727 } else {
13728 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13729 }
13730
13731 // Compute the type of the field that will capture this variable.
13732 if (ByRef) {
13733 // C++11 [expr.prim.lambda]p15:
13734 // An entity is captured by reference if it is implicitly or
13735 // explicitly captured but not captured by copy. It is
13736 // unspecified whether additional unnamed non-static data
13737 // members are declared in the closure type for entities
13738 // captured by reference.
13739 //
13740 // FIXME: It is not clear whether we want to build an lvalue reference
13741 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13742 // to do the former, while EDG does the latter. Core issue 1249 will
13743 // clarify, but for now we follow GCC because it's a more permissive and
13744 // easily defensible position.
13745 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13746 } else {
13747 // C++11 [expr.prim.lambda]p14:
13748 // For each entity captured by copy, an unnamed non-static
13749 // data member is declared in the closure type. The
13750 // declaration order of these members is unspecified. The type
13751 // of such a data member is the type of the corresponding
13752 // captured entity if the entity is not a reference to an
13753 // object, or the referenced type otherwise. [Note: If the
13754 // captured entity is a reference to a function, the
13755 // corresponding data member is also a reference to a
13756 // function. - end note ]
13757 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13758 if (!RefType->getPointeeType()->isFunctionType())
13759 CaptureType = RefType->getPointeeType();
13760 }
13761
13762 // Forbid the lambda copy-capture of autoreleasing variables.
13763 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13764 if (BuildAndDiagnose) {
13765 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13766 S.Diag(Var->getLocation(), diag::note_previous_decl)
13767 << Var->getDeclName();
13768 }
13769 return false;
13770 }
Douglas Gregor71fe0e82013-10-11 04:25:21 +000013771
Richard Smith111d3482014-01-21 23:27:46 +000013772 // Make sure that by-copy captures are of a complete and non-abstract type.
13773 if (BuildAndDiagnose) {
13774 if (!CaptureType->isDependentType() &&
13775 S.RequireCompleteType(Loc, CaptureType,
13776 diag::err_capture_of_incomplete_type,
13777 Var->getDeclName()))
13778 return false;
13779
13780 if (S.RequireNonAbstractType(Loc, CaptureType,
13781 diag::err_capture_of_abstract_type))
13782 return false;
13783 }
Faisal Valiad090d82013-10-07 05:13:48 +000013784 }
13785
13786 // Capture this variable in the lambda.
Richard Smithc38498f2015-04-27 21:27:54 +000013787 if (BuildAndDiagnose)
Faisal Vali084c9122016-03-23 17:39:51 +000013788 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
Richard Smithc38498f2015-04-27 21:27:54 +000013789 RefersToCapturedVariable);
Faisal Valiad090d82013-10-07 05:13:48 +000013790
13791 // Compute the type of a reference to this captured variable.
13792 if (ByRef)
13793 DeclRefType = CaptureType.getNonReferenceType();
13794 else {
13795 // C++ [expr.prim.lambda]p5:
13796 // The closure type for a lambda-expression has a public inline
13797 // function call operator [...]. This function call operator is
Justin Lebar14299362016-10-06 19:47:56 +000013798 // declared const (9.3.1) if and only if the lambda-expression's
Faisal Valiad090d82013-10-07 05:13:48 +000013799 // parameter-declaration-clause is not followed by mutable.
13800 DeclRefType = CaptureType.getNonReferenceType();
13801 if (!LSI->Mutable && !CaptureType->isReferenceType())
13802 DeclRefType.addConst();
13803 }
13804
13805 // Add the capture.
13806 if (BuildAndDiagnose)
Alexey Bataev07649fb2014-12-16 08:01:48 +000013807 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
Richard Smithc38498f2015-04-27 21:27:54 +000013808 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
Faisal Valiad090d82013-10-07 05:13:48 +000013809
13810 return true;
13811}
13812
Richard Smithc38498f2015-04-27 21:27:54 +000013813bool Sema::tryCaptureVariable(
13814 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13815 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13816 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13817 // An init-capture is notionally from the context surrounding its
13818 // declaration, but its parent DC is the lambda class.
13819 DeclContext *VarDC = Var->getDeclContext();
13820 if (Var->isInitCapture())
13821 VarDC = VarDC->getParent();
Douglas Gregor81495f32012-02-12 18:42:33 +000013822
Eli Friedman24af8502012-02-03 22:47:37 +000013823 DeclContext *DC = CurContext;
Faisal Valia17d19f2013-11-07 05:17:06 +000013824 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
13825 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
13826 // We need to sync up the Declaration Context with the
13827 // FunctionScopeIndexToStopAt
13828 if (FunctionScopeIndexToStopAt) {
13829 unsigned FSIndex = FunctionScopes.size() - 1;
13830 while (FSIndex != MaxFunctionScopesIndex) {
13831 DC = getLambdaAwareParentOfDeclContext(DC);
13832 --FSIndex;
13833 }
13834 }
Faisal Valiad090d82013-10-07 05:13:48 +000013835
Faisal Valia17d19f2013-11-07 05:17:06 +000013836
Richard Smithc38498f2015-04-27 21:27:54 +000013837 // If the variable is declared in the current context, there is no need to
13838 // capture it.
13839 if (VarDC == DC) return true;
Alexey Bataevf841bd92014-12-16 07:00:22 +000013840
13841 // Capture global variables if it is required to use private copy of this
13842 // variable.
13843 bool IsGlobal = !Var->hasLocalStorage();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000013844 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
Alexey Bataevf841bd92014-12-16 07:00:22 +000013845 return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000013846
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013847 // Walk up the stack to determine whether we can capture the variable,
13848 // performing the "simple" checks that don't depend on type. We stop when
13849 // we've either hit the declared scope of the variable or find an existing
Faisal Valiad090d82013-10-07 05:13:48 +000013850 // capture of that variable. We start from the innermost capturing-entity
13851 // (the DC) and ensure that all intervening capturing-entities
13852 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
13853 // declcontext can either capture the variable or have already captured
13854 // the variable.
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013855 CaptureType = Var->getType();
13856 DeclRefType = CaptureType.getNonReferenceType();
Richard Smithc38498f2015-04-27 21:27:54 +000013857 bool Nested = false;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013858 bool Explicit = (Kind != TryCapture_Implicit);
Faisal Valiad090d82013-10-07 05:13:48 +000013859 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
Eli Friedman9bb33f52012-02-03 02:04:35 +000013860 do {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000013861 // Only block literals, captured statements, and lambda expressions can
13862 // capture; other scopes don't work.
Faisal Valiad090d82013-10-07 05:13:48 +000013863 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
13864 ExprLoc,
13865 BuildAndDiagnose,
13866 *this);
Alexey Bataevf841bd92014-12-16 07:00:22 +000013867 // We need to check for the parent *first* because, if we *have*
13868 // private-captured a global variable, we need to recursively capture it in
13869 // intermediate blocks, lambdas, etc.
13870 if (!ParentDC) {
13871 if (IsGlobal) {
13872 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
13873 break;
13874 }
13875 return true;
13876 }
13877
Faisal Valiad090d82013-10-07 05:13:48 +000013878 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
13879 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
Eli Friedman9bb33f52012-02-03 02:04:35 +000013880
Eli Friedman9bb33f52012-02-03 02:04:35 +000013881
Eli Friedman24af8502012-02-03 22:47:37 +000013882 // Check whether we've already captured it.
Faisal Valiad090d82013-10-07 05:13:48 +000013883 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
13884 DeclRefType))
Eli Friedman9bb33f52012-02-03 02:04:35 +000013885 break;
Faisal Valia17d19f2013-11-07 05:17:06 +000013886 // If we are instantiating a generic lambda call operator body,
13887 // we do not want to capture new variables. What was captured
13888 // during either a lambdas transformation or initial parsing
13889 // should be used.
13890 if (isGenericLambdaCallOperatorSpecialization(DC)) {
13891 if (BuildAndDiagnose) {
13892 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13893 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
13894 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13895 Diag(Var->getLocation(), diag::note_previous_decl)
13896 << Var->getDeclName();
13897 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
13898 } else
13899 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
13900 }
13901 return true;
13902 }
Faisal Valiad090d82013-10-07 05:13:48 +000013903 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13904 // certain types of variables (unnamed, variably modified types etc.)
13905 // so check for eligibility.
13906 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
Alexey Bataevaca7fcf2014-06-30 02:55:54 +000013907 return true;
13908
13909 // Try to capture variable-length arrays types.
13910 if (Var->getType()->isVariablyModifiedType()) {
13911 // We're going to walk down into the type and look for VLA
13912 // expressions.
13913 QualType QTy = Var->getType();
13914 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
13915 QTy = PVD->getOriginalType();
Alexey Bataev93a546a2016-01-21 12:54:48 +000013916 captureVariablyModifiedType(Context, QTy, CSI);
Alexey Bataevaca7fcf2014-06-30 02:55:54 +000013917 }
13918
Alexey Bataevb5001012015-09-03 10:21:46 +000013919 if (getLangOpts().OpenMP) {
13920 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13921 // OpenMP private variables should not be captured in outer scope, so
Samuel Antao4be30e92015-10-02 17:14:03 +000013922 // just break here. Similarly, global variables that are captured in a
13923 // target region should not be captured outside the scope of the region.
Alexey Bataevb5001012015-09-03 10:21:46 +000013924 if (RSI->CapRegionKind == CR_OpenMP) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013925 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
Samuel Antao4be30e92015-10-02 17:14:03 +000013926 // When we detect target captures we are looking from inside the
13927 // target region, therefore we need to propagate the capture from the
13928 // enclosing region. Therefore, the capture is not initially nested.
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013929 if (IsTargetCap)
Samuel Antao4be30e92015-10-02 17:14:03 +000013930 FunctionScopesIndex--;
13931
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013932 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
13933 Nested = !IsTargetCap;
Alexey Bataevb5001012015-09-03 10:21:46 +000013934 DeclRefType = DeclRefType.getUnqualifiedType();
13935 CaptureType = Context.getLValueReferenceType(DeclRefType);
13936 break;
13937 }
Alexey Bataevb5001012015-09-03 10:21:46 +000013938 }
13939 }
13940 }
Douglas Gregor81495f32012-02-12 18:42:33 +000013941 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
Faisal Valiad090d82013-10-07 05:13:48 +000013942 // No capture-default, and this is not an explicit capture
13943 // so cannot capture this variable.
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013944 if (BuildAndDiagnose) {
Faisal Valiad090d82013-10-07 05:13:48 +000013945 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
Douglas Gregor81495f32012-02-12 18:42:33 +000013946 Diag(Var->getLocation(), diag::note_previous_decl)
13947 << Var->getDeclName();
Richard Trieu2334a302016-03-05 04:04:57 +000013948 if (cast<LambdaScopeInfo>(CSI)->Lambda)
13949 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
13950 diag::note_lambda_decl);
Faisal Valia17d19f2013-11-07 05:17:06 +000013951 // FIXME: If we error out because an outer lambda can not implicitly
13952 // capture a variable that an inner lambda explicitly captures, we
13953 // should have the inner lambda do the explicit capture - because
13954 // it makes for cleaner diagnostics later. This would purely be done
13955 // so that the diagnostic does not misleadingly claim that a variable
13956 // can not be captured by a lambda implicitly even though it is captured
13957 // explicitly. Suggestion:
13958 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
13959 // at the function head
13960 // - cache the StartingDeclContext - this must be a lambda
13961 // - captureInLambda in the innermost lambda the variable.
Douglas Gregor81495f32012-02-12 18:42:33 +000013962 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013963 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000013964 }
13965
13966 FunctionScopesIndex--;
13967 DC = ParentDC;
13968 Explicit = false;
Richard Smithc38498f2015-04-27 21:27:54 +000013969 } while (!VarDC->Equals(DC));
Douglas Gregor81495f32012-02-12 18:42:33 +000013970
Faisal Valiad090d82013-10-07 05:13:48 +000013971 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
13972 // computing the type of the capture at each step, checking type-specific
13973 // requirements, and adding captures if requested.
13974 // If the variable had already been captured previously, we start capturing
13975 // at the lambda nested within that one.
13976 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013977 ++I) {
13978 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor812d8f62012-02-18 05:51:20 +000013979
Faisal Valiad090d82013-10-07 05:13:48 +000013980 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
13981 if (!captureInBlock(BSI, Var, ExprLoc,
13982 BuildAndDiagnose, CaptureType,
13983 DeclRefType, Nested, *this))
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013984 return true;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000013985 Nested = true;
Faisal Valiad090d82013-10-07 05:13:48 +000013986 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13987 if (!captureInCapturedRegion(RSI, Var, ExprLoc,
13988 BuildAndDiagnose, CaptureType,
13989 DeclRefType, Nested, *this))
John McCall67cd5e02012-03-30 05:23:48 +000013990 return true;
Faisal Valiad090d82013-10-07 05:13:48 +000013991 Nested = true;
13992 } else {
13993 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13994 if (!captureInLambda(LSI, Var, ExprLoc,
13995 BuildAndDiagnose, CaptureType,
13996 DeclRefType, Nested, Kind, EllipsisLoc,
13997 /*IsTopScope*/I == N - 1, *this))
13998 return true;
13999 Nested = true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000014000 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000014001 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000014002 return false;
14003}
14004
14005bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
14006 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
14007 QualType CaptureType;
14008 QualType DeclRefType;
14009 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
14010 /*BuildAndDiagnose=*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +000014011 DeclRefType, nullptr);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000014012}
14013
Alexey Bataevf841bd92014-12-16 07:00:22 +000014014bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
14015 QualType CaptureType;
14016 QualType DeclRefType;
14017 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14018 /*BuildAndDiagnose=*/false, CaptureType,
14019 DeclRefType, nullptr);
14020}
14021
Douglas Gregorfdf598e2012-02-18 09:37:24 +000014022QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
14023 QualType CaptureType;
14024 QualType DeclRefType;
14025
14026 // Determine whether we can capture this variable.
14027 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
Faisal Valia17d19f2013-11-07 05:17:06 +000014028 /*BuildAndDiagnose=*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +000014029 DeclRefType, nullptr))
Douglas Gregorfdf598e2012-02-18 09:37:24 +000014030 return QualType();
14031
14032 return DeclRefType;
Eli Friedman9bb33f52012-02-03 02:04:35 +000014033}
14034
Eli Friedman3bda6b12012-02-02 23:15:15 +000014035
Eli Friedman9bb33f52012-02-03 02:04:35 +000014036
Faisal Valia17d19f2013-11-07 05:17:06 +000014037// If either the type of the variable or the initializer is dependent,
14038// return false. Otherwise, determine whether the variable is a constant
14039// expression. Use this if you need to know if a variable that might or
14040// might not be dependent is truly a constant expression.
14041static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
14042 ASTContext &Context) {
14043
14044 if (Var->getType()->isDependentType())
14045 return false;
Craig Topperc3ec1492014-05-26 06:22:03 +000014046 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +000014047 Var->getAnyInitializer(DefVD);
14048 if (!DefVD)
14049 return false;
14050 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
14051 Expr *Init = cast<Expr>(Eval->Value);
14052 if (Init->isValueDependent())
14053 return false;
14054 return IsVariableAConstantExpression(Var, Context);
Eli Friedman3bda6b12012-02-02 23:15:15 +000014055}
14056
Faisal Valia17d19f2013-11-07 05:17:06 +000014057
Eli Friedman3bda6b12012-02-02 23:15:15 +000014058void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
14059 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
14060 // an object that satisfies the requirements for appearing in a
14061 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
14062 // is immediately applied." This function handles the lvalue-to-rvalue
14063 // conversion part.
14064 MaybeODRUseExprs.erase(E->IgnoreParens());
Faisal Valia17d19f2013-11-07 05:17:06 +000014065
14066 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
14067 // to a variable that is a constant expression, and if so, identify it as
14068 // a reference to a variable that does not involve an odr-use of that
14069 // variable.
14070 if (LambdaScopeInfo *LSI = getCurLambda()) {
14071 Expr *SansParensExpr = E->IgnoreParens();
Craig Topperc3ec1492014-05-26 06:22:03 +000014072 VarDecl *Var = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +000014073 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
14074 Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
14075 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
14076 Var = dyn_cast<VarDecl>(ME->getMemberDecl());
14077
14078 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
14079 LSI->markVariableExprAsNonODRUsed(SansParensExpr);
14080 }
Eli Friedman3bda6b12012-02-02 23:15:15 +000014081}
14082
Eli Friedmanc6237c62012-02-29 03:16:56 +000014083ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
Kaelyn Takatab16e6322014-11-20 22:06:40 +000014084 Res = CorrectDelayedTyposInExpr(Res);
14085
Eli Friedmanc6237c62012-02-29 03:16:56 +000014086 if (!Res.isUsable())
14087 return Res;
14088
14089 // If a constant-expression is a reference to a variable where we delay
14090 // deciding whether it is an odr-use, just assume we will apply the
14091 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
14092 // (a non-type template argument), we have special handling anyway.
14093 UpdateMarkingForLValueToRValue(Res.get());
14094 return Res;
14095}
14096
Eli Friedman3bda6b12012-02-02 23:15:15 +000014097void Sema::CleanupVarDeclMarking() {
Craig Topperdfe29ae2015-12-21 06:35:56 +000014098 for (Expr *E : MaybeODRUseExprs) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000014099 VarDecl *Var;
14100 SourceLocation Loc;
Craig Topperdfe29ae2015-12-21 06:35:56 +000014101 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000014102 Var = cast<VarDecl>(DRE->getDecl());
14103 Loc = DRE->getLocation();
Craig Topperdfe29ae2015-12-21 06:35:56 +000014104 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000014105 Var = cast<VarDecl>(ME->getMemberDecl());
14106 Loc = ME->getMemberLoc();
14107 } else {
Larisse Voufo4e673c92014-07-29 18:45:54 +000014108 llvm_unreachable("Unexpected expression");
Eli Friedman3bda6b12012-02-02 23:15:15 +000014109 }
14110
Craig Topperc3ec1492014-05-26 06:22:03 +000014111 MarkVarDeclODRUsed(Var, Loc, *this,
14112 /*MaxFunctionScopeIndex Pointer*/ nullptr);
Eli Friedman3bda6b12012-02-02 23:15:15 +000014113 }
14114
14115 MaybeODRUseExprs.clear();
14116}
14117
Faisal Valia17d19f2013-11-07 05:17:06 +000014118
Eli Friedman3bda6b12012-02-02 23:15:15 +000014119static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
14120 VarDecl *Var, Expr *E) {
Benjamin Kramercd502b52013-11-07 11:03:53 +000014121 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
14122 "Invalid Expr argument to DoMarkVarDeclReferenced");
Eli Friedmanfa0df832012-02-02 03:46:19 +000014123 Var->setReferenced();
14124
Larisse Voufob6fab262014-07-29 18:44:19 +000014125 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
Larisse Voufof73da982014-07-30 00:49:55 +000014126 bool MarkODRUsed = true;
Larisse Voufob6fab262014-07-29 18:44:19 +000014127
Richard Smith5ef98f72014-02-03 23:22:05 +000014128 // If the context is not potentially evaluated, this is not an odr-use and
14129 // does not trigger instantiation.
Faisal Valia17d19f2013-11-07 05:17:06 +000014130 if (!IsPotentiallyEvaluatedContext(SemaRef)) {
Richard Smith5ef98f72014-02-03 23:22:05 +000014131 if (SemaRef.isUnevaluatedContext())
14132 return;
Faisal Valia17d19f2013-11-07 05:17:06 +000014133
Richard Smith5ef98f72014-02-03 23:22:05 +000014134 // If we don't yet know whether this context is going to end up being an
14135 // evaluated context, and we're referencing a variable from an enclosing
14136 // scope, add a potential capture.
14137 //
14138 // FIXME: Is this necessary? These contexts are only used for default
14139 // arguments, where local variables can't be used.
14140 const bool RefersToEnclosingScope =
14141 (SemaRef.CurContext != Var->getDeclContext() &&
Larisse Voufob6fab262014-07-29 18:44:19 +000014142 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
14143 if (RefersToEnclosingScope) {
Alexey Bataev31939e32016-11-11 12:36:20 +000014144 if (LambdaScopeInfo *const LSI =
14145 SemaRef.getCurLambda(/*IgnoreCapturedRegions=*/true)) {
Larisse Voufob6fab262014-07-29 18:44:19 +000014146 // If a variable could potentially be odr-used, defer marking it so
14147 // until we finish analyzing the full expression for any
14148 // lvalue-to-rvalue
14149 // or discarded value conversions that would obviate odr-use.
14150 // Add it to the list of potential captures that will be analyzed
14151 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
14152 // unless the variable is a reference that was initialized by a constant
14153 // expression (this will never need to be captured or odr-used).
14154 assert(E && "Capture variable should be used in an expression.");
14155 if (!Var->getType()->isReferenceType() ||
14156 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
14157 LSI->addPotentialCapture(E->IgnoreParens());
14158 }
Richard Smith5ef98f72014-02-03 23:22:05 +000014159 }
Larisse Voufob6fab262014-07-29 18:44:19 +000014160
14161 if (!isTemplateInstantiation(TSK))
Craig Topperbd44cd92015-12-08 04:33:04 +000014162 return;
Larisse Voufof73da982014-07-30 00:49:55 +000014163
14164 // Instantiate, but do not mark as odr-used, variable templates.
14165 MarkODRUsed = false;
Faisal Valia17d19f2013-11-07 05:17:06 +000014166 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000014167
Larisse Voufo39a1e502013-08-06 01:03:05 +000014168 VarTemplateSpecializationDecl *VarSpec =
14169 dyn_cast<VarTemplateSpecializationDecl>(Var);
Richard Smith8809a0c2013-09-27 20:14:12 +000014170 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14171 "Can't instantiate a partial template specialization.");
Larisse Voufo39a1e502013-08-06 01:03:05 +000014172
Richard Smith6739a102016-05-05 00:56:12 +000014173 // If this might be a member specialization of a static data member, check
14174 // the specialization is visible. We already did the checks for variable
14175 // template specializations when we created them.
14176 if (TSK != TSK_Undeclared && !isa<VarTemplateSpecializationDecl>(Var))
14177 SemaRef.checkSpecializationVisibility(Loc, Var);
14178
Richard Smith5ef98f72014-02-03 23:22:05 +000014179 // Perform implicit instantiation of static data members, static data member
14180 // templates of class templates, and variable template specializations. Delay
14181 // instantiations of variable templates, except for those that could be used
14182 // in a constant expression.
Richard Smith8809a0c2013-09-27 20:14:12 +000014183 if (isTemplateInstantiation(TSK)) {
14184 bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
Larisse Voufo39a1e502013-08-06 01:03:05 +000014185
Richard Smith8809a0c2013-09-27 20:14:12 +000014186 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
14187 if (Var->getPointOfInstantiation().isInvalid()) {
14188 // This is a modification of an existing AST node. Notify listeners.
14189 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
14190 L->StaticDataMemberInstantiated(Var);
14191 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
14192 // Don't bother trying to instantiate it again, unless we might need
14193 // its initializer before we get to the end of the TU.
14194 TryInstantiating = false;
Larisse Voufo39a1e502013-08-06 01:03:05 +000014195 }
14196
Richard Smith8809a0c2013-09-27 20:14:12 +000014197 if (Var->getPointOfInstantiation().isInvalid())
14198 Var->setTemplateSpecializationKind(TSK, Loc);
14199
14200 if (TryInstantiating) {
14201 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
Larisse Voufo39a1e502013-08-06 01:03:05 +000014202 bool InstantiationDependent = false;
14203 bool IsNonDependent =
14204 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14205 VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14206 : true;
14207
14208 // Do not instantiate specializations that are still type-dependent.
14209 if (IsNonDependent) {
14210 if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
14211 // Do not defer instantiations of variables which could be used in a
14212 // constant expression.
14213 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14214 } else {
14215 SemaRef.PendingInstantiations
14216 .push_back(std::make_pair(Var, PointOfInstantiation));
14217 }
Richard Smithd3cf2382012-02-15 02:42:50 +000014218 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000014219 }
14220 }
Richard Smith5ef98f72014-02-03 23:22:05 +000014221
Richard Smith6739a102016-05-05 00:56:12 +000014222 if (!MarkODRUsed)
14223 return;
Larisse Voufof73da982014-07-30 00:49:55 +000014224
Richard Smith5a1104b2012-10-20 01:38:33 +000014225 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
14226 // the requirements for appearing in a constant expression (5.19) and, if
14227 // it is an object, the lvalue-to-rvalue conversion (4.1)
Eli Friedman3bda6b12012-02-02 23:15:15 +000014228 // is immediately applied." We check the first part here, and
14229 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
14230 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith5a1104b2012-10-20 01:38:33 +000014231 // C++03 depends on whether we get the C++03 version correct. The second
14232 // part does not apply to references, since they are not objects.
Faisal Valia17d19f2013-11-07 05:17:06 +000014233 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
Richard Smith5ef98f72014-02-03 23:22:05 +000014234 // A reference initialized by a constant expression can never be
Faisal Valia17d19f2013-11-07 05:17:06 +000014235 // odr-used, so simply ignore it.
Richard Smith5a1104b2012-10-20 01:38:33 +000014236 if (!Var->getType()->isReferenceType())
14237 SemaRef.MaybeODRUseExprs.insert(E);
Richard Smith5ef98f72014-02-03 23:22:05 +000014238 } else
Craig Topperc3ec1492014-05-26 06:22:03 +000014239 MarkVarDeclODRUsed(Var, Loc, SemaRef,
14240 /*MaxFunctionScopeIndex ptr*/ nullptr);
Eli Friedman3bda6b12012-02-02 23:15:15 +000014241}
Eli Friedmanfa0df832012-02-02 03:46:19 +000014242
Eli Friedman3bda6b12012-02-02 23:15:15 +000014243/// \brief Mark a variable referenced, and check whether it is odr-used
14244/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
14245/// used directly for normal expressions referring to VarDecl.
14246void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
Craig Topperc3ec1492014-05-26 06:22:03 +000014247 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
Eli Friedmanfa0df832012-02-02 03:46:19 +000014248}
14249
14250static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
Richard Smith0e32c522016-03-25 22:29:27 +000014251 Decl *D, Expr *E, bool MightBeOdrUse) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014252 if (SemaRef.isInOpenMPDeclareTargetContext())
14253 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
14254
Eli Friedman3bda6b12012-02-02 23:15:15 +000014255 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14256 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14257 return;
14258 }
14259
Richard Smith0e32c522016-03-25 22:29:27 +000014260 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
Rafael Espindola49e860b2012-06-26 17:45:31 +000014261
14262 // If this is a call to a method via a cast, also mark the method in the
14263 // derived class used in case codegen can devirtualize the call.
14264 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14265 if (!ME)
14266 return;
14267 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14268 if (!MD)
14269 return;
Reid Kleckner5c553e32014-09-16 22:23:33 +000014270 // Only attempt to devirtualize if this is truly a virtual call.
Davide Italianoccb37382015-07-14 23:36:10 +000014271 bool IsVirtualCall = MD->isVirtual() &&
14272 ME->performsVirtualDispatch(SemaRef.getLangOpts());
Reid Kleckner5c553e32014-09-16 22:23:33 +000014273 if (!IsVirtualCall)
14274 return;
Rafael Espindola49e860b2012-06-26 17:45:31 +000014275 const Expr *Base = ME->getBase();
Rafael Espindolab7f5a9c2012-06-27 18:18:05 +000014276 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Rafael Espindola49e860b2012-06-26 17:45:31 +000014277 if (!MostDerivedClassDecl)
14278 return;
14279 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
Nick Lewyckyb7444cd2013-02-14 00:55:17 +000014280 if (!DM || DM->isPure())
Rafael Espindolaa245edc2012-06-27 17:44:39 +000014281 return;
Richard Smith0e32c522016-03-25 22:29:27 +000014282 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
Douglas Gregord3b672c2012-02-16 01:06:16 +000014283}
Eli Friedmanfa0df832012-02-02 03:46:19 +000014284
Eli Friedmanfa0df832012-02-02 03:46:19 +000014285/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14286void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
Nick Lewycky45b50522013-02-02 00:25:55 +000014287 // TODO: update this with DR# once a defect report is filed.
14288 // C++11 defect. The address of a pure member should not be an ODR use, even
14289 // if it's a qualified reference.
14290 bool OdrUse = true;
14291 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
Nick Lewycky192542c2013-02-05 06:20:31 +000014292 if (Method->isVirtual())
Nick Lewycky45b50522013-02-02 00:25:55 +000014293 OdrUse = false;
14294 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
Eli Friedmanfa0df832012-02-02 03:46:19 +000014295}
14296
14297/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14298void Sema::MarkMemberReferenced(MemberExpr *E) {
Nick Lewycky60bd4be2013-01-31 03:15:20 +000014299 // C++11 [basic.def.odr]p2:
Nick Lewycky35d23592013-01-31 01:34:31 +000014300 // A non-overloaded function whose name appears as a potentially-evaluated
14301 // expression or a member of a set of candidate functions, if selected by
14302 // overload resolution when referred to from a potentially-evaluated
14303 // expression, is odr-used, unless it is a pure virtual function and its
14304 // name is not explicitly qualified.
Richard Smith0e32c522016-03-25 22:29:27 +000014305 bool MightBeOdrUse = true;
Davide Italianoccb37382015-07-14 23:36:10 +000014306 if (E->performsVirtualDispatch(getLangOpts())) {
Nick Lewycky35d23592013-01-31 01:34:31 +000014307 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14308 if (Method->isPure())
Richard Smith0e32c522016-03-25 22:29:27 +000014309 MightBeOdrUse = false;
Nick Lewycky35d23592013-01-31 01:34:31 +000014310 }
Nick Lewyckya096b142013-02-12 08:08:54 +000014311 SourceLocation Loc = E->getMemberLoc().isValid() ?
14312 E->getMemberLoc() : E->getLocStart();
Richard Smith0e32c522016-03-25 22:29:27 +000014313 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
Eli Friedmanfa0df832012-02-02 03:46:19 +000014314}
14315
Douglas Gregorf02455e2012-02-10 09:26:04 +000014316/// \brief Perform marking for a reference to an arbitrary declaration. It
Nico Weber83ea0122014-05-03 21:57:40 +000014317/// marks the declaration referenced, and performs odr-use checking for
14318/// functions and variables. This method should not be used when building a
14319/// normal expression which refers to a variable.
Richard Smith0e32c522016-03-25 22:29:27 +000014320void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14321 bool MightBeOdrUse) {
14322 if (MightBeOdrUse) {
Nico Weber8bf410f2014-08-27 17:04:39 +000014323 if (auto *VD = dyn_cast<VarDecl>(D)) {
Nick Lewycky45b50522013-02-02 00:25:55 +000014324 MarkVariableReferenced(Loc, VD);
14325 return;
14326 }
Nico Weber8bf410f2014-08-27 17:04:39 +000014327 }
14328 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
Richard Smith0e32c522016-03-25 22:29:27 +000014329 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
Nico Weber8bf410f2014-08-27 17:04:39 +000014330 return;
Nick Lewycky45b50522013-02-02 00:25:55 +000014331 }
14332 D->setReferenced();
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000014333}
Anders Carlsson7f84ed92009-10-09 23:51:55 +000014334
Douglas Gregor5597ab42010-05-07 23:12:07 +000014335namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +000014336 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +000014337 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +000014338 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +000014339 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14340 Sema &S;
14341 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +000014342
Douglas Gregor5597ab42010-05-07 23:12:07 +000014343 public:
14344 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +000014345
Douglas Gregor5597ab42010-05-07 23:12:07 +000014346 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +000014347
14348 bool TraverseTemplateArgument(const TemplateArgument &Arg);
14349 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +000014350 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000014351}
Douglas Gregor5597ab42010-05-07 23:12:07 +000014352
Chandler Carruthaf80f662010-06-09 08:17:30 +000014353bool MarkReferencedDecls::TraverseTemplateArgument(
Nico Weber83ea0122014-05-03 21:57:40 +000014354 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000014355 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +000014356 if (Decl *D = Arg.getAsDecl())
Nick Lewycky45b50522013-02-02 00:25:55 +000014357 S.MarkAnyDeclReferenced(Loc, D, true);
Douglas Gregor5597ab42010-05-07 23:12:07 +000014358 }
Chandler Carruthaf80f662010-06-09 08:17:30 +000014359
14360 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +000014361}
14362
Chandler Carruthaf80f662010-06-09 08:17:30 +000014363bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000014364 if (ClassTemplateSpecializationDecl *Spec
14365 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
14366 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +000014367 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +000014368 }
14369
Chandler Carruthc65667c2010-06-10 10:31:57 +000014370 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +000014371}
14372
14373void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14374 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +000014375 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +000014376}
14377
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014378namespace {
14379 /// \brief Helper class that marks all of the declarations referenced by
14380 /// potentially-evaluated subexpressions as "referenced".
14381 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14382 Sema &S;
Douglas Gregor680e9e02012-02-21 19:11:17 +000014383 bool SkipLocalVariables;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014384
14385 public:
14386 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14387
Douglas Gregor680e9e02012-02-21 19:11:17 +000014388 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
14389 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014390
14391 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregor680e9e02012-02-21 19:11:17 +000014392 // If we were asked not to visit local variables, don't.
14393 if (SkipLocalVariables) {
14394 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14395 if (VD->hasLocalStorage())
14396 return;
14397 }
14398
Eli Friedmanfa0df832012-02-02 03:46:19 +000014399 S.MarkDeclRefReferenced(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014400 }
Nico Weber83ea0122014-05-03 21:57:40 +000014401
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014402 void VisitMemberExpr(MemberExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000014403 S.MarkMemberReferenced(E);
Douglas Gregor32b3de52010-09-11 23:32:50 +000014404 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014405 }
14406
John McCall28fc7092011-11-10 05:35:25 +000014407 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000014408 S.MarkFunctionReferenced(E->getLocStart(),
John McCall28fc7092011-11-10 05:35:25 +000014409 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14410 Visit(E->getSubExpr());
14411 }
14412
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014413 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014414 if (E->getOperatorNew())
Eli Friedmanfa0df832012-02-02 03:46:19 +000014415 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014416 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000014417 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +000014418 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014419 }
Sebastian Redl6047f072012-02-16 12:22:20 +000014420
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014421 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14422 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000014423 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000014424 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14425 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14426 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedmanfa0df832012-02-02 03:46:19 +000014427 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000014428 S.LookupDestructor(Record));
14429 }
14430
Douglas Gregor32b3de52010-09-11 23:32:50 +000014431 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014432 }
14433
14434 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000014435 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +000014436 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014437 }
14438
Douglas Gregorf0873f42010-10-19 17:17:35 +000014439 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14440 Visit(E->getExpr());
14441 }
Eli Friedman3bda6b12012-02-02 23:15:15 +000014442
14443 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14444 Inherited::VisitImplicitCastExpr(E);
14445
14446 if (E->getCastKind() == CK_LValueToRValue)
14447 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14448 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014449 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000014450}
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014451
14452/// \brief Mark any declarations that appear within this expression or any
14453/// potentially-evaluated subexpressions as "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +000014454///
14455/// \param SkipLocalVariables If true, don't mark local variables as
14456/// 'referenced'.
14457void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
14458 bool SkipLocalVariables) {
14459 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014460}
14461
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000014462/// \brief Emit a diagnostic that describes an effect on the run-time behavior
14463/// of the program being compiled.
14464///
14465/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000014466/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000014467/// possibility that the code will actually be executable. Code in sizeof()
14468/// expressions, code used only during overload resolution, etc., are not
14469/// potentially evaluated. This routine will suppress such diagnostics or,
14470/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000014471/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000014472/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000014473///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000014474/// This routine should be used for all diagnostics that describe the run-time
14475/// behavior of a program, such as passing a non-POD value through an ellipsis.
14476/// Failure to do so will likely result in spurious diagnostics or failures
14477/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuba63ce62011-09-09 01:45:06 +000014478bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000014479 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +000014480 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000014481 case Unevaluated:
John McCallf413f5e2013-05-03 00:10:13 +000014482 case UnevaluatedAbstract:
Richard Smithb130fe72016-06-23 19:16:49 +000014483 case DiscardedStatement:
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000014484 // The argument will never be evaluated, so don't complain.
14485 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000014486
Richard Smith764d2fe2011-12-20 02:08:33 +000014487 case ConstantEvaluated:
14488 // Relevant diagnostics should be produced by constant evaluation.
14489 break;
14490
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000014491 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000014492 case PotentiallyEvaluatedIfUsed:
Richard Trieuba63ce62011-09-09 01:45:06 +000014493 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +000014494 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuba63ce62011-09-09 01:45:06 +000014495 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek3427fac2011-02-23 01:52:04 +000014496 }
14497 else
14498 Diag(Loc, PD);
14499
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000014500 return true;
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000014501 }
14502
14503 return false;
14504}
14505
Anders Carlsson7f84ed92009-10-09 23:51:55 +000014506bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14507 CallExpr *CE, FunctionDecl *FD) {
14508 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14509 return false;
14510
Richard Smithfd555f62012-02-22 02:04:18 +000014511 // If we're inside a decltype's expression, don't check for a valid return
14512 // type or construct temporaries until we know whether this is the last call.
14513 if (ExprEvalContexts.back().IsDecltype) {
14514 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14515 return false;
14516 }
14517
Douglas Gregora6c5abb2012-05-04 16:48:41 +000014518 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000014519 FunctionDecl *FD;
14520 CallExpr *CE;
14521
14522 public:
14523 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14524 : FD(FD), CE(CE) { }
Craig Toppere14c0f82014-03-12 04:55:44 +000014525
14526 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000014527 if (!FD) {
14528 S.Diag(Loc, diag::err_call_incomplete_return)
14529 << T << CE->getSourceRange();
14530 return;
14531 }
14532
14533 S.Diag(Loc, diag::err_call_function_incomplete_return)
14534 << CE->getSourceRange() << FD->getDeclName() << T;
Alp Toker2afa8782014-05-28 12:20:14 +000014535 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14536 << FD->getDeclName();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000014537 }
14538 } Diagnoser(FD, CE);
14539
14540 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson7f84ed92009-10-09 23:51:55 +000014541 return true;
14542
14543 return false;
14544}
14545
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000014546// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000014547// will prevent this condition from triggering, which is what we want.
14548void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14549 SourceLocation Loc;
14550
John McCall0506e4a2009-11-11 02:41:58 +000014551 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000014552 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000014553
Chandler Carruthf87d6c02011-08-16 22:30:10 +000014554 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000014555 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000014556 return;
14557
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000014558 IsOrAssign = Op->getOpcode() == BO_OrAssign;
14559
John McCallb0e419e2009-11-12 00:06:05 +000014560 // Greylist some idioms by putting them into a warning subcategory.
14561 if (ObjCMessageExpr *ME
14562 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14563 Selector Sel = ME->getSelector();
14564
John McCallb0e419e2009-11-12 00:06:05 +000014565 // self = [<foo> init...]
Jean-Daniel Dupas39655742013-07-17 18:17:14 +000014566 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
John McCallb0e419e2009-11-12 00:06:05 +000014567 diagnostic = diag::warn_condition_is_idiomatic_assignment;
14568
14569 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000014570 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000014571 diagnostic = diag::warn_condition_is_idiomatic_assignment;
14572 }
John McCall0506e4a2009-11-11 02:41:58 +000014573
John McCalld5707ab2009-10-12 21:59:07 +000014574 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +000014575 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000014576 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000014577 return;
14578
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000014579 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000014580 Loc = Op->getOperatorLoc();
Fariborz Jahanianf07bcc52012-08-29 17:17:11 +000014581 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14582 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14583 else {
John McCalld5707ab2009-10-12 21:59:07 +000014584 // Not an assignment.
14585 return;
14586 }
14587
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000014588 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000014589
Daniel Dunbar62ee6412012-03-09 18:35:03 +000014590 SourceLocation Open = E->getLocStart();
Craig Topper07fa1762015-11-15 02:31:46 +000014591 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000014592 Diag(Loc, diag::note_condition_assign_silence)
14593 << FixItHint::CreateInsertion(Open, "(")
14594 << FixItHint::CreateInsertion(Close, ")");
14595
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000014596 if (IsOrAssign)
14597 Diag(Loc, diag::note_condition_or_assign_to_comparison)
14598 << FixItHint::CreateReplacement(Loc, "!=");
14599 else
14600 Diag(Loc, diag::note_condition_assign_to_comparison)
14601 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +000014602}
14603
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000014604/// \brief Redundant parentheses over an equality comparison can indicate
14605/// that the user intended an assignment used as condition.
Richard Trieuba63ce62011-09-09 01:45:06 +000014606void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000014607 // Don't warn if the parens came from a macro.
Richard Trieuba63ce62011-09-09 01:45:06 +000014608 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000014609 if (parenLoc.isInvalid() || parenLoc.isMacroID())
14610 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000014611 // Don't warn for dependent expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +000014612 if (ParenE->isTypeDependent())
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000014613 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000014614
Richard Trieuba63ce62011-09-09 01:45:06 +000014615 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000014616
14617 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000014618 if (opE->getOpcode() == BO_EQ &&
14619 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14620 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000014621 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000014622
Ted Kremenekae022092011-02-02 02:20:30 +000014623 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +000014624 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +000014625 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar62ee6412012-03-09 18:35:03 +000014626 << FixItHint::CreateRemoval(ParenERange.getBegin())
14627 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000014628 Diag(Loc, diag::note_equality_comparison_to_assign)
14629 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000014630 }
14631}
14632
Richard Smithb130fe72016-06-23 19:16:49 +000014633ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
14634 bool IsConstexpr) {
John McCalld5707ab2009-10-12 21:59:07 +000014635 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000014636 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14637 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000014638
John McCall0009fcc2011-04-26 20:42:42 +000014639 ExprResult result = CheckPlaceholderExpr(E);
14640 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014641 E = result.get();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000014642
John McCall0009fcc2011-04-26 20:42:42 +000014643 if (!E->isTypeDependent()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000014644 if (getLangOpts().CPlusPlus)
Richard Smithb130fe72016-06-23 19:16:49 +000014645 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
John McCall34376a62010-12-04 03:47:34 +000014646
John Wiegley01296292011-04-08 18:41:53 +000014647 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14648 if (ERes.isInvalid())
14649 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014650 E = ERes.get();
John McCall29cb2fd2010-12-04 06:09:13 +000014651
14652 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000014653 if (!T->isScalarType()) { // C99 6.8.4.1p1
14654 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14655 << T << E->getSourceRange();
14656 return ExprError();
14657 }
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000014658 CheckBoolLikeConversion(E, Loc);
John McCalld5707ab2009-10-12 21:59:07 +000014659 }
14660
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000014661 return E;
John McCalld5707ab2009-10-12 21:59:07 +000014662}
Douglas Gregore60e41a2010-05-06 17:25:47 +000014663
Richard Smith03a4aa32016-06-23 19:02:52 +000014664Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
14665 Expr *SubExpr, ConditionKind CK) {
14666 // Empty conditions are valid in for-statements.
Richard Trieuba63ce62011-09-09 01:45:06 +000014667 if (!SubExpr)
Richard Smith03a4aa32016-06-23 19:02:52 +000014668 return ConditionResult();
John Wiegley01296292011-04-08 18:41:53 +000014669
Richard Smith03a4aa32016-06-23 19:02:52 +000014670 ExprResult Cond;
14671 switch (CK) {
14672 case ConditionKind::Boolean:
14673 Cond = CheckBooleanCondition(Loc, SubExpr);
14674 break;
14675
Richard Smithb130fe72016-06-23 19:16:49 +000014676 case ConditionKind::ConstexprIf:
14677 Cond = CheckBooleanCondition(Loc, SubExpr, true);
14678 break;
14679
Richard Smith03a4aa32016-06-23 19:02:52 +000014680 case ConditionKind::Switch:
14681 Cond = CheckSwitchCondition(Loc, SubExpr);
14682 break;
14683 }
14684 if (Cond.isInvalid())
14685 return ConditionError();
14686
Richard Smithcc4bb632016-06-30 18:36:34 +000014687 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
14688 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
14689 if (!FullExpr.get())
14690 return ConditionError();
14691
14692 return ConditionResult(*this, nullptr, FullExpr,
Richard Smithb130fe72016-06-23 19:16:49 +000014693 CK == ConditionKind::ConstexprIf);
Douglas Gregore60e41a2010-05-06 17:25:47 +000014694}
John McCall36e7fe32010-10-12 00:20:44 +000014695
John McCall31996342011-04-07 08:22:57 +000014696namespace {
John McCall2979fe02011-04-12 00:42:48 +000014697 /// A visitor for rebuilding a call to an __unknown_any expression
14698 /// to have an appropriate type.
14699 struct RebuildUnknownAnyFunction
14700 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14701
14702 Sema &S;
14703
14704 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14705
14706 ExprResult VisitStmt(Stmt *S) {
14707 llvm_unreachable("unexpected statement!");
John McCall2979fe02011-04-12 00:42:48 +000014708 }
14709
Richard Trieu10162ab2011-09-09 03:59:41 +000014710 ExprResult VisitExpr(Expr *E) {
14711 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14712 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000014713 return ExprError();
14714 }
14715
14716 /// Rebuild an expression which simply semantically wraps another
14717 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000014718 template <class T> ExprResult rebuildSugarExpr(T *E) {
14719 ExprResult SubResult = Visit(E->getSubExpr());
14720 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000014721
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014722 Expr *SubExpr = SubResult.get();
Richard Trieu10162ab2011-09-09 03:59:41 +000014723 E->setSubExpr(SubExpr);
14724 E->setType(SubExpr->getType());
14725 E->setValueKind(SubExpr->getValueKind());
14726 assert(E->getObjectKind() == OK_Ordinary);
14727 return E;
John McCall2979fe02011-04-12 00:42:48 +000014728 }
14729
Richard Trieu10162ab2011-09-09 03:59:41 +000014730 ExprResult VisitParenExpr(ParenExpr *E) {
14731 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000014732 }
14733
Richard Trieu10162ab2011-09-09 03:59:41 +000014734 ExprResult VisitUnaryExtension(UnaryOperator *E) {
14735 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000014736 }
14737
Richard Trieu10162ab2011-09-09 03:59:41 +000014738 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14739 ExprResult SubResult = Visit(E->getSubExpr());
14740 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000014741
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014742 Expr *SubExpr = SubResult.get();
Richard Trieu10162ab2011-09-09 03:59:41 +000014743 E->setSubExpr(SubExpr);
14744 E->setType(S.Context.getPointerType(SubExpr->getType()));
14745 assert(E->getValueKind() == VK_RValue);
14746 assert(E->getObjectKind() == OK_Ordinary);
14747 return E;
John McCall2979fe02011-04-12 00:42:48 +000014748 }
14749
Richard Trieu10162ab2011-09-09 03:59:41 +000014750 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14751 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000014752
Richard Trieu10162ab2011-09-09 03:59:41 +000014753 E->setType(VD->getType());
John McCall2979fe02011-04-12 00:42:48 +000014754
Richard Trieu10162ab2011-09-09 03:59:41 +000014755 assert(E->getValueKind() == VK_RValue);
David Blaikiebbafb8a2012-03-11 07:00:24 +000014756 if (S.getLangOpts().CPlusPlus &&
Richard Trieu10162ab2011-09-09 03:59:41 +000014757 !(isa<CXXMethodDecl>(VD) &&
14758 cast<CXXMethodDecl>(VD)->isInstance()))
14759 E->setValueKind(VK_LValue);
John McCall2979fe02011-04-12 00:42:48 +000014760
Richard Trieu10162ab2011-09-09 03:59:41 +000014761 return E;
John McCall2979fe02011-04-12 00:42:48 +000014762 }
14763
Richard Trieu10162ab2011-09-09 03:59:41 +000014764 ExprResult VisitMemberExpr(MemberExpr *E) {
14765 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000014766 }
14767
Richard Trieu10162ab2011-09-09 03:59:41 +000014768 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14769 return resolveDecl(E, E->getDecl());
John McCall2979fe02011-04-12 00:42:48 +000014770 }
14771 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000014772}
John McCall2979fe02011-04-12 00:42:48 +000014773
14774/// Given a function expression of unknown-any type, try to rebuild it
14775/// to have a function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000014776static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14777 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14778 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014779 return S.DefaultFunctionArrayConversion(Result.get());
John McCall2979fe02011-04-12 00:42:48 +000014780}
14781
14782namespace {
John McCall2d2e8702011-04-11 07:02:50 +000014783 /// A visitor for rebuilding an expression of type __unknown_anytype
14784 /// into one which resolves the type directly on the referring
14785 /// expression. Strict preservation of the original source
14786 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +000014787 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +000014788 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +000014789
14790 Sema &S;
14791
14792 /// The current destination type.
14793 QualType DestType;
14794
Richard Trieu10162ab2011-09-09 03:59:41 +000014795 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14796 : S(S), DestType(CastType) {}
John McCall31996342011-04-07 08:22:57 +000014797
John McCall39439732011-04-09 22:50:59 +000014798 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +000014799 llvm_unreachable("unexpected statement!");
John McCall31996342011-04-07 08:22:57 +000014800 }
14801
Richard Trieu10162ab2011-09-09 03:59:41 +000014802 ExprResult VisitExpr(Expr *E) {
14803 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14804 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000014805 return ExprError();
John McCall31996342011-04-07 08:22:57 +000014806 }
14807
Richard Trieu10162ab2011-09-09 03:59:41 +000014808 ExprResult VisitCallExpr(CallExpr *E);
14809 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall2d2e8702011-04-11 07:02:50 +000014810
John McCall39439732011-04-09 22:50:59 +000014811 /// Rebuild an expression which simply semantically wraps another
14812 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000014813 template <class T> ExprResult rebuildSugarExpr(T *E) {
14814 ExprResult SubResult = Visit(E->getSubExpr());
14815 if (SubResult.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014816 Expr *SubExpr = SubResult.get();
Richard Trieu10162ab2011-09-09 03:59:41 +000014817 E->setSubExpr(SubExpr);
14818 E->setType(SubExpr->getType());
14819 E->setValueKind(SubExpr->getValueKind());
14820 assert(E->getObjectKind() == OK_Ordinary);
14821 return E;
John McCall39439732011-04-09 22:50:59 +000014822 }
John McCall31996342011-04-07 08:22:57 +000014823
Richard Trieu10162ab2011-09-09 03:59:41 +000014824 ExprResult VisitParenExpr(ParenExpr *E) {
14825 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000014826 }
14827
Richard Trieu10162ab2011-09-09 03:59:41 +000014828 ExprResult VisitUnaryExtension(UnaryOperator *E) {
14829 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000014830 }
14831
Richard Trieu10162ab2011-09-09 03:59:41 +000014832 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14833 const PointerType *Ptr = DestType->getAs<PointerType>();
14834 if (!Ptr) {
14835 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14836 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000014837 return ExprError();
14838 }
Akira Hatanakaf7d563c72016-11-19 00:13:03 +000014839
14840 if (isa<CallExpr>(E->getSubExpr())) {
14841 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
14842 << E->getSourceRange();
14843 return ExprError();
14844 }
14845
Richard Trieu10162ab2011-09-09 03:59:41 +000014846 assert(E->getValueKind() == VK_RValue);
14847 assert(E->getObjectKind() == OK_Ordinary);
14848 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +000014849
14850 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu10162ab2011-09-09 03:59:41 +000014851 DestType = Ptr->getPointeeType();
14852 ExprResult SubResult = Visit(E->getSubExpr());
14853 if (SubResult.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014854 E->setSubExpr(SubResult.get());
Richard Trieu10162ab2011-09-09 03:59:41 +000014855 return E;
John McCall2979fe02011-04-12 00:42:48 +000014856 }
14857
Richard Trieu10162ab2011-09-09 03:59:41 +000014858 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCall39439732011-04-09 22:50:59 +000014859
Richard Trieu10162ab2011-09-09 03:59:41 +000014860 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCall39439732011-04-09 22:50:59 +000014861
Richard Trieu10162ab2011-09-09 03:59:41 +000014862 ExprResult VisitMemberExpr(MemberExpr *E) {
14863 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000014864 }
John McCall39439732011-04-09 22:50:59 +000014865
Richard Trieu10162ab2011-09-09 03:59:41 +000014866 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14867 return resolveDecl(E, E->getDecl());
John McCall31996342011-04-07 08:22:57 +000014868 }
14869 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000014870}
John McCall31996342011-04-07 08:22:57 +000014871
John McCall2d2e8702011-04-11 07:02:50 +000014872/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu10162ab2011-09-09 03:59:41 +000014873ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
14874 Expr *CalleeExpr = E->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000014875
14876 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +000014877 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +000014878 FK_FunctionPointer,
14879 FK_BlockPointer
14880 };
14881
Richard Trieu10162ab2011-09-09 03:59:41 +000014882 FnKind Kind;
14883 QualType CalleeType = CalleeExpr->getType();
14884 if (CalleeType == S.Context.BoundMemberTy) {
14885 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
14886 Kind = FK_MemberFunction;
14887 CalleeType = Expr::findBoundMemberType(CalleeExpr);
14888 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
14889 CalleeType = Ptr->getPointeeType();
14890 Kind = FK_FunctionPointer;
John McCall2d2e8702011-04-11 07:02:50 +000014891 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000014892 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
14893 Kind = FK_BlockPointer;
John McCall2d2e8702011-04-11 07:02:50 +000014894 }
Richard Trieu10162ab2011-09-09 03:59:41 +000014895 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall2d2e8702011-04-11 07:02:50 +000014896
14897 // Verify that this is a legal result type of a function.
14898 if (DestType->isArrayType() || DestType->isFunctionType()) {
14899 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu10162ab2011-09-09 03:59:41 +000014900 if (Kind == FK_BlockPointer)
John McCall2d2e8702011-04-11 07:02:50 +000014901 diagID = diag::err_block_returning_array_function;
14902
Richard Trieu10162ab2011-09-09 03:59:41 +000014903 S.Diag(E->getExprLoc(), diagID)
John McCall2d2e8702011-04-11 07:02:50 +000014904 << DestType->isFunctionType() << DestType;
14905 return ExprError();
14906 }
14907
14908 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu10162ab2011-09-09 03:59:41 +000014909 E->setType(DestType.getNonLValueExprType(S.Context));
14910 E->setValueKind(Expr::getValueKindForType(DestType));
14911 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000014912
14913 // Rebuild the function type, replacing the result type with DestType.
John McCall611d9b62013-06-27 22:43:24 +000014914 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
14915 if (Proto) {
14916 // __unknown_anytype(...) is a special case used by the debugger when
14917 // it has no idea what a function's signature is.
14918 //
14919 // We want to build this call essentially under the K&R
14920 // unprototyped rules, but making a FunctionNoProtoType in C++
14921 // would foul up all sorts of assumptions. However, we cannot
14922 // simply pass all arguments as variadic arguments, nor can we
14923 // portably just call the function under a non-variadic type; see
14924 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
14925 // However, it turns out that in practice it is generally safe to
14926 // call a function declared as "A foo(B,C,D);" under the prototype
14927 // "A foo(B,C,D,...);". The only known exception is with the
14928 // Windows ABI, where any variadic function is implicitly cdecl
14929 // regardless of its normal CC. Therefore we change the parameter
14930 // types to match the types of the arguments.
14931 //
14932 // This is a hack, but it is far superior to moving the
14933 // corresponding target-specific code from IR-gen to Sema/AST.
14934
Alp Toker9cacbab2014-01-20 20:26:09 +000014935 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
John McCall611d9b62013-06-27 22:43:24 +000014936 SmallVector<QualType, 8> ArgTypes;
14937 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
14938 ArgTypes.reserve(E->getNumArgs());
14939 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
14940 Expr *Arg = E->getArg(i);
14941 QualType ArgType = Arg->getType();
14942 if (E->isLValue()) {
14943 ArgType = S.Context.getLValueReferenceType(ArgType);
14944 } else if (E->isXValue()) {
14945 ArgType = S.Context.getRValueReferenceType(ArgType);
14946 }
14947 ArgTypes.push_back(ArgType);
14948 }
14949 ParamTypes = ArgTypes;
14950 }
14951 DestType = S.Context.getFunctionType(DestType, ParamTypes,
Reid Kleckner896b32f2013-06-10 20:51:09 +000014952 Proto->getExtProtoInfo());
John McCall611d9b62013-06-27 22:43:24 +000014953 } else {
John McCall2d2e8702011-04-11 07:02:50 +000014954 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000014955 FnType->getExtInfo());
John McCall611d9b62013-06-27 22:43:24 +000014956 }
John McCall2d2e8702011-04-11 07:02:50 +000014957
14958 // Rebuild the appropriate pointer-to-function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000014959 switch (Kind) {
John McCall4adb38c2011-04-27 00:36:17 +000014960 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +000014961 // Nothing to do.
14962 break;
14963
14964 case FK_FunctionPointer:
14965 DestType = S.Context.getPointerType(DestType);
14966 break;
14967
14968 case FK_BlockPointer:
14969 DestType = S.Context.getBlockPointerType(DestType);
14970 break;
14971 }
14972
14973 // Finally, we can recurse.
Richard Trieu10162ab2011-09-09 03:59:41 +000014974 ExprResult CalleeResult = Visit(CalleeExpr);
14975 if (!CalleeResult.isUsable()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014976 E->setCallee(CalleeResult.get());
John McCall2d2e8702011-04-11 07:02:50 +000014977
14978 // Bind a temporary if necessary.
Richard Trieu10162ab2011-09-09 03:59:41 +000014979 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000014980}
14981
Richard Trieu10162ab2011-09-09 03:59:41 +000014982ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000014983 // Verify that this is a legal result type of a call.
14984 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu10162ab2011-09-09 03:59:41 +000014985 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall2979fe02011-04-12 00:42:48 +000014986 << DestType->isFunctionType() << DestType;
14987 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000014988 }
14989
John McCall3f4138c2011-07-13 17:56:40 +000014990 // Rewrite the method result type if available.
Richard Trieu10162ab2011-09-09 03:59:41 +000014991 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +000014992 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
14993 Method->setReturnType(DestType);
John McCall3f4138c2011-07-13 17:56:40 +000014994 }
John McCall2979fe02011-04-12 00:42:48 +000014995
John McCall2d2e8702011-04-11 07:02:50 +000014996 // Change the type of the message.
Richard Trieu10162ab2011-09-09 03:59:41 +000014997 E->setType(DestType.getNonReferenceType());
14998 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000014999
Richard Trieu10162ab2011-09-09 03:59:41 +000015000 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000015001}
15002
Richard Trieu10162ab2011-09-09 03:59:41 +000015003ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000015004 // The only case we should ever see here is a function-to-pointer decay.
Sean Callanan2db103c2012-03-06 23:12:57 +000015005 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanan12495112012-03-06 21:34:12 +000015006 assert(E->getValueKind() == VK_RValue);
15007 assert(E->getObjectKind() == OK_Ordinary);
15008
15009 E->setType(DestType);
15010
15011 // Rebuild the sub-expression as the pointee (function) type.
15012 DestType = DestType->castAs<PointerType>()->getPointeeType();
15013
15014 ExprResult Result = Visit(E->getSubExpr());
15015 if (!Result.isUsable()) return ExprError();
15016
Nikola Smiljanic01a75982014-05-29 10:55:11 +000015017 E->setSubExpr(Result.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000015018 return E;
Sean Callanan2db103c2012-03-06 23:12:57 +000015019 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanan12495112012-03-06 21:34:12 +000015020 assert(E->getValueKind() == VK_RValue);
15021 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000015022
Sean Callanan12495112012-03-06 21:34:12 +000015023 assert(isa<BlockPointerType>(E->getType()));
John McCall2979fe02011-04-12 00:42:48 +000015024
Sean Callanan12495112012-03-06 21:34:12 +000015025 E->setType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000015026
Sean Callanan12495112012-03-06 21:34:12 +000015027 // The sub-expression has to be a lvalue reference, so rebuild it as such.
15028 DestType = S.Context.getLValueReferenceType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000015029
Sean Callanan12495112012-03-06 21:34:12 +000015030 ExprResult Result = Visit(E->getSubExpr());
15031 if (!Result.isUsable()) return ExprError();
15032
Nikola Smiljanic01a75982014-05-29 10:55:11 +000015033 E->setSubExpr(Result.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000015034 return E;
Sean Callanan2db103c2012-03-06 23:12:57 +000015035 } else {
Sean Callanan12495112012-03-06 21:34:12 +000015036 llvm_unreachable("Unhandled cast type!");
15037 }
John McCall2d2e8702011-04-11 07:02:50 +000015038}
15039
Richard Trieu10162ab2011-09-09 03:59:41 +000015040ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
15041 ExprValueKind ValueKind = VK_LValue;
15042 QualType Type = DestType;
John McCall2d2e8702011-04-11 07:02:50 +000015043
15044 // We know how to make this work for certain kinds of decls:
15045
15046 // - functions
Richard Trieu10162ab2011-09-09 03:59:41 +000015047 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
15048 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
15049 DestType = Ptr->getPointeeType();
15050 ExprResult Result = resolveDecl(E, VD);
15051 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000015052 return S.ImpCastExprToType(Result.get(), Type,
John McCall9a877fe2011-08-10 04:12:23 +000015053 CK_FunctionToPointerDecay, VK_RValue);
15054 }
15055
Richard Trieu10162ab2011-09-09 03:59:41 +000015056 if (!Type->isFunctionType()) {
15057 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
15058 << VD << E->getSourceRange();
John McCall9a877fe2011-08-10 04:12:23 +000015059 return ExprError();
15060 }
Fariborz Jahaniana29986c2014-11-11 16:56:21 +000015061 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
15062 // We must match the FunctionDecl's type to the hack introduced in
15063 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
15064 // type. See the lengthy commentary in that routine.
15065 QualType FDT = FD->getType();
15066 const FunctionType *FnType = FDT->castAs<FunctionType>();
15067 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
15068 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
15069 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
15070 SourceLocation Loc = FD->getLocation();
15071 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
15072 FD->getDeclContext(),
15073 Loc, Loc, FD->getNameInfo().getName(),
15074 DestType, FD->getTypeSourceInfo(),
15075 SC_None, false/*isInlineSpecified*/,
15076 FD->hasPrototype(),
15077 false/*isConstexprSpecified*/);
15078
15079 if (FD->getQualifier())
15080 NewFD->setQualifierInfo(FD->getQualifierLoc());
15081
15082 SmallVector<ParmVarDecl*, 16> Params;
15083 for (const auto &AI : FT->param_types()) {
15084 ParmVarDecl *Param =
15085 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
15086 Param->setScopeInfo(0, Params.size());
15087 Params.push_back(Param);
15088 }
15089 NewFD->setParams(Params);
15090 DRE->setDecl(NewFD);
15091 VD = DRE->getDecl();
15092 }
15093 }
John McCall2d2e8702011-04-11 07:02:50 +000015094
Richard Trieu10162ab2011-09-09 03:59:41 +000015095 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
15096 if (MD->isInstance()) {
15097 ValueKind = VK_RValue;
15098 Type = S.Context.BoundMemberTy;
John McCall4adb38c2011-04-27 00:36:17 +000015099 }
15100
John McCall2d2e8702011-04-11 07:02:50 +000015101 // Function references aren't l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000015102 if (!S.getLangOpts().CPlusPlus)
Richard Trieu10162ab2011-09-09 03:59:41 +000015103 ValueKind = VK_RValue;
John McCall2d2e8702011-04-11 07:02:50 +000015104
15105 // - variables
Richard Trieu10162ab2011-09-09 03:59:41 +000015106 } else if (isa<VarDecl>(VD)) {
15107 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
15108 Type = RefTy->getPointeeType();
15109 } else if (Type->isFunctionType()) {
15110 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
15111 << VD << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000015112 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000015113 }
15114
15115 // - nothing else
15116 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000015117 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
15118 << VD << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000015119 return ExprError();
15120 }
15121
John McCall611d9b62013-06-27 22:43:24 +000015122 // Modifying the declaration like this is friendly to IR-gen but
15123 // also really dangerous.
Richard Trieu10162ab2011-09-09 03:59:41 +000015124 VD->setType(DestType);
15125 E->setType(Type);
15126 E->setValueKind(ValueKind);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000015127 return E;
John McCall2d2e8702011-04-11 07:02:50 +000015128}
15129
John McCall31996342011-04-07 08:22:57 +000015130/// Check a cast of an unknown-any type. We intentionally only
15131/// trigger this for C-style casts.
Richard Trieuba63ce62011-09-09 01:45:06 +000015132ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
15133 Expr *CastExpr, CastKind &CastKind,
15134 ExprValueKind &VK, CXXCastPath &Path) {
Douglas Gregor0fc3a002016-02-03 19:13:08 +000015135 // The type we're casting to must be either void or complete.
15136 if (!CastType->isVoidType() &&
15137 RequireCompleteType(TypeRange.getBegin(), CastType,
15138 diag::err_typecheck_cast_to_incomplete))
15139 return ExprError();
15140
John McCall31996342011-04-07 08:22:57 +000015141 // Rewrite the casted expression from scratch.
Richard Trieuba63ce62011-09-09 01:45:06 +000015142 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCall39439732011-04-09 22:50:59 +000015143 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000015144
Nikola Smiljanic01a75982014-05-29 10:55:11 +000015145 CastExpr = result.get();
Richard Trieuba63ce62011-09-09 01:45:06 +000015146 VK = CastExpr->getValueKind();
15147 CastKind = CK_NoOp;
John McCall39439732011-04-09 22:50:59 +000015148
Richard Trieuba63ce62011-09-09 01:45:06 +000015149 return CastExpr;
John McCall31996342011-04-07 08:22:57 +000015150}
15151
Douglas Gregord8fb1e32011-12-01 01:37:36 +000015152ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15153 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15154}
15155
John McCallcc5788c2013-03-04 07:34:02 +000015156ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15157 Expr *arg, QualType &paramType) {
15158 // If the syntactic form of the argument is not an explicit cast of
15159 // any sort, just do default argument promotion.
15160 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15161 if (!castArg) {
15162 ExprResult result = DefaultArgumentPromotion(arg);
15163 if (result.isInvalid()) return ExprError();
15164 paramType = result.get()->getType();
15165 return result;
John McCallea0a39e2012-11-14 00:49:39 +000015166 }
15167
John McCallcc5788c2013-03-04 07:34:02 +000015168 // Otherwise, use the type that was written in the explicit cast.
15169 assert(!arg->hasPlaceholderType());
15170 paramType = castArg->getTypeAsWritten();
15171
15172 // Copy-initialize a parameter of that type.
15173 InitializedEntity entity =
15174 InitializedEntity::InitializeParameter(Context, paramType,
15175 /*consumed*/ false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000015176 return PerformCopyInitialization(entity, callLoc, arg);
John McCallea0a39e2012-11-14 00:49:39 +000015177}
15178
Richard Trieuba63ce62011-09-09 01:45:06 +000015179static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
15180 Expr *orig = E;
John McCall2d2e8702011-04-11 07:02:50 +000015181 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000015182 while (true) {
Richard Trieuba63ce62011-09-09 01:45:06 +000015183 E = E->IgnoreParenImpCasts();
15184 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15185 E = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000015186 diagID = diag::err_uncasted_call_of_unknown_any;
15187 } else {
John McCall31996342011-04-07 08:22:57 +000015188 break;
John McCall2d2e8702011-04-11 07:02:50 +000015189 }
John McCall31996342011-04-07 08:22:57 +000015190 }
15191
John McCall2d2e8702011-04-11 07:02:50 +000015192 SourceLocation loc;
15193 NamedDecl *d;
Richard Trieuba63ce62011-09-09 01:45:06 +000015194 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000015195 loc = ref->getLocation();
15196 d = ref->getDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000015197 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000015198 loc = mem->getMemberLoc();
15199 d = mem->getMemberDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000015200 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000015201 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidisa6011e22011-10-03 06:36:51 +000015202 loc = msg->getSelectorStartLoc();
John McCall2d2e8702011-04-11 07:02:50 +000015203 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000015204 if (!d) {
15205 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15206 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15207 << orig->getSourceRange();
15208 return ExprError();
15209 }
John McCall2d2e8702011-04-11 07:02:50 +000015210 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +000015211 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15212 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000015213 return ExprError();
15214 }
15215
15216 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000015217
15218 // Never recoverable.
15219 return ExprError();
15220}
15221
John McCall36e7fe32010-10-12 00:20:44 +000015222/// Check for operands with placeholder types and complain if found.
15223/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000015224ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
Kaelyn Takata15867822014-11-21 18:48:04 +000015225 if (!getLangOpts().CPlusPlus) {
15226 // C cannot handle TypoExpr nodes on either side of a binop because it
15227 // doesn't handle dependent types properly, so make sure any TypoExprs have
15228 // been dealt with before checking the operands.
15229 ExprResult Result = CorrectDelayedTyposInExpr(E);
15230 if (!Result.isUsable()) return ExprError();
15231 E = Result.get();
15232 }
15233
John McCall4124c492011-10-17 18:40:02 +000015234 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000015235 if (!placeholderType) return E;
John McCall4124c492011-10-17 18:40:02 +000015236
15237 switch (placeholderType->getKind()) {
John McCall36e7fe32010-10-12 00:20:44 +000015238
John McCall31996342011-04-07 08:22:57 +000015239 // Overloaded expressions.
John McCall4124c492011-10-17 18:40:02 +000015240 case BuiltinType::Overload: {
John McCall50a2c2c2011-10-11 23:14:30 +000015241 // Try to resolve a single function template specialization.
15242 // This is obligatory.
George Burgess IVbeca4a32016-06-08 00:34:22 +000015243 ExprResult Result = E;
15244 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
15245 return Result;
15246
15247 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
15248 // leaves Result unchanged on failure.
15249 Result = E;
15250 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
15251 return Result;
John McCall50a2c2c2011-10-11 23:14:30 +000015252
15253 // If that failed, try to recover with a call.
George Burgess IVbeca4a32016-06-08 00:34:22 +000015254 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
15255 /*complain*/ true);
15256 return Result;
John McCall50a2c2c2011-10-11 23:14:30 +000015257 }
John McCall31996342011-04-07 08:22:57 +000015258
John McCall0009fcc2011-04-26 20:42:42 +000015259 // Bound member functions.
John McCall4124c492011-10-17 18:40:02 +000015260 case BuiltinType::BoundMember: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000015261 ExprResult result = E;
David Majnemerced8bdf2015-02-25 17:36:15 +000015262 const Expr *BME = E->IgnoreParens();
15263 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15264 // Try to give a nicer diagnostic if it is a bound member that we recognize.
15265 if (isa<CXXPseudoDestructorExpr>(BME)) {
15266 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15267 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15268 if (ME->getMemberNameInfo().getName().getNameKind() ==
15269 DeclarationName::CXXDestructorName)
15270 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15271 }
15272 tryToRecoverWithCall(result, PD,
John McCall50a2c2c2011-10-11 23:14:30 +000015273 /*complain*/ true);
15274 return result;
John McCall4124c492011-10-17 18:40:02 +000015275 }
15276
15277 // ARC unbridged casts.
15278 case BuiltinType::ARCUnbridgedCast: {
15279 Expr *realCast = stripARCUnbridgedCast(E);
15280 diagnoseARCUnbridgedCast(realCast);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000015281 return realCast;
John McCall4124c492011-10-17 18:40:02 +000015282 }
John McCall0009fcc2011-04-26 20:42:42 +000015283
John McCall31996342011-04-07 08:22:57 +000015284 // Expressions of unknown type.
John McCall4124c492011-10-17 18:40:02 +000015285 case BuiltinType::UnknownAny:
John McCall31996342011-04-07 08:22:57 +000015286 return diagnoseUnknownAnyExpr(*this, E);
15287
John McCall526ab472011-10-25 17:37:35 +000015288 // Pseudo-objects.
15289 case BuiltinType::PseudoObject:
15290 return checkPseudoObjectRValue(E);
15291
Reid Klecknerf392ec62014-07-11 23:54:29 +000015292 case BuiltinType::BuiltinFn: {
15293 // Accept __noop without parens by implicitly converting it to a call expr.
15294 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15295 if (DRE) {
15296 auto *FD = cast<FunctionDecl>(DRE->getDecl());
15297 if (FD->getBuiltinID() == Builtin::BI__noop) {
15298 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15299 CK_BuiltinFnToFnPtr).get();
15300 return new (Context) CallExpr(Context, E, None, Context.IntTy,
15301 VK_RValue, SourceLocation());
15302 }
15303 }
15304
Eli Friedman34866c72012-08-31 00:14:07 +000015305 Diag(E->getLocStart(), diag::err_builtin_fn_use);
15306 return ExprError();
Reid Klecknerf392ec62014-07-11 23:54:29 +000015307 }
Eli Friedman34866c72012-08-31 00:14:07 +000015308
Alexey Bataev1a3320e2015-08-25 14:24:04 +000015309 // Expressions of unknown type.
15310 case BuiltinType::OMPArraySection:
15311 Diag(E->getLocStart(), diag::err_omp_array_section_use);
15312 return ExprError();
15313
John McCalle314e272011-10-18 21:02:43 +000015314 // Everything else should be impossible.
Alexey Bader954ba212016-04-08 13:40:33 +000015315#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
John McCalle314e272011-10-18 21:02:43 +000015316 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +000015317#include "clang/Basic/OpenCLImageTypes.def"
Alexey Bader954ba212016-04-08 13:40:33 +000015318#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
John McCalle314e272011-10-18 21:02:43 +000015319#define PLACEHOLDER_TYPE(Id, SingletonId)
15320#include "clang/AST/BuiltinTypes.def"
John McCall4124c492011-10-17 18:40:02 +000015321 break;
15322 }
15323
15324 llvm_unreachable("invalid placeholder type!");
John McCall36e7fe32010-10-12 00:20:44 +000015325}
Richard Trieu2c850c02011-04-21 21:44:26 +000015326
Richard Trieuba63ce62011-09-09 01:45:06 +000015327bool Sema::CheckCaseExpression(Expr *E) {
15328 if (E->isTypeDependent())
Richard Trieu2c850c02011-04-21 21:44:26 +000015329 return true;
Richard Trieuba63ce62011-09-09 01:45:06 +000015330 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15331 return E->getType()->isIntegralOrEnumerationType();
Richard Trieu2c850c02011-04-21 21:44:26 +000015332 return false;
15333}
Ted Kremeneke65b0862012-03-06 20:05:56 +000015334
15335/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15336ExprResult
15337Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15338 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15339 "Unknown Objective-C Boolean value!");
Fariborz Jahanianf2578572012-08-30 18:49:41 +000015340 QualType BoolT = Context.ObjCBuiltinBoolTy;
15341 if (!Context.getBOOLDecl()) {
Fariborz Jahanianeab17302012-10-16 17:08:11 +000015342 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
Fariborz Jahanianf2578572012-08-30 18:49:41 +000015343 Sema::LookupOrdinaryName);
Fariborz Jahanian379e5362012-10-16 16:21:20 +000015344 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
Fariborz Jahanianf2578572012-08-30 18:49:41 +000015345 NamedDecl *ND = Result.getFoundDecl();
15346 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
15347 Context.setBOOLDecl(TD);
15348 }
15349 }
15350 if (Context.getBOOLDecl())
15351 BoolT = Context.getBOOLType();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000015352 return new (Context)
15353 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
Ted Kremeneke65b0862012-03-06 20:05:56 +000015354}
Erik Pilkington29099de2016-07-16 00:35:23 +000015355
15356ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15357 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15358 SourceLocation RParen) {
15359
15360 StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15361
15362 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15363 [&](const AvailabilitySpec &Spec) {
15364 return Spec.getPlatform() == Platform;
15365 });
15366
15367 VersionTuple Version;
15368 if (Spec != AvailSpecs.end())
15369 Version = Spec->getVersion();
Erik Pilkington29099de2016-07-16 00:35:23 +000015370
15371 return new (Context)
15372 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
15373}