blob: 23bc4831b1bb8aaea348e79c1a33386ac352b02e [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- SemaExprCXX.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 Lattner29375652006-12-04 18:06:35 +00007//
8//===----------------------------------------------------------------------===//
James Dennett84053fb2012-06-22 05:14:59 +00009///
10/// \file
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011/// Implements semantic analysis for C++ expressions.
James Dennett84053fb2012-06-22 05:14:59 +000012///
13//===----------------------------------------------------------------------===//
Chris Lattner29375652006-12-04 18:06:35 +000014
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Kaelyn Takata6c759512014-10-27 18:07:37 +000016#include "TreeTransform.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "TypeLocBuilder.h"
Steve Naroffaac94152007-08-25 14:02:58 +000018#include "clang/AST/ASTContext.h"
Faisal Vali47d9ed42014-05-30 04:39:37 +000019#include "clang/AST/ASTLambda.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/AST/CharUnits.h"
John McCallde6836a2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000023#include "clang/AST/ExprCXX.h"
Fariborz Jahanian1d446082010-06-16 18:56:04 +000024#include "clang/AST/ExprObjC.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000025#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000026#include "clang/AST/TypeLoc.h"
Akira Hatanaka3e40c302017-07-19 17:17:50 +000027#include "clang/Basic/AlignedAllocation.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000029#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000030#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/Initialization.h"
33#include "clang/Sema/Lookup.h"
34#include "clang/Sema/ParsedTemplate.h"
35#include "clang/Sema/Scope.h"
36#include "clang/Sema/ScopeInfo.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000037#include "clang/Sema/SemaLambda.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "clang/Sema/TemplateDeduction.h"
Sebastian Redlb8fc4772012-02-16 12:59:47 +000039#include "llvm/ADT/APInt.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000040#include "llvm/ADT/STLExtras.h"
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +000041#include "llvm/Support/ErrorHandling.h"
Chris Lattner29375652006-12-04 18:06:35 +000042using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000043using namespace sema;
Chris Lattner29375652006-12-04 18:06:35 +000044
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000045/// Handle the result of the special case name lookup for inheriting
Richard Smith7447af42013-03-26 01:15:19 +000046/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
47/// constructor names in member using declarations, even if 'X' is not the
48/// name of the corresponding type.
49ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
50 SourceLocation NameLoc,
51 IdentifierInfo &Name) {
52 NestedNameSpecifier *NNS = SS.getScopeRep();
53
54 // Convert the nested-name-specifier into a type.
55 QualType Type;
56 switch (NNS->getKind()) {
57 case NestedNameSpecifier::TypeSpec:
58 case NestedNameSpecifier::TypeSpecWithTemplate:
59 Type = QualType(NNS->getAsType(), 0);
60 break;
61
62 case NestedNameSpecifier::Identifier:
63 // Strip off the last layer of the nested-name-specifier and build a
64 // typename type for it.
65 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
66 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
67 NNS->getAsIdentifier());
68 break;
69
70 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +000071 case NestedNameSpecifier::Super:
Richard Smith7447af42013-03-26 01:15:19 +000072 case NestedNameSpecifier::Namespace:
73 case NestedNameSpecifier::NamespaceAlias:
74 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
75 }
76
77 // This reference to the type is located entirely at the location of the
78 // final identifier in the qualified-id.
79 return CreateParsedType(Type,
80 Context.getTrivialTypeSourceInfo(Type, NameLoc));
81}
82
Richard Smith715ee072018-06-20 21:58:20 +000083ParsedType Sema::getConstructorName(IdentifierInfo &II,
84 SourceLocation NameLoc,
Richard Smith69bc9aa2018-06-22 19:50:19 +000085 Scope *S, CXXScopeSpec &SS,
86 bool EnteringContext) {
Richard Smith715ee072018-06-20 21:58:20 +000087 CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
88 assert(CurClass && &II == CurClass->getIdentifier() &&
89 "not a constructor name");
90
Richard Smith69bc9aa2018-06-22 19:50:19 +000091 // When naming a constructor as a member of a dependent context (eg, in a
92 // friend declaration or an inherited constructor declaration), form an
93 // unresolved "typename" type.
94 if (CurClass->isDependentContext() && !EnteringContext) {
95 QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II);
96 return ParsedType::make(T);
97 }
98
Richard Smith715ee072018-06-20 21:58:20 +000099 if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
100 return ParsedType();
101
102 // Find the injected-class-name declaration. Note that we make no attempt to
103 // diagnose cases where the injected-class-name is shadowed: the only
104 // declaration that can validly shadow the injected-class-name is a
105 // non-static data member, and if the class contains both a non-static data
106 // member and a constructor then it is ill-formed (we check that in
107 // CheckCompletedCXXClass).
108 CXXRecordDecl *InjectedClassName = nullptr;
109 for (NamedDecl *ND : CurClass->lookup(&II)) {
110 auto *RD = dyn_cast<CXXRecordDecl>(ND);
111 if (RD && RD->isInjectedClassName()) {
112 InjectedClassName = RD;
113 break;
114 }
115 }
Richard Smith2e34bbd2018-08-08 00:42:42 +0000116 if (!InjectedClassName) {
117 if (!CurClass->isInvalidDecl()) {
118 // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
119 // properly. Work around it here for now.
120 Diag(SS.getLastQualifierNameLoc(),
121 diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
122 }
Ilya Biryukova2d58252018-07-04 08:50:12 +0000123 return ParsedType();
Richard Smith2e34bbd2018-08-08 00:42:42 +0000124 }
Richard Smith715ee072018-06-20 21:58:20 +0000125
126 QualType T = Context.getTypeDeclType(InjectedClassName);
127 DiagnoseUseOfDecl(InjectedClassName, NameLoc);
128 MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
129
130 return ParsedType::make(T);
131}
132
John McCallba7bf592010-08-24 05:47:05 +0000133ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000134 IdentifierInfo &II,
John McCallba7bf592010-08-24 05:47:05 +0000135 SourceLocation NameLoc,
136 Scope *S, CXXScopeSpec &SS,
137 ParsedType ObjectTypePtr,
138 bool EnteringContext) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000139 // Determine where to perform name lookup.
140
141 // FIXME: This area of the standard is very messy, and the current
142 // wording is rather unclear about which scopes we search for the
143 // destructor name; see core issues 399 and 555. Issue 399 in
144 // particular shows where the current description of destructor name
145 // lookup is completely out of line with existing practice, e.g.,
146 // this appears to be ill-formed:
147 //
148 // namespace N {
149 // template <typename T> struct S {
150 // ~S();
151 // };
152 // }
153 //
154 // void f(N::S<int>* s) {
155 // s->N::S<int>::~S();
156 // }
157 //
Douglas Gregor46841e12010-02-23 00:15:22 +0000158 // See also PR6358 and PR6359.
Sebastian Redla771d222010-07-07 23:17:38 +0000159 // For this reason, we're currently only doing the C++03 version of this
160 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000161 QualType SearchType;
Craig Topperc3ec1492014-05-26 06:22:03 +0000162 DeclContext *LookupCtx = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000163 bool isDependent = false;
164 bool LookInScope = false;
165
Richard Smith64e033f2015-01-15 00:48:52 +0000166 if (SS.isInvalid())
David Blaikieefdccaa2016-01-15 23:43:34 +0000167 return nullptr;
Richard Smith64e033f2015-01-15 00:48:52 +0000168
Douglas Gregorfe17d252010-02-16 19:09:40 +0000169 // If we have an object type, it's because we are in a
170 // pseudo-destructor-expression or a member access expression, and
171 // we know what type we're looking for.
172 if (ObjectTypePtr)
173 SearchType = GetTypeFromParser(ObjectTypePtr);
174
175 if (SS.isSet()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000176 NestedNameSpecifier *NNS = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000177
Douglas Gregor46841e12010-02-23 00:15:22 +0000178 bool AlreadySearched = false;
179 bool LookAtPrefix = true;
David Majnemere37a6ce2014-05-21 20:19:59 +0000180 // C++11 [basic.lookup.qual]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000181 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redla771d222010-07-07 23:17:38 +0000182 // the type-names are looked up as types in the scope designated by the
David Majnemere37a6ce2014-05-21 20:19:59 +0000183 // nested-name-specifier. Similarly, in a qualified-id of the form:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +0000184 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000185 // nested-name-specifier[opt] class-name :: ~ class-name
Sebastian Redla771d222010-07-07 23:17:38 +0000186 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000187 // the second class-name is looked up in the same scope as the first.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000188 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000189 // Here, we determine whether the code below is permitted to look at the
190 // prefix of the nested-name-specifier.
Sebastian Redla771d222010-07-07 23:17:38 +0000191 DeclContext *DC = computeDeclContext(SS, EnteringContext);
192 if (DC && DC->isFileContext()) {
193 AlreadySearched = true;
194 LookupCtx = DC;
195 isDependent = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000196 } else if (DC && isa<CXXRecordDecl>(DC)) {
Sebastian Redla771d222010-07-07 23:17:38 +0000197 LookAtPrefix = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000198 LookInScope = true;
199 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000200
Sebastian Redla771d222010-07-07 23:17:38 +0000201 // The second case from the C++03 rules quoted further above.
Craig Topperc3ec1492014-05-26 06:22:03 +0000202 NestedNameSpecifier *Prefix = nullptr;
Douglas Gregor46841e12010-02-23 00:15:22 +0000203 if (AlreadySearched) {
204 // Nothing left to do.
205 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
206 CXXScopeSpec PrefixSS;
Douglas Gregor10176412011-02-25 16:07:42 +0000207 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor46841e12010-02-23 00:15:22 +0000208 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
209 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor46841e12010-02-23 00:15:22 +0000210 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000211 LookupCtx = computeDeclContext(SearchType);
212 isDependent = SearchType->isDependentType();
213 } else {
214 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000215 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000216 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000217 } else if (ObjectTypePtr) {
218 // C++ [basic.lookup.classref]p3:
219 // If the unqualified-id is ~type-name, the type-name is looked up
220 // in the context of the entire postfix-expression. If the type T
221 // of the object expression is of a class type C, the type-name is
222 // also looked up in the scope of class C. At least one of the
223 // lookups shall find a name that refers to (possibly
224 // cv-qualified) T.
225 LookupCtx = computeDeclContext(SearchType);
226 isDependent = SearchType->isDependentType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000227 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregorfe17d252010-02-16 19:09:40 +0000228 "Caller should have completed object type");
229
230 LookInScope = true;
231 } else {
232 // Perform lookup into the current scope (only).
233 LookInScope = true;
234 }
235
Craig Topperc3ec1492014-05-26 06:22:03 +0000236 TypeDecl *NonMatchingTypeDecl = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000237 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
238 for (unsigned Step = 0; Step != 2; ++Step) {
239 // Look for the name first in the computed lookup context (if we
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000240 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregorfe17d252010-02-16 19:09:40 +0000241 // we're allowed to look there).
242 Found.clear();
John McCallcb731542017-06-11 20:33:00 +0000243 if (Step == 0 && LookupCtx) {
244 if (RequireCompleteDeclContext(SS, LookupCtx))
245 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000246 LookupQualifiedName(Found, LookupCtx);
John McCallcb731542017-06-11 20:33:00 +0000247 } else if (Step == 1 && LookInScope && S) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000248 LookupName(Found, S);
John McCallcb731542017-06-11 20:33:00 +0000249 } else {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000250 continue;
John McCallcb731542017-06-11 20:33:00 +0000251 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000252
253 // FIXME: Should we be suppressing ambiguities here?
254 if (Found.isAmbiguous())
David Blaikieefdccaa2016-01-15 23:43:34 +0000255 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000256
257 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
258 QualType T = Context.getTypeDeclType(Type);
Nico Weber83a63872014-11-12 04:33:52 +0000259 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000260
261 if (SearchType.isNull() || SearchType->isDependentType() ||
262 Context.hasSameUnqualifiedType(T, SearchType)) {
263 // We found our type!
264
Richard Smithc278c002014-01-22 00:30:17 +0000265 return CreateParsedType(T,
266 Context.getTrivialTypeSourceInfo(T, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000267 }
John Wiegleyb4a9e512011-03-08 08:13:22 +0000268
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000269 if (!SearchType.isNull())
270 NonMatchingTypeDecl = Type;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000271 }
272
273 // If the name that we found is a class template name, and it is
274 // the same name as the template name in the last part of the
275 // nested-name-specifier (if present) or the object type, then
276 // this is the destructor for that class.
277 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000278 // issue 399, for which there isn't even an obvious direction.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000279 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
280 QualType MemberOfType;
281 if (SS.isSet()) {
282 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
283 // Figure out the type of the context, if it has one.
John McCalle78aac42010-03-10 03:28:59 +0000284 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
285 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000286 }
287 }
288 if (MemberOfType.isNull())
289 MemberOfType = SearchType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000290
Douglas Gregorfe17d252010-02-16 19:09:40 +0000291 if (MemberOfType.isNull())
292 continue;
293
294 // We're referring into a class template specialization. If the
295 // class template we found is the same as the template being
296 // specialized, we found what we are looking for.
297 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
298 if (ClassTemplateSpecializationDecl *Spec
299 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
300 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
301 Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000302 return CreateParsedType(
303 MemberOfType,
304 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000305 }
306
307 continue;
308 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000309
Douglas Gregorfe17d252010-02-16 19:09:40 +0000310 // We're referring to an unresolved class template
311 // specialization. Determine whether we class template we found
312 // is the same as the template being specialized or, if we don't
313 // know which template is being specialized, that it at least
314 // has the same name.
315 if (const TemplateSpecializationType *SpecType
316 = MemberOfType->getAs<TemplateSpecializationType>()) {
317 TemplateName SpecName = SpecType->getTemplateName();
318
319 // The class template we found is the same template being
320 // specialized.
321 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
322 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000323 return CreateParsedType(
324 MemberOfType,
325 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000326
327 continue;
328 }
329
330 // The class template we found has the same name as the
331 // (dependent) template name being specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000332 if (DependentTemplateName *DepTemplate
Douglas Gregorfe17d252010-02-16 19:09:40 +0000333 = SpecName.getAsDependentTemplateName()) {
334 if (DepTemplate->isIdentifier() &&
335 DepTemplate->getIdentifier() == Template->getIdentifier())
Richard Smithc278c002014-01-22 00:30:17 +0000336 return CreateParsedType(
337 MemberOfType,
338 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000339
340 continue;
341 }
342 }
343 }
344 }
345
346 if (isDependent) {
347 // We didn't find our type, but that's okay: it's dependent
348 // anyway.
Simon Pilgrim75c26882016-09-30 14:25:09 +0000349
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000350 // FIXME: What if we have no nested-name-specifier?
351 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
352 SS.getWithLocInContext(Context),
353 II, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +0000354 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000355 }
356
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000357 if (NonMatchingTypeDecl) {
358 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
359 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
360 << T << SearchType;
361 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
362 << T;
363 } else if (ObjectTypePtr)
364 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000365 << &II;
David Blaikie5e026f52013-03-20 17:42:13 +0000366 else {
367 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
368 diag::err_destructor_class_name);
369 if (S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000370 const DeclContext *Ctx = S->getEntity();
David Blaikie5e026f52013-03-20 17:42:13 +0000371 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
372 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
373 Class->getNameAsString());
374 }
375 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000376
David Blaikieefdccaa2016-01-15 23:43:34 +0000377 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000378}
379
Richard Smithef2cd8f2017-02-08 20:39:08 +0000380ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
381 ParsedType ObjectType) {
382 if (DS.getTypeSpecType() == DeclSpec::TST_error)
383 return nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000384
Richard Smithef2cd8f2017-02-08 20:39:08 +0000385 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
386 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
387 return nullptr;
388 }
389
390 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
391 "unexpected type in getDestructorType");
392 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
393
394 // If we know the type of the object, check that the correct destructor
395 // type was named now; we can give better diagnostics this way.
396 QualType SearchType = GetTypeFromParser(ObjectType);
397 if (!SearchType.isNull() && !SearchType->isDependentType() &&
398 !Context.hasSameUnqualifiedType(T, SearchType)) {
David Blaikieecd8a942011-12-08 16:13:53 +0000399 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
400 << T << SearchType;
David Blaikieefdccaa2016-01-15 23:43:34 +0000401 return nullptr;
Richard Smithef2cd8f2017-02-08 20:39:08 +0000402 }
403
404 return ParsedType::make(T);
David Blaikieecd8a942011-12-08 16:13:53 +0000405}
406
Richard Smithd091dc12013-12-05 00:58:33 +0000407bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
408 const UnqualifiedId &Name) {
Faisal Vali2ab8c152017-12-30 04:15:27 +0000409 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
Richard Smithd091dc12013-12-05 00:58:33 +0000410
411 if (!SS.isValid())
412 return false;
413
414 switch (SS.getScopeRep()->getKind()) {
415 case NestedNameSpecifier::Identifier:
416 case NestedNameSpecifier::TypeSpec:
417 case NestedNameSpecifier::TypeSpecWithTemplate:
418 // Per C++11 [over.literal]p2, literal operators can only be declared at
419 // namespace scope. Therefore, this unqualified-id cannot name anything.
420 // Reject it early, because we have no AST representation for this in the
421 // case where the scope is dependent.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000422 Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
423 << SS.getScopeRep();
Richard Smithd091dc12013-12-05 00:58:33 +0000424 return true;
425
426 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +0000427 case NestedNameSpecifier::Super:
Richard Smithd091dc12013-12-05 00:58:33 +0000428 case NestedNameSpecifier::Namespace:
429 case NestedNameSpecifier::NamespaceAlias:
430 return false;
431 }
432
433 llvm_unreachable("unknown nested name specifier kind");
434}
435
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000436/// Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000437ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000438 SourceLocation TypeidLoc,
439 TypeSourceInfo *Operand,
440 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000441 // C++ [expr.typeid]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000442 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor9da64192010-04-26 22:37:10 +0000443 // that is the operand of typeid are always ignored.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000444 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor9da64192010-04-26 22:37:10 +0000445 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000446 Qualifiers Quals;
447 QualType T
448 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
449 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000450 if (T->getAs<RecordType>() &&
451 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
452 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000453
David Majnemer6f3150a2014-11-21 21:09:12 +0000454 if (T->isVariablyModifiedType())
455 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
456
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000457 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
458 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000459}
460
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000461/// Build a C++ typeid expression with an expression operand.
John McCalldadc5752010-08-24 06:29:42 +0000462ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000463 SourceLocation TypeidLoc,
464 Expr *E,
465 SourceLocation RParenLoc) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000466 bool WasEvaluated = false;
Douglas Gregor9da64192010-04-26 22:37:10 +0000467 if (E && !E->isTypeDependent()) {
John McCall50a2c2c2011-10-11 23:14:30 +0000468 if (E->getType()->isPlaceholderType()) {
469 ExprResult result = CheckPlaceholderExpr(E);
470 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000471 E = result.get();
John McCall50a2c2c2011-10-11 23:14:30 +0000472 }
473
Douglas Gregor9da64192010-04-26 22:37:10 +0000474 QualType T = E->getType();
475 if (const RecordType *RecordT = T->getAs<RecordType>()) {
476 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
477 // C++ [expr.typeid]p3:
478 // [...] If the type of the expression is a class type, the class
479 // shall be completely-defined.
480 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
481 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000482
Douglas Gregor9da64192010-04-26 22:37:10 +0000483 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000484 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000485 // polymorphic class type [...] [the] expression is an unevaluated
486 // operand. [...]
Richard Smithef8bf432012-08-13 20:08:14 +0000487 if (RecordD->isPolymorphic() && E->isGLValue()) {
Eli Friedman456f0182012-01-20 01:26:23 +0000488 // The subexpression is potentially evaluated; switch the context
489 // and recheck the subexpression.
Benjamin Kramerd81108f2012-11-14 15:08:31 +0000490 ExprResult Result = TransformToPotentiallyEvaluated(E);
Eli Friedman456f0182012-01-20 01:26:23 +0000491 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000492 E = Result.get();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000493
494 // We require a vtable to query the type at run time.
495 MarkVTableUsed(TypeidLoc, RecordD);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000496 WasEvaluated = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000497 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000498 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000499
Douglas Gregor9da64192010-04-26 22:37:10 +0000500 // C++ [expr.typeid]p4:
501 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000502 // cv-qualified type, the result of the typeid expression refers to a
503 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor9da64192010-04-26 22:37:10 +0000504 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000505 Qualifiers Quals;
506 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
507 if (!Context.hasSameType(T, UnqualT)) {
508 T = UnqualT;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000509 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
Douglas Gregor9da64192010-04-26 22:37:10 +0000510 }
511 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000512
David Majnemer6f3150a2014-11-21 21:09:12 +0000513 if (E->getType()->isVariablyModifiedType())
514 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
515 << E->getType());
Richard Smith51ec0cf2017-02-21 01:17:38 +0000516 else if (!inTemplateInstantiation() &&
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000517 E->HasSideEffects(Context, WasEvaluated)) {
518 // The expression operand for typeid is in an unevaluated expression
519 // context, so side effects could result in unintended consequences.
520 Diag(E->getExprLoc(), WasEvaluated
521 ? diag::warn_side_effects_typeid
522 : diag::warn_side_effects_unevaluated_context);
523 }
David Majnemer6f3150a2014-11-21 21:09:12 +0000524
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000525 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
526 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000527}
528
529/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000530ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000531Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
532 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +0000533 // OpenCL C++ 1.0 s2.9: typeid is not supported.
534 if (getLangOpts().OpenCLCPlusPlus) {
535 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
536 << "typeid");
537 }
538
Douglas Gregor9da64192010-04-26 22:37:10 +0000539 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000540 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000541 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000542
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000543 if (!CXXTypeInfoDecl) {
544 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
545 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
546 LookupQualifiedName(R, getStdNamespace());
547 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
Nico Weber5f968832012-06-19 23:58:27 +0000548 // Microsoft's typeinfo doesn't have type_info in std but in the global
549 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
Alp Tokerbfa39342014-01-14 12:51:41 +0000550 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
Nico Weber5f968832012-06-19 23:58:27 +0000551 LookupQualifiedName(R, Context.getTranslationUnitDecl());
552 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
553 }
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000554 if (!CXXTypeInfoDecl)
555 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
556 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000557
Nico Weber1b7f39d2012-05-20 01:27:21 +0000558 if (!getLangOpts().RTTI) {
559 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
560 }
561
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000562 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000563
Douglas Gregor9da64192010-04-26 22:37:10 +0000564 if (isType) {
565 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000566 TypeSourceInfo *TInfo = nullptr;
John McCallba7bf592010-08-24 05:47:05 +0000567 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
568 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000569 if (T.isNull())
570 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000571
Douglas Gregor9da64192010-04-26 22:37:10 +0000572 if (!TInfo)
573 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000574
Douglas Gregor9da64192010-04-26 22:37:10 +0000575 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000576 }
Mike Stump11289f42009-09-09 15:08:12 +0000577
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000578 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000579 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000580}
581
David Majnemer1dbc7a72016-03-27 04:46:07 +0000582/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
583/// a single GUID.
584static void
585getUuidAttrOfType(Sema &SemaRef, QualType QT,
586 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
587 // Optionally remove one level of pointer, reference or array indirection.
588 const Type *Ty = QT.getTypePtr();
589 if (QT->isPointerType() || QT->isReferenceType())
590 Ty = QT->getPointeeType().getTypePtr();
591 else if (QT->isArrayType())
592 Ty = Ty->getBaseElementTypeUnsafe();
593
Reid Klecknere516eab2016-12-13 18:58:09 +0000594 const auto *TD = Ty->getAsTagDecl();
595 if (!TD)
David Majnemer1dbc7a72016-03-27 04:46:07 +0000596 return;
597
Reid Klecknere516eab2016-12-13 18:58:09 +0000598 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000599 UuidAttrs.insert(Uuid);
600 return;
601 }
602
603 // __uuidof can grab UUIDs from template arguments.
Reid Klecknere516eab2016-12-13 18:58:09 +0000604 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000605 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
606 for (const TemplateArgument &TA : TAL.asArray()) {
607 const UuidAttr *UuidForTA = nullptr;
608 if (TA.getKind() == TemplateArgument::Type)
609 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
610 else if (TA.getKind() == TemplateArgument::Declaration)
611 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
612
613 if (UuidForTA)
614 UuidAttrs.insert(UuidForTA);
615 }
616 }
617}
618
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000619/// Build a Microsoft __uuidof expression with a type operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000620ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
621 SourceLocation TypeidLoc,
622 TypeSourceInfo *Operand,
623 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000624 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000625 if (!Operand->getType()->isDependentType()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000626 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
627 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
628 if (UuidAttrs.empty())
629 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
630 if (UuidAttrs.size() > 1)
631 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000632 UuidStr = UuidAttrs.back()->getGuid();
Francois Pichetb7577652010-12-27 01:32:00 +0000633 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000634
David Majnemer2041b462016-03-28 03:19:50 +0000635 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000636 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000637}
638
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000639/// Build a Microsoft __uuidof expression with an expression operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000640ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
641 SourceLocation TypeidLoc,
642 Expr *E,
643 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000644 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000645 if (!E->getType()->isDependentType()) {
David Majnemer2041b462016-03-28 03:19:50 +0000646 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
647 UuidStr = "00000000-0000-0000-0000-000000000000";
648 } else {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000649 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
650 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
651 if (UuidAttrs.empty())
David Majnemer59c0ec22013-09-07 06:59:46 +0000652 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
David Majnemer1dbc7a72016-03-27 04:46:07 +0000653 if (UuidAttrs.size() > 1)
654 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000655 UuidStr = UuidAttrs.back()->getGuid();
David Majnemer59c0ec22013-09-07 06:59:46 +0000656 }
Francois Pichetb7577652010-12-27 01:32:00 +0000657 }
David Majnemer59c0ec22013-09-07 06:59:46 +0000658
David Majnemer2041b462016-03-28 03:19:50 +0000659 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000660 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000661}
662
663/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
664ExprResult
665Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
666 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000667 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000668 if (!MSVCGuidDecl) {
669 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
670 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
671 LookupQualifiedName(R, Context.getTranslationUnitDecl());
672 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
673 if (!MSVCGuidDecl)
674 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000675 }
676
Francois Pichet9f4f2072010-09-08 12:20:18 +0000677 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000678
Francois Pichet9f4f2072010-09-08 12:20:18 +0000679 if (isType) {
680 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000681 TypeSourceInfo *TInfo = nullptr;
Francois Pichet9f4f2072010-09-08 12:20:18 +0000682 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
683 &TInfo);
684 if (T.isNull())
685 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000686
Francois Pichet9f4f2072010-09-08 12:20:18 +0000687 if (!TInfo)
688 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
689
690 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
691 }
692
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000693 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000694 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
695}
696
Steve Naroff66356bd2007-09-16 14:56:35 +0000697/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000698ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000699Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000700 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000701 "Unknown C++ Boolean value!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000702 return new (Context)
703 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Bill Wendling4073ed52007-02-13 01:51:42 +0000704}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000705
Sebastian Redl576fd422009-05-10 18:38:11 +0000706/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000707ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000708Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000709 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
Sebastian Redl576fd422009-05-10 18:38:11 +0000710}
711
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000712/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000713ExprResult
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000714Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
715 bool IsThrownVarInScope = false;
716 if (Ex) {
717 // C++0x [class.copymove]p31:
Nico Weberb58e51c2014-11-19 05:21:39 +0000718 // When certain criteria are met, an implementation is allowed to omit the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000719 // copy/move construction of a class object [...]
720 //
David Blaikie3c8c46e2014-11-19 05:48:40 +0000721 // - in a throw-expression, when the operand is the name of a
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000722 // non-volatile automatic object (other than a function or catch-
Nico Weberb58e51c2014-11-19 05:21:39 +0000723 // clause parameter) whose scope does not extend beyond the end of the
David Blaikie3c8c46e2014-11-19 05:48:40 +0000724 // innermost enclosing try-block (if there is one), the copy/move
725 // operation from the operand to the exception object (15.1) can be
726 // omitted by constructing the automatic object directly into the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000727 // exception object
728 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
729 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
730 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
731 for( ; S; S = S->getParent()) {
732 if (S->isDeclScope(Var)) {
733 IsThrownVarInScope = true;
734 break;
735 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000736
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000737 if (S->getFlags() &
738 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
739 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
740 Scope::TryScope))
741 break;
742 }
743 }
744 }
745 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000746
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000747 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
748}
749
Simon Pilgrim75c26882016-09-30 14:25:09 +0000750ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000751 bool IsThrownVarInScope) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000752 // Don't report an error if 'throw' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000753 if (!getLangOpts().CXXExceptions &&
Alexey Bataev1ab34572018-05-02 16:52:07 +0000754 !getSourceManager().isInSystemHeader(OpLoc) &&
755 (!getLangOpts().OpenMPIsDevice ||
756 !getLangOpts().OpenMPHostCXXExceptions ||
757 isInOpenMPTargetExecutionDirective() ||
758 isInOpenMPDeclareTargetContext()))
Anders Carlssonb94ad3e2011-02-19 21:53:09 +0000759 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000760
Justin Lebar2a8db342016-09-28 22:45:54 +0000761 // Exceptions aren't allowed in CUDA device code.
762 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +0000763 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
764 << "throw" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +0000765
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000766 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
767 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
768
John Wiegley01296292011-04-08 18:41:53 +0000769 if (Ex && !Ex->isTypeDependent()) {
David Majnemerba3e5ec2015-03-13 18:26:17 +0000770 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
771 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
John Wiegley01296292011-04-08 18:41:53 +0000772 return ExprError();
David Majnemerba3e5ec2015-03-13 18:26:17 +0000773
774 // Initialize the exception result. This implicitly weeds out
775 // abstract types or types with inaccessible copy constructors.
776
777 // C++0x [class.copymove]p31:
778 // When certain criteria are met, an implementation is allowed to omit the
779 // copy/move construction of a class object [...]
780 //
781 // - in a throw-expression, when the operand is the name of a
782 // non-volatile automatic object (other than a function or
783 // catch-clause
784 // parameter) whose scope does not extend beyond the end of the
785 // innermost enclosing try-block (if there is one), the copy/move
786 // operation from the operand to the exception object (15.1) can be
787 // omitted by constructing the automatic object directly into the
788 // exception object
789 const VarDecl *NRVOVariable = nullptr;
790 if (IsThrownVarInScope)
Richard Trieu09c163b2018-03-15 03:00:55 +0000791 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict);
David Majnemerba3e5ec2015-03-13 18:26:17 +0000792
793 InitializedEntity Entity = InitializedEntity::InitializeException(
794 OpLoc, ExceptionObjectTy,
795 /*NRVO=*/NRVOVariable != nullptr);
796 ExprResult Res = PerformMoveOrCopyInitialization(
797 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
798 if (Res.isInvalid())
799 return ExprError();
800 Ex = Res.get();
John Wiegley01296292011-04-08 18:41:53 +0000801 }
David Majnemerba3e5ec2015-03-13 18:26:17 +0000802
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000803 return new (Context)
804 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000805}
806
David Majnemere7a818f2015-03-06 18:53:55 +0000807static void
808collectPublicBases(CXXRecordDecl *RD,
809 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
810 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
811 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
812 bool ParentIsPublic) {
813 for (const CXXBaseSpecifier &BS : RD->bases()) {
814 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
815 bool NewSubobject;
816 // Virtual bases constitute the same subobject. Non-virtual bases are
817 // always distinct subobjects.
818 if (BS.isVirtual())
819 NewSubobject = VBases.insert(BaseDecl).second;
820 else
821 NewSubobject = true;
822
823 if (NewSubobject)
824 ++SubobjectsSeen[BaseDecl];
825
826 // Only add subobjects which have public access throughout the entire chain.
827 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
828 if (PublicPath)
829 PublicSubobjectsSeen.insert(BaseDecl);
830
831 // Recurse on to each base subobject.
832 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
833 PublicPath);
834 }
835}
836
837static void getUnambiguousPublicSubobjects(
838 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
839 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
840 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
841 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
842 SubobjectsSeen[RD] = 1;
843 PublicSubobjectsSeen.insert(RD);
844 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
845 /*ParentIsPublic=*/true);
846
847 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
848 // Skip ambiguous objects.
849 if (SubobjectsSeen[PublicSubobject] > 1)
850 continue;
851
852 Objects.push_back(PublicSubobject);
853 }
854}
855
Sebastian Redl4de47b42009-04-27 20:27:31 +0000856/// CheckCXXThrowOperand - Validate the operand of a throw.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000857bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
858 QualType ExceptionObjectTy, Expr *E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000859 // If the type of the exception would be an incomplete type or a pointer
860 // to an incomplete type other than (cv) void the program is ill-formed.
David Majnemerd09a51c2015-03-03 01:50:05 +0000861 QualType Ty = ExceptionObjectTy;
John McCall2e6567a2010-04-22 01:10:34 +0000862 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000863 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000864 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000865 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000866 }
867 if (!isPointer || !Ty->isVoidType()) {
868 if (RequireCompleteType(ThrowLoc, Ty,
David Majnemerba3e5ec2015-03-13 18:26:17 +0000869 isPointer ? diag::err_throw_incomplete_ptr
870 : diag::err_throw_incomplete,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000871 E->getSourceRange()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000872 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000873
David Majnemerd09a51c2015-03-03 01:50:05 +0000874 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
Douglas Gregorae298422012-05-04 17:09:59 +0000875 diag::err_throw_abstract_type, E))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000876 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000877 }
878
Eli Friedman91a3d272010-06-03 20:39:03 +0000879 // If the exception has class type, we need additional handling.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000880 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
881 if (!RD)
882 return false;
Eli Friedman91a3d272010-06-03 20:39:03 +0000883
Douglas Gregor88d292c2010-05-13 16:44:06 +0000884 // If we are throwing a polymorphic class type or pointer thereof,
885 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000886 MarkVTableUsed(ThrowLoc, RD);
887
Eli Friedman36ebbec2010-10-12 20:32:36 +0000888 // If a pointer is thrown, the referenced object will not be destroyed.
889 if (isPointer)
David Majnemerba3e5ec2015-03-13 18:26:17 +0000890 return false;
Eli Friedman36ebbec2010-10-12 20:32:36 +0000891
Richard Smitheec915d62012-02-18 04:13:32 +0000892 // If the class has a destructor, we must be able to call it.
David Majnemere7a818f2015-03-06 18:53:55 +0000893 if (!RD->hasIrrelevantDestructor()) {
894 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
895 MarkFunctionReferenced(E->getExprLoc(), Destructor);
896 CheckDestructorAccess(E->getExprLoc(), Destructor,
897 PDiag(diag::err_access_dtor_exception) << Ty);
898 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000899 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000900 }
901 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000902
David Majnemerdfa6d202015-03-11 18:36:39 +0000903 // The MSVC ABI creates a list of all types which can catch the exception
904 // object. This list also references the appropriate copy constructor to call
905 // if the object is caught by value and has a non-trivial copy constructor.
David Majnemere7a818f2015-03-06 18:53:55 +0000906 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000907 // We are only interested in the public, unambiguous bases contained within
908 // the exception object. Bases which are ambiguous or otherwise
909 // inaccessible are not catchable types.
David Majnemere7a818f2015-03-06 18:53:55 +0000910 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
911 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
David Majnemerdfa6d202015-03-11 18:36:39 +0000912
David Majnemere7a818f2015-03-06 18:53:55 +0000913 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000914 // Attempt to lookup the copy constructor. Various pieces of machinery
915 // will spring into action, like template instantiation, which means this
916 // cannot be a simple walk of the class's decls. Instead, we must perform
917 // lookup and overload resolution.
918 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
919 if (!CD)
920 continue;
921
922 // Mark the constructor referenced as it is used by this throw expression.
923 MarkFunctionReferenced(E->getExprLoc(), CD);
924
925 // Skip this copy constructor if it is trivial, we don't need to record it
926 // in the catchable type data.
927 if (CD->isTrivial())
928 continue;
929
930 // The copy constructor is non-trivial, create a mapping from this class
931 // type to this constructor.
932 // N.B. The selection of copy constructor is not sensitive to this
933 // particular throw-site. Lookup will be performed at the catch-site to
934 // ensure that the copy constructor is, in fact, accessible (via
935 // friendship or any other means).
936 Context.addCopyConstructorForExceptionObject(Subobject, CD);
937
938 // We don't keep the instantiated default argument expressions around so
939 // we must rebuild them here.
940 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
Reid Klecknerc01ee752016-11-23 16:51:30 +0000941 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
942 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000943 }
944 }
945 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000946
David Majnemerba3e5ec2015-03-13 18:26:17 +0000947 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000948}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000949
Faisal Vali67b04462016-06-11 16:41:54 +0000950static QualType adjustCVQualifiersForCXXThisWithinLambda(
951 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
952 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
953
954 QualType ClassType = ThisTy->getPointeeType();
955 LambdaScopeInfo *CurLSI = nullptr;
956 DeclContext *CurDC = CurSemaContext;
957
958 // Iterate through the stack of lambdas starting from the innermost lambda to
959 // the outermost lambda, checking if '*this' is ever captured by copy - since
960 // that could change the cv-qualifiers of the '*this' object.
961 // The object referred to by '*this' starts out with the cv-qualifiers of its
962 // member function. We then start with the innermost lambda and iterate
963 // outward checking to see if any lambda performs a by-copy capture of '*this'
964 // - and if so, any nested lambda must respect the 'constness' of that
965 // capturing lamdbda's call operator.
966 //
967
Faisal Vali999f27e2017-05-02 20:56:34 +0000968 // Since the FunctionScopeInfo stack is representative of the lexical
969 // nesting of the lambda expressions during initial parsing (and is the best
970 // place for querying information about captures about lambdas that are
971 // partially processed) and perhaps during instantiation of function templates
972 // that contain lambda expressions that need to be transformed BUT not
973 // necessarily during instantiation of a nested generic lambda's function call
974 // operator (which might even be instantiated at the end of the TU) - at which
975 // time the DeclContext tree is mature enough to query capture information
976 // reliably - we use a two pronged approach to walk through all the lexically
977 // enclosing lambda expressions:
978 //
979 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
980 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
981 // enclosed by the call-operator of the LSI below it on the stack (while
982 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
983 // the stack represents the innermost lambda.
984 //
985 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
986 // represents a lambda's call operator. If it does, we must be instantiating
987 // a generic lambda's call operator (represented by the Current LSI, and
988 // should be the only scenario where an inconsistency between the LSI and the
989 // DeclContext should occur), so climb out the DeclContexts if they
990 // represent lambdas, while querying the corresponding closure types
991 // regarding capture information.
Faisal Vali67b04462016-06-11 16:41:54 +0000992
Faisal Vali999f27e2017-05-02 20:56:34 +0000993 // 1) Climb down the function scope info stack.
Faisal Vali67b04462016-06-11 16:41:54 +0000994 for (int I = FunctionScopes.size();
Faisal Vali999f27e2017-05-02 20:56:34 +0000995 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
996 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
997 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
Faisal Vali67b04462016-06-11 16:41:54 +0000998 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
999 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001000
1001 if (!CurLSI->isCXXThisCaptured())
Faisal Vali67b04462016-06-11 16:41:54 +00001002 continue;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001003
Faisal Vali67b04462016-06-11 16:41:54 +00001004 auto C = CurLSI->getCXXThisCapture();
1005
1006 if (C.isCopyCapture()) {
1007 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1008 if (CurLSI->CallOperator->isConst())
1009 ClassType.addConst();
1010 return ASTCtx.getPointerType(ClassType);
1011 }
1012 }
Faisal Vali999f27e2017-05-02 20:56:34 +00001013
1014 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
1015 // happen during instantiation of its nested generic lambda call operator)
Faisal Vali67b04462016-06-11 16:41:54 +00001016 if (isLambdaCallOperator(CurDC)) {
Faisal Vali999f27e2017-05-02 20:56:34 +00001017 assert(CurLSI && "While computing 'this' capture-type for a generic "
1018 "lambda, we must have a corresponding LambdaScopeInfo");
1019 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
1020 "While computing 'this' capture-type for a generic lambda, when we "
1021 "run out of enclosing LSI's, yet the enclosing DC is a "
1022 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1023 "lambda call oeprator");
Faisal Vali67b04462016-06-11 16:41:54 +00001024 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
Simon Pilgrim75c26882016-09-30 14:25:09 +00001025
Faisal Vali67b04462016-06-11 16:41:54 +00001026 auto IsThisCaptured =
1027 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1028 IsConst = false;
1029 IsByCopy = false;
1030 for (auto &&C : Closure->captures()) {
1031 if (C.capturesThis()) {
1032 if (C.getCaptureKind() == LCK_StarThis)
1033 IsByCopy = true;
1034 if (Closure->getLambdaCallOperator()->isConst())
1035 IsConst = true;
1036 return true;
1037 }
1038 }
1039 return false;
1040 };
1041
1042 bool IsByCopyCapture = false;
1043 bool IsConstCapture = false;
1044 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1045 while (Closure &&
1046 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1047 if (IsByCopyCapture) {
1048 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1049 if (IsConstCapture)
1050 ClassType.addConst();
1051 return ASTCtx.getPointerType(ClassType);
1052 }
1053 Closure = isLambdaCallOperator(Closure->getParent())
1054 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1055 : nullptr;
1056 }
1057 }
1058 return ASTCtx.getPointerType(ClassType);
1059}
1060
Eli Friedman73a04092012-01-07 04:59:52 +00001061QualType Sema::getCurrentThisType() {
1062 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +00001063 QualType ThisTy = CXXThisTypeOverride;
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001064
Richard Smith938f40b2011-06-11 17:19:42 +00001065 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1066 if (method && method->isInstance())
1067 ThisTy = method->getThisType(Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001068 }
Faisal Validc6b5962016-03-21 09:25:37 +00001069
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001070 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
Richard Smith51ec0cf2017-02-21 01:17:38 +00001071 inTemplateInstantiation()) {
Faisal Validc6b5962016-03-21 09:25:37 +00001072
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001073 assert(isa<CXXRecordDecl>(DC) &&
1074 "Trying to get 'this' type from static method?");
1075
1076 // This is a lambda call operator that is being instantiated as a default
1077 // initializer. DC must point to the enclosing class type, so we can recover
1078 // the 'this' type from it.
1079
1080 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1081 // There are no cv-qualifiers for 'this' within default initializers,
1082 // per [expr.prim.general]p4.
1083 ThisTy = Context.getPointerType(ClassTy);
Faisal Validc6b5962016-03-21 09:25:37 +00001084 }
Faisal Vali67b04462016-06-11 16:41:54 +00001085
1086 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1087 // might need to be adjusted if the lambda or any of its enclosing lambda's
1088 // captures '*this' by copy.
1089 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1090 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1091 CurContext, Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001092 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +00001093}
1094
Simon Pilgrim75c26882016-09-30 14:25:09 +00001095Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
Douglas Gregor3024f072012-04-16 07:05:22 +00001096 Decl *ContextDecl,
1097 unsigned CXXThisTypeQuals,
Simon Pilgrim75c26882016-09-30 14:25:09 +00001098 bool Enabled)
Douglas Gregor3024f072012-04-16 07:05:22 +00001099 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1100{
1101 if (!Enabled || !ContextDecl)
1102 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00001103
1104 CXXRecordDecl *Record = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00001105 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1106 Record = Template->getTemplatedDecl();
1107 else
1108 Record = cast<CXXRecordDecl>(ContextDecl);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001109
Andrey Bokhanko67a41862016-05-26 10:06:01 +00001110 // We care only for CVR qualifiers here, so cut everything else.
1111 CXXThisTypeQuals &= Qualifiers::FastMask;
Douglas Gregor3024f072012-04-16 07:05:22 +00001112 S.CXXThisTypeOverride
1113 = S.Context.getPointerType(
1114 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
Simon Pilgrim75c26882016-09-30 14:25:09 +00001115
Douglas Gregor3024f072012-04-16 07:05:22 +00001116 this->Enabled = true;
1117}
1118
1119
1120Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1121 if (Enabled) {
1122 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1123 }
1124}
1125
Faisal Validc6b5962016-03-21 09:25:37 +00001126static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1127 QualType ThisTy, SourceLocation Loc,
1128 const bool ByCopy) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00001129
Faisal Vali67b04462016-06-11 16:41:54 +00001130 QualType AdjustedThisTy = ThisTy;
1131 // The type of the corresponding data member (not a 'this' pointer if 'by
1132 // copy').
1133 QualType CaptureThisFieldTy = ThisTy;
1134 if (ByCopy) {
1135 // If we are capturing the object referred to by '*this' by copy, ignore any
1136 // cv qualifiers inherited from the type of the member function for the type
1137 // of the closure-type's corresponding data member and any use of 'this'.
1138 CaptureThisFieldTy = ThisTy->getPointeeType();
1139 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1140 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1141 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00001142
Faisal Vali67b04462016-06-11 16:41:54 +00001143 FieldDecl *Field = FieldDecl::Create(
1144 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1145 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1146 ICIS_NoInit);
1147
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001148 Field->setImplicit(true);
1149 Field->setAccess(AS_private);
1150 RD->addDecl(Field);
Faisal Vali67b04462016-06-11 16:41:54 +00001151 Expr *This =
1152 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
Faisal Validc6b5962016-03-21 09:25:37 +00001153 if (ByCopy) {
1154 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1155 UO_Deref,
1156 This).get();
1157 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
Faisal Vali67b04462016-06-11 16:41:54 +00001158 nullptr, CaptureThisFieldTy, Loc);
Faisal Validc6b5962016-03-21 09:25:37 +00001159 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1160 InitializationSequence Init(S, Entity, InitKind, StarThis);
1161 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1162 if (ER.isInvalid()) return nullptr;
1163 return ER.get();
1164 }
1165 return This;
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001166}
1167
Simon Pilgrim75c26882016-09-30 14:25:09 +00001168bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
Faisal Validc6b5962016-03-21 09:25:37 +00001169 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1170 const bool ByCopy) {
Eli Friedman73a04092012-01-07 04:59:52 +00001171 // We don't need to capture this in an unevaluated context.
John McCallf413f5e2013-05-03 00:10:13 +00001172 if (isUnevaluatedContext() && !Explicit)
Faisal Valia17d19f2013-11-07 05:17:06 +00001173 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001174
Faisal Validc6b5962016-03-21 09:25:37 +00001175 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
Eli Friedman73a04092012-01-07 04:59:52 +00001176
Reid Kleckner87a31802018-03-12 21:43:02 +00001177 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1178 ? *FunctionScopeIndexToStopAt
1179 : FunctionScopes.size() - 1;
Faisal Validc6b5962016-03-21 09:25:37 +00001180
Simon Pilgrim75c26882016-09-30 14:25:09 +00001181 // Check that we can capture the *enclosing object* (referred to by '*this')
1182 // by the capturing-entity/closure (lambda/block/etc) at
1183 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1184
1185 // Note: The *enclosing object* can only be captured by-value by a
1186 // closure that is a lambda, using the explicit notation:
Faisal Validc6b5962016-03-21 09:25:37 +00001187 // [*this] { ... }.
1188 // Every other capture of the *enclosing object* results in its by-reference
1189 // capture.
1190
1191 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1192 // stack), we can capture the *enclosing object* only if:
1193 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1194 // - or, 'L' has an implicit capture.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001195 // AND
Faisal Validc6b5962016-03-21 09:25:37 +00001196 // -- there is no enclosing closure
Simon Pilgrim75c26882016-09-30 14:25:09 +00001197 // -- or, there is some enclosing closure 'E' that has already captured the
1198 // *enclosing object*, and every intervening closure (if any) between 'E'
Faisal Validc6b5962016-03-21 09:25:37 +00001199 // and 'L' can implicitly capture the *enclosing object*.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001200 // -- or, every enclosing closure can implicitly capture the
Faisal Validc6b5962016-03-21 09:25:37 +00001201 // *enclosing object*
Simon Pilgrim75c26882016-09-30 14:25:09 +00001202
1203
Faisal Validc6b5962016-03-21 09:25:37 +00001204 unsigned NumCapturingClosures = 0;
Reid Kleckner87a31802018-03-12 21:43:02 +00001205 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +00001206 if (CapturingScopeInfo *CSI =
1207 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1208 if (CSI->CXXThisCaptureIndex != 0) {
1209 // 'this' is already being captured; there isn't anything more to do.
Malcolm Parsons87a03622017-01-13 15:01:06 +00001210 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
Eli Friedman73a04092012-01-07 04:59:52 +00001211 break;
1212 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001213 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1214 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1215 // This context can't implicitly capture 'this'; fail out.
1216 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001217 Diag(Loc, diag::err_this_capture)
1218 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001219 return true;
1220 }
Eli Friedman20139d32012-01-11 02:36:31 +00001221 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +00001222 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001223 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001224 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Faisal Validc6b5962016-03-21 09:25:37 +00001225 (Explicit && idx == MaxFunctionScopesIndex)) {
1226 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1227 // iteration through can be an explicit capture, all enclosing closures,
1228 // if any, must perform implicit captures.
1229
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001230 // This closure can capture 'this'; continue looking upwards.
Faisal Validc6b5962016-03-21 09:25:37 +00001231 NumCapturingClosures++;
Eli Friedman73a04092012-01-07 04:59:52 +00001232 continue;
1233 }
Eli Friedman20139d32012-01-11 02:36:31 +00001234 // This context can't implicitly capture 'this'; fail out.
Faisal Valia17d19f2013-11-07 05:17:06 +00001235 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001236 Diag(Loc, diag::err_this_capture)
1237 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001238 return true;
Eli Friedman73a04092012-01-07 04:59:52 +00001239 }
Eli Friedman73a04092012-01-07 04:59:52 +00001240 break;
1241 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001242 if (!BuildAndDiagnose) return false;
Faisal Validc6b5962016-03-21 09:25:37 +00001243
1244 // If we got here, then the closure at MaxFunctionScopesIndex on the
1245 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1246 // (including implicit by-reference captures in any enclosing closures).
1247
1248 // In the loop below, respect the ByCopy flag only for the closure requesting
1249 // the capture (i.e. first iteration through the loop below). Ignore it for
Simon Pilgrimb17efcb2016-11-15 18:28:07 +00001250 // all enclosing closure's up to NumCapturingClosures (since they must be
Faisal Validc6b5962016-03-21 09:25:37 +00001251 // implicitly capturing the *enclosing object* by reference (see loop
1252 // above)).
1253 assert((!ByCopy ||
1254 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1255 "Only a lambda can capture the enclosing object (referred to by "
1256 "*this) by copy");
Eli Friedman73a04092012-01-07 04:59:52 +00001257 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1258 // contexts.
Faisal Vali67b04462016-06-11 16:41:54 +00001259 QualType ThisTy = getCurrentThisType();
Reid Kleckner87a31802018-03-12 21:43:02 +00001260 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1261 --idx, --NumCapturingClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +00001262 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Craig Topperc3ec1492014-05-26 06:22:03 +00001263 Expr *ThisExpr = nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001264
Faisal Validc6b5962016-03-21 09:25:37 +00001265 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1266 // For lambda expressions, build a field and an initializing expression,
1267 // and capture the *enclosing object* by copy only if this is the first
1268 // iteration.
1269 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1270 ByCopy && idx == MaxFunctionScopesIndex);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001271
Faisal Validc6b5962016-03-21 09:25:37 +00001272 } else if (CapturedRegionScopeInfo *RSI
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001273 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
Faisal Validc6b5962016-03-21 09:25:37 +00001274 ThisExpr =
1275 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1276 false/*ByCopy*/);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001277
Faisal Validc6b5962016-03-21 09:25:37 +00001278 bool isNested = NumCapturingClosures > 1;
Faisal Vali67b04462016-06-11 16:41:54 +00001279 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
Eli Friedman73a04092012-01-07 04:59:52 +00001280 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001281 return false;
Eli Friedman73a04092012-01-07 04:59:52 +00001282}
1283
Richard Smith938f40b2011-06-11 17:19:42 +00001284ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +00001285 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1286 /// is a non-lvalue expression whose value is the address of the object for
1287 /// which the function is called.
1288
Douglas Gregor09deffa2011-10-18 16:47:30 +00001289 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001290 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +00001291
Eli Friedman73a04092012-01-07 04:59:52 +00001292 CheckCXXThisCapture(Loc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001293 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001294}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001295
Douglas Gregor3024f072012-04-16 07:05:22 +00001296bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1297 // If we're outside the body of a member function, then we'll have a specified
1298 // type for 'this'.
1299 if (CXXThisTypeOverride.isNull())
1300 return false;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001301
Douglas Gregor3024f072012-04-16 07:05:22 +00001302 // Determine whether we're looking into a class that's currently being
1303 // defined.
1304 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1305 return Class && Class->isBeingDefined();
1306}
1307
Vedant Kumara14a1f92018-01-17 18:53:51 +00001308/// Parse construction of a specified type.
1309/// Can be interpreted either as function-style casting ("int(x)")
1310/// or class type construction ("ClassType(x,y,z)")
1311/// or creation of a value-initialized type ("int()").
John McCalldadc5752010-08-24 06:29:42 +00001312ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +00001313Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001314 SourceLocation LParenOrBraceLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001315 MultiExprArg exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001316 SourceLocation RParenOrBraceLoc,
1317 bool ListInitialization) {
Douglas Gregor7df89f52010-02-05 19:11:37 +00001318 if (!TypeRep)
1319 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001320
John McCall97513962010-01-15 18:39:57 +00001321 TypeSourceInfo *TInfo;
1322 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1323 if (!TInfo)
1324 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +00001325
Vedant Kumara14a1f92018-01-17 18:53:51 +00001326 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1327 RParenOrBraceLoc, ListInitialization);
Richard Smithb8c414c2016-06-30 20:24:30 +00001328 // Avoid creating a non-type-dependent expression that contains typos.
1329 // Non-type-dependent expressions are liable to be discarded without
1330 // checking for embedded typos.
1331 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1332 !Result.get()->isTypeDependent())
1333 Result = CorrectDelayedTyposInExpr(Result.get());
1334 return Result;
Douglas Gregor2b88c112010-09-08 00:15:04 +00001335}
1336
Douglas Gregor2b88c112010-09-08 00:15:04 +00001337ExprResult
1338Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001339 SourceLocation LParenOrBraceLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001340 MultiExprArg Exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001341 SourceLocation RParenOrBraceLoc,
1342 bool ListInitialization) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00001343 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +00001344 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001345
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001346 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Vedant Kumara14a1f92018-01-17 18:53:51 +00001347 // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1348 // directly. We work around this by dropping the locations of the braces.
1349 SourceRange Locs = ListInitialization
1350 ? SourceRange()
1351 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1352 return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(),
1353 Exprs, Locs.getEnd());
Douglas Gregor0950e412009-03-13 21:01:28 +00001354 }
1355
Richard Smith600b5262017-01-26 20:40:47 +00001356 assert((!ListInitialization ||
1357 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1358 "List initialization must have initializer list as expression.");
Vedant Kumara14a1f92018-01-17 18:53:51 +00001359 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
Sebastian Redld74dd492012-02-12 18:41:05 +00001360
Richard Smith60437622017-02-09 19:17:44 +00001361 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1362 InitializationKind Kind =
1363 Exprs.size()
1364 ? ListInitialization
Vedant Kumara14a1f92018-01-17 18:53:51 +00001365 ? InitializationKind::CreateDirectList(
1366 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1367 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1368 RParenOrBraceLoc)
1369 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1370 RParenOrBraceLoc);
Richard Smith60437622017-02-09 19:17:44 +00001371
1372 // C++1z [expr.type.conv]p1:
1373 // If the type is a placeholder for a deduced class type, [...perform class
1374 // template argument deduction...]
1375 DeducedType *Deduced = Ty->getContainedDeducedType();
1376 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1377 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1378 Kind, Exprs);
1379 if (Ty.isNull())
1380 return ExprError();
1381 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1382 }
1383
Douglas Gregordd04d332009-01-16 18:33:17 +00001384 // C++ [expr.type.conv]p1:
Richard Smith49a6b6e2017-03-24 01:14:25 +00001385 // If the expression list is a parenthesized single expression, the type
1386 // conversion expression is equivalent (in definedness, and if defined in
1387 // meaning) to the corresponding cast expression.
1388 if (Exprs.size() == 1 && !ListInitialization &&
1389 !isa<InitListExpr>(Exprs[0])) {
John McCallb50451a2011-10-05 07:41:44 +00001390 Expr *Arg = Exprs[0];
Vedant Kumara14a1f92018-01-17 18:53:51 +00001391 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1392 RParenOrBraceLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001393 }
1394
Richard Smith49a6b6e2017-03-24 01:14:25 +00001395 // For an expression of the form T(), T shall not be an array type.
Eli Friedman576cbd02012-02-29 00:00:28 +00001396 QualType ElemTy = Ty;
1397 if (Ty->isArrayType()) {
1398 if (!ListInitialization)
Richard Smith49a6b6e2017-03-24 01:14:25 +00001399 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1400 << FullRange);
Eli Friedman576cbd02012-02-29 00:00:28 +00001401 ElemTy = Context.getBaseElementType(Ty);
1402 }
1403
Richard Smith49a6b6e2017-03-24 01:14:25 +00001404 // There doesn't seem to be an explicit rule against this but sanity demands
1405 // we only construct objects with object types.
1406 if (Ty->isFunctionType())
1407 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1408 << Ty << FullRange);
David Majnemer7eddcff2015-09-14 07:05:00 +00001409
Richard Smith49a6b6e2017-03-24 01:14:25 +00001410 // C++17 [expr.type.conv]p2:
1411 // If the type is cv void and the initializer is (), the expression is a
1412 // prvalue of the specified type that performs no initialization.
Eli Friedman576cbd02012-02-29 00:00:28 +00001413 if (!Ty->isVoidType() &&
1414 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001415 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +00001416 return ExprError();
1417
Richard Smith49a6b6e2017-03-24 01:14:25 +00001418 // Otherwise, the expression is a prvalue of the specified type whose
1419 // result object is direct-initialized (11.6) with the initializer.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001420 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1421 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001422
Richard Smith49a6b6e2017-03-24 01:14:25 +00001423 if (Result.isInvalid())
Richard Smith90061902013-09-23 02:20:00 +00001424 return Result;
1425
1426 Expr *Inner = Result.get();
1427 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1428 Inner = BTE->getSubExpr();
Richard Smith49a6b6e2017-03-24 01:14:25 +00001429 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1430 !isa<CXXScalarValueInitExpr>(Inner)) {
Richard Smith1ae689c2015-01-28 22:06:01 +00001431 // If we created a CXXTemporaryObjectExpr, that node also represents the
1432 // functional cast. Otherwise, create an explicit cast to represent
1433 // the syntactic form of a functional-style cast that was used here.
1434 //
1435 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1436 // would give a more consistent AST representation than using a
1437 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1438 // is sometimes handled by initialization and sometimes not.
Richard Smith90061902013-09-23 02:20:00 +00001439 QualType ResultType = Result.get()->getType();
Vedant Kumara14a1f92018-01-17 18:53:51 +00001440 SourceRange Locs = ListInitialization
1441 ? SourceRange()
1442 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001443 Result = CXXFunctionalCastExpr::Create(
Vedant Kumara14a1f92018-01-17 18:53:51 +00001444 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1445 Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd());
Sebastian Redl2b80af42012-02-13 19:55:43 +00001446 }
1447
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001448 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001449}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001450
Artem Belevich78929ef2018-09-21 17:29:33 +00001451bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) {
1452 // [CUDA] Ignore this function, if we can't call it.
1453 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
1454 if (getLangOpts().CUDA &&
1455 IdentifyCUDAPreference(Caller, Method) <= CFP_WrongSide)
1456 return false;
1457
1458 SmallVector<const FunctionDecl*, 4> PreventedBy;
1459 bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1460
1461 if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1462 return Result;
1463
1464 // In case of CUDA, return true if none of the 1-argument deallocator
1465 // functions are actually callable.
1466 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1467 assert(FD->getNumParams() == 1 &&
1468 "Only single-operand functions should be in PreventedBy");
1469 return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice;
1470 });
1471}
1472
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001473/// Determine whether the given function is a non-placement
Richard Smithb2f0f052016-10-10 18:54:32 +00001474/// deallocation function.
1475static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001476 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
Artem Belevich78929ef2018-09-21 17:29:33 +00001477 return S.isUsualDeallocationFunction(Method);
Richard Smithb2f0f052016-10-10 18:54:32 +00001478
1479 if (FD->getOverloadedOperator() != OO_Delete &&
1480 FD->getOverloadedOperator() != OO_Array_Delete)
1481 return false;
1482
1483 unsigned UsualParams = 1;
1484
1485 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1486 S.Context.hasSameUnqualifiedType(
1487 FD->getParamDecl(UsualParams)->getType(),
1488 S.Context.getSizeType()))
1489 ++UsualParams;
1490
1491 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1492 S.Context.hasSameUnqualifiedType(
1493 FD->getParamDecl(UsualParams)->getType(),
1494 S.Context.getTypeDeclType(S.getStdAlignValT())))
1495 ++UsualParams;
1496
1497 return UsualParams == FD->getNumParams();
1498}
1499
1500namespace {
1501 struct UsualDeallocFnInfo {
1502 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
Richard Smithf75dcbe2016-10-11 00:21:10 +00001503 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
Richard Smithb2f0f052016-10-10 18:54:32 +00001504 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
Richard Smith5b349582017-10-13 01:55:36 +00001505 Destroying(false), HasSizeT(false), HasAlignValT(false),
1506 CUDAPref(Sema::CFP_Native) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001507 // A function template declaration is never a usual deallocation function.
1508 if (!FD)
1509 return;
Richard Smith5b349582017-10-13 01:55:36 +00001510 unsigned NumBaseParams = 1;
1511 if (FD->isDestroyingOperatorDelete()) {
1512 Destroying = true;
1513 ++NumBaseParams;
1514 }
1515 if (FD->getNumParams() == NumBaseParams + 2)
Richard Smithb2f0f052016-10-10 18:54:32 +00001516 HasAlignValT = HasSizeT = true;
Richard Smith5b349582017-10-13 01:55:36 +00001517 else if (FD->getNumParams() == NumBaseParams + 1) {
Eric Fiselier3b4bbe72018-10-25 19:50:43 +00001518 HasSizeT = FD->getParamDecl(NumBaseParams)->getType()->isIntegerType();
1519 HasAlignValT = !HasSizeT;
Richard Smithb2f0f052016-10-10 18:54:32 +00001520 }
Richard Smithf75dcbe2016-10-11 00:21:10 +00001521
1522 // In CUDA, determine how much we'd like / dislike to call this.
1523 if (S.getLangOpts().CUDA)
1524 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1525 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001526 }
1527
Eric Fiselierfa752f22018-03-21 19:19:48 +00001528 explicit operator bool() const { return FD; }
Richard Smithb2f0f052016-10-10 18:54:32 +00001529
Richard Smithf75dcbe2016-10-11 00:21:10 +00001530 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1531 bool WantAlign) const {
Richard Smith5b349582017-10-13 01:55:36 +00001532 // C++ P0722:
1533 // A destroying operator delete is preferred over a non-destroying
1534 // operator delete.
1535 if (Destroying != Other.Destroying)
1536 return Destroying;
1537
Richard Smithf75dcbe2016-10-11 00:21:10 +00001538 // C++17 [expr.delete]p10:
1539 // If the type has new-extended alignment, a function with a parameter
1540 // of type std::align_val_t is preferred; otherwise a function without
1541 // such a parameter is preferred
1542 if (HasAlignValT != Other.HasAlignValT)
1543 return HasAlignValT == WantAlign;
1544
1545 if (HasSizeT != Other.HasSizeT)
1546 return HasSizeT == WantSize;
1547
1548 // Use CUDA call preference as a tiebreaker.
1549 return CUDAPref > Other.CUDAPref;
1550 }
1551
Richard Smithb2f0f052016-10-10 18:54:32 +00001552 DeclAccessPair Found;
1553 FunctionDecl *FD;
Richard Smith5b349582017-10-13 01:55:36 +00001554 bool Destroying, HasSizeT, HasAlignValT;
Richard Smithf75dcbe2016-10-11 00:21:10 +00001555 Sema::CUDAFunctionPreference CUDAPref;
Richard Smithb2f0f052016-10-10 18:54:32 +00001556 };
1557}
1558
1559/// Determine whether a type has new-extended alignment. This may be called when
1560/// the type is incomplete (for a delete-expression with an incomplete pointee
1561/// type), in which case it will conservatively return false if the alignment is
1562/// not known.
1563static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1564 return S.getLangOpts().AlignedAllocation &&
1565 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1566 S.getASTContext().getTargetInfo().getNewAlign();
1567}
1568
1569/// Select the correct "usual" deallocation function to use from a selection of
1570/// deallocation functions (either global or class-scope).
1571static UsualDeallocFnInfo resolveDeallocationOverload(
1572 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1573 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1574 UsualDeallocFnInfo Best;
1575
Richard Smithb2f0f052016-10-10 18:54:32 +00001576 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00001577 UsualDeallocFnInfo Info(S, I.getPair());
1578 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1579 Info.CUDAPref == Sema::CFP_Never)
Richard Smithb2f0f052016-10-10 18:54:32 +00001580 continue;
1581
1582 if (!Best) {
1583 Best = Info;
1584 if (BestFns)
1585 BestFns->push_back(Info);
1586 continue;
1587 }
1588
Richard Smithf75dcbe2016-10-11 00:21:10 +00001589 if (Best.isBetterThan(Info, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001590 continue;
1591
1592 // If more than one preferred function is found, all non-preferred
1593 // functions are eliminated from further consideration.
Richard Smithf75dcbe2016-10-11 00:21:10 +00001594 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001595 BestFns->clear();
1596
1597 Best = Info;
1598 if (BestFns)
1599 BestFns->push_back(Info);
1600 }
1601
1602 return Best;
1603}
1604
1605/// Determine whether a given type is a class for which 'delete[]' would call
1606/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1607/// we need to store the array size (even if the type is
1608/// trivially-destructible).
John McCall284c48f2011-01-27 09:37:56 +00001609static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1610 QualType allocType) {
1611 const RecordType *record =
1612 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1613 if (!record) return false;
1614
1615 // Try to find an operator delete[] in class scope.
1616
1617 DeclarationName deleteName =
1618 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1619 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1620 S.LookupQualifiedName(ops, record->getDecl());
1621
1622 // We're just doing this for information.
1623 ops.suppressDiagnostics();
1624
1625 // Very likely: there's no operator delete[].
1626 if (ops.empty()) return false;
1627
1628 // If it's ambiguous, it should be illegal to call operator delete[]
1629 // on this thing, so it doesn't matter if we allocate extra space or not.
1630 if (ops.isAmbiguous()) return false;
1631
Richard Smithb2f0f052016-10-10 18:54:32 +00001632 // C++17 [expr.delete]p10:
1633 // If the deallocation functions have class scope, the one without a
1634 // parameter of type std::size_t is selected.
1635 auto Best = resolveDeallocationOverload(
1636 S, ops, /*WantSize*/false,
1637 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1638 return Best && Best.HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00001639}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001640
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001641/// Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +00001642///
Sebastian Redld74dd492012-02-12 18:41:05 +00001643/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +00001644/// @code new (memory) int[size][4] @endcode
1645/// or
1646/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001647///
1648/// \param StartLoc The first location of the expression.
1649/// \param UseGlobal True if 'new' was prefixed with '::'.
1650/// \param PlacementLParen Opening paren of the placement arguments.
1651/// \param PlacementArgs Placement new arguments.
1652/// \param PlacementRParen Closing paren of the placement arguments.
1653/// \param TypeIdParens If the type is in parens, the source range.
1654/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +00001655/// \param Initializer The initializing expression or initializer-list, or null
1656/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001657ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001658Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001659 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001660 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001661 Declarator &D, Expr *Initializer) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001662 Expr *ArraySize = nullptr;
Sebastian Redl351bb782008-12-02 14:43:59 +00001663 // If the specified type is an array, unwrap it and save the expression.
1664 if (D.getNumTypeObjects() > 0 &&
1665 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
Richard Smith3beb7c62017-01-12 02:27:38 +00001666 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smithbfbff072017-02-10 22:35:37 +00001667 if (D.getDeclSpec().hasAutoTypeSpec())
Richard Smith30482bc2011-02-20 03:19:35 +00001668 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1669 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001670 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001671 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1672 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001673 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001674 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1675 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001676
Sebastian Redl351bb782008-12-02 14:43:59 +00001677 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001678 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001679 }
1680
Douglas Gregor73341c42009-09-11 00:18:58 +00001681 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001682 if (ArraySize) {
1683 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001684 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1685 break;
1686
1687 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1688 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001689 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001690 if (getLangOpts().CPlusPlus14) {
Fangrui Song99337e22018-07-20 08:19:20 +00001691 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1692 // shall be a converted constant expression (5.19) of type std::size_t
1693 // and shall evaluate to a strictly positive value.
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001694 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1695 assert(IntWidth && "Builtin type of size 0?");
1696 llvm::APSInt Value(IntWidth);
1697 Array.NumElts
1698 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1699 CCEK_NewExpr)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001700 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001701 } else {
1702 Array.NumElts
Craig Topperc3ec1492014-05-26 06:22:03 +00001703 = VerifyIntegerConstantExpression(NumElts, nullptr,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001704 diag::err_new_array_nonconst)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001705 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001706 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001707 if (!Array.NumElts)
1708 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001709 }
1710 }
1711 }
1712 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001713
Craig Topperc3ec1492014-05-26 06:22:03 +00001714 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
John McCall8cb7bdf2010-06-04 23:28:52 +00001715 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001716 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001717 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001718
Sebastian Redl6047f072012-02-16 12:22:20 +00001719 SourceRange DirectInitRange;
Richard Smith49a6b6e2017-03-24 01:14:25 +00001720 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
Sebastian Redl6047f072012-02-16 12:22:20 +00001721 DirectInitRange = List->getSourceRange();
1722
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001723 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1724 PlacementLParen, PlacementArgs, PlacementRParen,
1725 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001726 Initializer);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001727}
1728
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001729static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1730 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001731 if (!Init)
1732 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001733 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1734 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001735 if (isa<ImplicitValueInitExpr>(Init))
1736 return true;
1737 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1738 return !CCE->isListInitialization() &&
1739 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001740 else if (Style == CXXNewExpr::ListInit) {
1741 assert(isa<InitListExpr>(Init) &&
1742 "Shouldn't create list CXXConstructExprs for arrays.");
1743 return true;
1744 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001745 return false;
1746}
1747
Akira Hatanakacae83f72017-06-29 18:48:40 +00001748// Emit a diagnostic if an aligned allocation/deallocation function that is not
1749// implemented in the standard library is selected.
1750static void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1751 SourceLocation Loc, bool IsDelete,
1752 Sema &S) {
1753 if (!S.getLangOpts().AlignedAllocationUnavailable)
1754 return;
1755
1756 // Return if there is a definition.
1757 if (FD.isDefined())
1758 return;
1759
1760 bool IsAligned = false;
1761 if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned) {
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001762 const llvm::Triple &T = S.getASTContext().getTargetInfo().getTriple();
1763 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1764 S.getASTContext().getTargetInfo().getPlatformName());
1765
Volodymyr Sapsaie5015ab2018-08-03 23:12:37 +00001766 S.Diag(Loc, diag::err_aligned_allocation_unavailable)
1767 << IsDelete << FD.getType().getAsString() << OSName
1768 << alignedAllocMinVersion(T.getOS()).getAsString();
Louis Dionne751381d2018-08-21 15:54:24 +00001769 S.Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
Akira Hatanakacae83f72017-06-29 18:48:40 +00001770 }
1771}
1772
John McCalldadc5752010-08-24 06:29:42 +00001773ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001774Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001775 SourceLocation PlacementLParen,
1776 MultiExprArg PlacementArgs,
1777 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001778 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001779 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001780 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +00001781 Expr *ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001782 SourceRange DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001783 Expr *Initializer) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001784 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001785 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001786
Sebastian Redl6047f072012-02-16 12:22:20 +00001787 CXXNewExpr::InitializationStyle initStyle;
1788 if (DirectInitRange.isValid()) {
1789 assert(Initializer && "Have parens but no initializer.");
1790 initStyle = CXXNewExpr::CallInit;
1791 } else if (Initializer && isa<InitListExpr>(Initializer))
1792 initStyle = CXXNewExpr::ListInit;
1793 else {
1794 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1795 isa<CXXConstructExpr>(Initializer)) &&
1796 "Initializer expression that cannot have been implicitly created.");
1797 initStyle = CXXNewExpr::NoInit;
1798 }
1799
1800 Expr **Inits = &Initializer;
1801 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001802 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1803 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1804 Inits = List->getExprs();
1805 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001806 }
1807
Richard Smith60437622017-02-09 19:17:44 +00001808 // C++11 [expr.new]p15:
1809 // A new-expression that creates an object of type T initializes that
1810 // object as follows:
1811 InitializationKind Kind
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001812 // - If the new-initializer is omitted, the object is default-
1813 // initialized (8.5); if no initialization is performed,
1814 // the object has indeterminate value
1815 = initStyle == CXXNewExpr::NoInit
1816 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1817 // - Otherwise, the new-initializer is interpreted according to
1818 // the
1819 // initialization rules of 8.5 for direct-initialization.
1820 : initStyle == CXXNewExpr::ListInit
1821 ? InitializationKind::CreateDirectList(
1822 TypeRange.getBegin(), Initializer->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001823 Initializer->getEndLoc())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001824 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1825 DirectInitRange.getBegin(),
1826 DirectInitRange.getEnd());
Richard Smith600b5262017-01-26 20:40:47 +00001827
Richard Smith60437622017-02-09 19:17:44 +00001828 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1829 auto *Deduced = AllocType->getContainedDeducedType();
1830 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1831 if (ArraySize)
1832 return ExprError(Diag(ArraySize->getExprLoc(),
1833 diag::err_deduced_class_template_compound_type)
1834 << /*array*/ 2 << ArraySize->getSourceRange());
1835
1836 InitializedEntity Entity
1837 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1838 AllocType = DeduceTemplateSpecializationFromInitializer(
1839 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1840 if (AllocType.isNull())
1841 return ExprError();
1842 } else if (Deduced) {
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001843 bool Braced = (initStyle == CXXNewExpr::ListInit);
1844 if (NumInits == 1) {
1845 if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1846 Inits = p->getInits();
1847 NumInits = p->getNumInits();
1848 Braced = true;
1849 }
1850 }
1851
Sebastian Redl6047f072012-02-16 12:22:20 +00001852 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001853 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1854 << AllocType << TypeRange);
Sebastian Redl6047f072012-02-16 12:22:20 +00001855 if (NumInits > 1) {
1856 Expr *FirstBad = Inits[1];
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001857 return ExprError(Diag(FirstBad->getBeginLoc(),
Richard Smith30482bc2011-02-20 03:19:35 +00001858 diag::err_auto_new_ctor_multiple_expressions)
1859 << AllocType << TypeRange);
1860 }
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001861 if (Braced && !getLangOpts().CPlusPlus17)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001862 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001863 << AllocType << TypeRange;
Sebastian Redl6047f072012-02-16 12:22:20 +00001864 Expr *Deduce = Inits[0];
Richard Smith061f1e22013-04-30 21:23:01 +00001865 QualType DeducedType;
Richard Smith74801c82012-07-08 04:13:07 +00001866 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001867 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redld74dd492012-02-12 18:41:05 +00001868 << AllocType << Deduce->getType()
1869 << TypeRange << Deduce->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001870 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001871 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001872 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001873 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001874
Douglas Gregorcda95f42010-05-16 16:01:03 +00001875 // Per C++0x [expr.new]p5, the type being constructed may be a
1876 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001877 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001878 if (const ConstantArrayType *Array
1879 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001880 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1881 Context.getSizeType(),
1882 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001883 AllocType = Array->getElementType();
1884 }
1885 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001886
Douglas Gregor3999e152010-10-06 16:00:31 +00001887 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1888 return ExprError();
1889
Simon Pilgrim75c26882016-09-30 14:25:09 +00001890 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001891 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001892 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1893 AllocType->isObjCLifetimeType()) {
1894 AllocType = Context.getLifetimeQualifiedType(AllocType,
1895 AllocType->getObjCARCImplicitLifetime());
1896 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001897
John McCall31168b02011-06-15 23:02:42 +00001898 QualType ResultType = Context.getPointerType(AllocType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001899
John McCall5e77d762013-04-16 07:28:30 +00001900 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1901 ExprResult result = CheckPlaceholderExpr(ArraySize);
1902 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001903 ArraySize = result.get();
John McCall5e77d762013-04-16 07:28:30 +00001904 }
Richard Smith8dd34252012-02-04 07:07:42 +00001905 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1906 // integral or enumeration type with a non-negative value."
1907 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1908 // enumeration type, or a class type for which a single non-explicit
1909 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001910 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001911 // std::size_t.
Richard Smith0511d232016-10-05 22:41:02 +00001912 llvm::Optional<uint64_t> KnownArraySize;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001913 if (ArraySize && !ArraySize->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001914 ExprResult ConvertedSize;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001915 if (getLangOpts().CPlusPlus14) {
Alp Toker965f8822013-11-27 05:22:15 +00001916 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1917
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001918 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
Fangrui Song99337e22018-07-20 08:19:20 +00001919 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00001920
Simon Pilgrim75c26882016-09-30 14:25:09 +00001921 if (!ConvertedSize.isInvalid() &&
Larisse Voufobf4aa572013-06-18 03:08:53 +00001922 ArraySize->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00001923 // Diagnose the compatibility of this conversion.
1924 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1925 << ArraySize->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001926 } else {
1927 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1928 protected:
1929 Expr *ArraySize;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001930
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001931 public:
1932 SizeConvertDiagnoser(Expr *ArraySize)
1933 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1934 ArraySize(ArraySize) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001935
1936 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1937 QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001938 return S.Diag(Loc, diag::err_array_size_not_integral)
1939 << S.getLangOpts().CPlusPlus11 << T;
1940 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001941
1942 SemaDiagnosticBuilder diagnoseIncomplete(
1943 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001944 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1945 << T << ArraySize->getSourceRange();
1946 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001947
1948 SemaDiagnosticBuilder diagnoseExplicitConv(
1949 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001950 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1951 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001952
1953 SemaDiagnosticBuilder noteExplicitConv(
1954 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001955 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1956 << ConvTy->isEnumeralType() << ConvTy;
1957 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001958
1959 SemaDiagnosticBuilder diagnoseAmbiguous(
1960 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001961 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1962 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001963
1964 SemaDiagnosticBuilder noteAmbiguous(
1965 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001966 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1967 << ConvTy->isEnumeralType() << ConvTy;
1968 }
Richard Smithccc11812013-05-21 19:05:48 +00001969
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001970 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1971 QualType T,
1972 QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001973 return S.Diag(Loc,
1974 S.getLangOpts().CPlusPlus11
1975 ? diag::warn_cxx98_compat_array_size_conversion
1976 : diag::ext_array_size_conversion)
1977 << T << ConvTy->isEnumeralType() << ConvTy;
1978 }
1979 } SizeDiagnoser(ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00001980
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001981 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1982 SizeDiagnoser);
1983 }
Douglas Gregor4799d032010-06-30 00:20:43 +00001984 if (ConvertedSize.isInvalid())
1985 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001986
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001987 ArraySize = ConvertedSize.get();
John McCall9b80c212012-01-11 00:14:46 +00001988 QualType SizeType = ArraySize->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001989
Douglas Gregor0bf31402010-10-08 23:50:27 +00001990 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001991 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001992
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001993 // C++98 [expr.new]p7:
1994 // The expression in a direct-new-declarator shall have integral type
1995 // with a non-negative value.
1996 //
Richard Smith0511d232016-10-05 22:41:02 +00001997 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1998 // per CWG1464. Otherwise, if it's not a constant, we must have an
1999 // unparenthesized array type.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002000 if (!ArraySize->isValueDependent()) {
2001 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00002002 // We've already performed any required implicit conversion to integer or
2003 // unscoped enumeration type.
Richard Smith0511d232016-10-05 22:41:02 +00002004 // FIXME: Per CWG1464, we are required to check the value prior to
2005 // converting to size_t. This will never find a negative array size in
2006 // C++14 onwards, because Value is always unsigned here!
Richard Smithbcc9bcb2012-02-04 05:35:53 +00002007 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Richard Smith0511d232016-10-05 22:41:02 +00002008 if (Value.isSigned() && Value.isNegative()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002009 return ExprError(Diag(ArraySize->getBeginLoc(),
Richard Smith0511d232016-10-05 22:41:02 +00002010 diag::err_typecheck_negative_array_size)
2011 << ArraySize->getSourceRange());
2012 }
2013
2014 if (!AllocType->isDependentType()) {
Richard Smithbcc9bcb2012-02-04 05:35:53 +00002015 unsigned ActiveSizeBits =
2016 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
Richard Smith0511d232016-10-05 22:41:02 +00002017 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002018 return ExprError(
2019 Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2020 << Value.toString(10) << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00002021 }
Richard Smith0511d232016-10-05 22:41:02 +00002022
2023 KnownArraySize = Value.getZExtValue();
Douglas Gregorf2753b32010-07-13 15:54:32 +00002024 } else if (TypeIdParens.isValid()) {
2025 // Can't have dynamic array size when the type-id is in parentheses.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002026 Diag(ArraySize->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2027 << ArraySize->getSourceRange()
2028 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2029 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002030
Douglas Gregorf2753b32010-07-13 15:54:32 +00002031 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002032 }
Sebastian Redl351bb782008-12-02 14:43:59 +00002033 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002034
John McCall036f2f62011-05-15 07:14:44 +00002035 // Note that we do *not* convert the argument in any way. It can
2036 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00002037 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002038
Craig Topperc3ec1492014-05-26 06:22:03 +00002039 FunctionDecl *OperatorNew = nullptr;
2040 FunctionDecl *OperatorDelete = nullptr;
Richard Smithb2f0f052016-10-10 18:54:32 +00002041 unsigned Alignment =
2042 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2043 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2044 bool PassAlignment = getLangOpts().AlignedAllocation &&
2045 Alignment > NewAlignment;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002046
Brian Gesiakcb024022018-04-01 22:59:22 +00002047 AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002048 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002049 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002050 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002051 SourceRange(PlacementLParen, PlacementRParen),
Brian Gesiakcb024022018-04-01 22:59:22 +00002052 Scope, Scope, AllocType, ArraySize, PassAlignment,
Richard Smithb2f0f052016-10-10 18:54:32 +00002053 PlacementArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002054 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00002055
2056 // If this is an array allocation, compute whether the usual array
2057 // deallocation function for the type has a size_t parameter.
2058 bool UsualArrayDeleteWantsSize = false;
2059 if (ArraySize && !AllocType->isDependentType())
Richard Smithb2f0f052016-10-10 18:54:32 +00002060 UsualArrayDeleteWantsSize =
2061 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
John McCall284c48f2011-01-27 09:37:56 +00002062
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002063 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00002064 if (OperatorNew) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002065 const FunctionProtoType *Proto =
Richard Smithd6f9e732014-05-13 19:56:21 +00002066 OperatorNew->getType()->getAs<FunctionProtoType>();
2067 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2068 : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002069
Richard Smithd6f9e732014-05-13 19:56:21 +00002070 // We've already converted the placement args, just fill in any default
2071 // arguments. Skip the first parameter because we don't have a corresponding
Richard Smithb2f0f052016-10-10 18:54:32 +00002072 // argument. Skip the second parameter too if we're passing in the
2073 // alignment; we've already filled it in.
2074 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2075 PassAlignment ? 2 : 1, PlacementArgs,
2076 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00002077 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002078
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002079 if (!AllPlaceArgs.empty())
2080 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00002081
Richard Smithd6f9e732014-05-13 19:56:21 +00002082 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002083 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +00002084
2085 // FIXME: Missing call to CheckFunctionCall or equivalent
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002086
Richard Smithb2f0f052016-10-10 18:54:32 +00002087 // Warn if the type is over-aligned and is being allocated by (unaligned)
2088 // global operator new.
2089 if (PlacementArgs.empty() && !PassAlignment &&
2090 (OperatorNew->isImplicit() ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002091 (OperatorNew->getBeginLoc().isValid() &&
2092 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002093 if (Alignment > NewAlignment)
Nick Lewycky411fc652012-01-24 21:15:41 +00002094 Diag(StartLoc, diag::warn_overaligned_type)
2095 << AllocType
Richard Smithb2f0f052016-10-10 18:54:32 +00002096 << unsigned(Alignment / Context.getCharWidth())
2097 << unsigned(NewAlignment / Context.getCharWidth());
Nick Lewycky411fc652012-01-24 21:15:41 +00002098 }
2099 }
2100
Sebastian Redl6047f072012-02-16 12:22:20 +00002101 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002102 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2103 // dialect distinction.
Richard Smith0511d232016-10-05 22:41:02 +00002104 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002105 SourceRange InitRange(Inits[0]->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002106 Inits[NumInits - 1]->getEndLoc());
Richard Smith0511d232016-10-05 22:41:02 +00002107 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2108 return ExprError();
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00002109 }
2110
Richard Smithdd2ca572012-11-26 08:32:48 +00002111 // If we can perform the initialization, and we've not already done so,
2112 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002113 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002114 !Expr::hasAnyTypeDependentArguments(
Richard Smithc6abd962014-07-25 01:12:44 +00002115 llvm::makeArrayRef(Inits, NumInits))) {
Richard Smith0511d232016-10-05 22:41:02 +00002116 // The type we initialize is the complete type, including the array bound.
2117 QualType InitType;
2118 if (KnownArraySize)
2119 InitType = Context.getConstantArrayType(
2120 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2121 *KnownArraySize),
2122 ArrayType::Normal, 0);
2123 else if (ArraySize)
2124 InitType =
2125 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2126 else
2127 InitType = AllocType;
2128
Douglas Gregor85dabae2009-12-16 01:38:02 +00002129 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002130 = InitializedEntity::InitializeNew(StartLoc, InitType);
Richard Smith0511d232016-10-05 22:41:02 +00002131 InitializationSequence InitSeq(*this, Entity, Kind,
2132 MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002133 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00002134 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00002135 if (FullInit.isInvalid())
2136 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002137
Sebastian Redl6047f072012-02-16 12:22:20 +00002138 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2139 // we don't want the initialized object to be destructed.
Richard Smith0511d232016-10-05 22:41:02 +00002140 // FIXME: We should not create these in the first place.
Sebastian Redl6047f072012-02-16 12:22:20 +00002141 if (CXXBindTemporaryExpr *Binder =
2142 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002143 FullInit = Binder->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002144
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002145 Initializer = FullInit.get();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002146 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002147
Douglas Gregor6642ca22010-02-26 05:06:18 +00002148 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00002149 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00002150 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2151 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002152 MarkFunctionReferenced(StartLoc, OperatorNew);
Akira Hatanakacae83f72017-06-29 18:48:40 +00002153 diagnoseUnavailableAlignedAllocation(*OperatorNew, StartLoc, false, *this);
Nick Lewyckya096b142013-02-12 08:08:54 +00002154 }
2155 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00002156 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2157 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002158 MarkFunctionReferenced(StartLoc, OperatorDelete);
Akira Hatanakacae83f72017-06-29 18:48:40 +00002159 diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true, *this);
Nick Lewyckya096b142013-02-12 08:08:54 +00002160 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002161
John McCall928a2572011-07-13 20:12:57 +00002162 // C++0x [expr.new]p17:
2163 // If the new expression creates an array of objects of class type,
2164 // access and ambiguity control are done for the destructor.
David Blaikie631a4862012-03-10 23:40:02 +00002165 QualType BaseAllocType = Context.getBaseElementType(AllocType);
2166 if (ArraySize && !BaseAllocType->isDependentType()) {
2167 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
2168 if (CXXDestructorDecl *dtor = LookupDestructor(
2169 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
2170 MarkFunctionReferenced(StartLoc, dtor);
Simon Pilgrim75c26882016-09-30 14:25:09 +00002171 CheckDestructorAccess(StartLoc, dtor,
David Blaikie631a4862012-03-10 23:40:02 +00002172 PDiag(diag::err_access_dtor)
2173 << BaseAllocType);
Richard Smith22262ab2013-05-04 06:44:46 +00002174 if (DiagnoseUseOfDecl(dtor, StartLoc))
2175 return ExprError();
David Blaikie631a4862012-03-10 23:40:02 +00002176 }
John McCall928a2572011-07-13 20:12:57 +00002177 }
2178 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002179
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002180 return new (Context)
Richard Smithb2f0f052016-10-10 18:54:32 +00002181 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002182 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
2183 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
2184 Range, DirectInitRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002185}
2186
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002187/// Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00002188/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00002189bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00002190 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002191 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2192 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00002193 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002194 return Diag(Loc, diag::err_bad_new_type)
2195 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002196 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002197 return Diag(Loc, diag::err_bad_new_type)
2198 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002199 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002200 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00002201 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00002202 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00002203 diag::err_allocation_of_abstract_type))
2204 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00002205 else if (AllocType->isVariablyModifiedType())
2206 return Diag(Loc, diag::err_variably_modified_new_type)
2207 << AllocType;
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002208 else if (AllocType.getAddressSpace() != LangAS::Default &&
2209 !getLangOpts().OpenCLCPlusPlus)
Douglas Gregor39d1a092011-04-15 19:46:20 +00002210 return Diag(Loc, diag::err_address_space_qualified_new)
Yaxun Liub34ec822017-04-11 17:24:23 +00002211 << AllocType.getUnqualifiedType()
2212 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002213 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002214 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2215 QualType BaseAllocType = Context.getBaseElementType(AT);
2216 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2217 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002218 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00002219 << BaseAllocType;
2220 }
2221 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00002222
Sebastian Redlbd150f42008-11-21 19:14:01 +00002223 return false;
2224}
2225
Brian Gesiak87412d92018-02-15 20:09:25 +00002226static bool resolveAllocationOverload(
2227 Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2228 bool &PassAlignment, FunctionDecl *&Operator,
2229 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002230 OverloadCandidateSet Candidates(R.getNameLoc(),
2231 OverloadCandidateSet::CSK_Normal);
2232 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2233 Alloc != AllocEnd; ++Alloc) {
2234 // Even member operator new/delete are implicitly treated as
2235 // static, so don't use AddMemberCandidate.
2236 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2237
2238 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2239 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2240 /*ExplicitTemplateArgs=*/nullptr, Args,
2241 Candidates,
2242 /*SuppressUserConversions=*/false);
2243 continue;
2244 }
2245
2246 FunctionDecl *Fn = cast<FunctionDecl>(D);
2247 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2248 /*SuppressUserConversions=*/false);
2249 }
2250
2251 // Do the resolution.
2252 OverloadCandidateSet::iterator Best;
2253 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2254 case OR_Success: {
2255 // Got one!
2256 FunctionDecl *FnDecl = Best->Function;
2257 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2258 Best->FoundDecl) == Sema::AR_inaccessible)
2259 return true;
2260
2261 Operator = FnDecl;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002262 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002263 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002264
Richard Smithb2f0f052016-10-10 18:54:32 +00002265 case OR_No_Viable_Function:
2266 // C++17 [expr.new]p13:
2267 // If no matching function is found and the allocated object type has
2268 // new-extended alignment, the alignment argument is removed from the
2269 // argument list, and overload resolution is performed again.
2270 if (PassAlignment) {
2271 PassAlignment = false;
2272 AlignArg = Args[1];
2273 Args.erase(Args.begin() + 1);
2274 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002275 Operator, &Candidates, AlignArg,
2276 Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002277 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002278
Richard Smithb2f0f052016-10-10 18:54:32 +00002279 // MSVC will fall back on trying to find a matching global operator new
2280 // if operator new[] cannot be found. Also, MSVC will leak by not
2281 // generating a call to operator delete or operator delete[], but we
2282 // will not replicate that bug.
2283 // FIXME: Find out how this interacts with the std::align_val_t fallback
2284 // once MSVC implements it.
2285 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2286 S.Context.getLangOpts().MSVCCompat) {
2287 R.clear();
2288 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2289 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2290 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2291 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002292 Operator, /*Candidates=*/nullptr,
2293 /*AlignArg=*/nullptr, Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002294 }
Richard Smith1cdec012013-09-29 04:40:38 +00002295
Brian Gesiak87412d92018-02-15 20:09:25 +00002296 if (Diagnose) {
2297 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2298 << R.getLookupName() << Range;
Richard Smithb2f0f052016-10-10 18:54:32 +00002299
Brian Gesiak87412d92018-02-15 20:09:25 +00002300 // If we have aligned candidates, only note the align_val_t candidates
2301 // from AlignedCandidates and the non-align_val_t candidates from
2302 // Candidates.
2303 if (AlignedCandidates) {
2304 auto IsAligned = [](OverloadCandidate &C) {
2305 return C.Function->getNumParams() > 1 &&
2306 C.Function->getParamDecl(1)->getType()->isAlignValT();
2307 };
2308 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
Richard Smithb2f0f052016-10-10 18:54:32 +00002309
Brian Gesiak87412d92018-02-15 20:09:25 +00002310 // This was an overaligned allocation, so list the aligned candidates
2311 // first.
2312 Args.insert(Args.begin() + 1, AlignArg);
2313 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2314 R.getNameLoc(), IsAligned);
2315 Args.erase(Args.begin() + 1);
2316 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2317 IsUnaligned);
2318 } else {
2319 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2320 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002321 }
Richard Smith1cdec012013-09-29 04:40:38 +00002322 return true;
2323
Richard Smithb2f0f052016-10-10 18:54:32 +00002324 case OR_Ambiguous:
Brian Gesiak87412d92018-02-15 20:09:25 +00002325 if (Diagnose) {
2326 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2327 << R.getLookupName() << Range;
2328 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2329 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002330 return true;
2331
2332 case OR_Deleted: {
Brian Gesiak87412d92018-02-15 20:09:25 +00002333 if (Diagnose) {
2334 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2335 << Best->Function->isDeleted() << R.getLookupName()
2336 << S.getDeletedOrUnavailableSuffix(Best->Function) << Range;
2337 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2338 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002339 return true;
2340 }
2341 }
2342 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Douglas Gregor6642ca22010-02-26 05:06:18 +00002343}
2344
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002345bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
Brian Gesiakcb024022018-04-01 22:59:22 +00002346 AllocationFunctionScope NewScope,
2347 AllocationFunctionScope DeleteScope,
2348 QualType AllocType, bool IsArray,
2349 bool &PassAlignment, MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00002350 FunctionDecl *&OperatorNew,
Brian Gesiak87412d92018-02-15 20:09:25 +00002351 FunctionDecl *&OperatorDelete,
2352 bool Diagnose) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002353 // --- Choosing an allocation function ---
2354 // C++ 5.3.4p8 - 14 & 18
Brian Gesiakcb024022018-04-01 22:59:22 +00002355 // 1) If looking in AFS_Global scope for allocation functions, only look in
2356 // the global scope. Else, if AFS_Class, only look in the scope of the
2357 // allocated class. If AFS_Both, look in both.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002358 // 2) If an array size is given, look for operator new[], else look for
2359 // operator new.
2360 // 3) The first argument is always size_t. Append the arguments from the
2361 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002362
Richard Smithb2f0f052016-10-10 18:54:32 +00002363 SmallVector<Expr*, 8> AllocArgs;
2364 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2365
2366 // We don't care about the actual value of these arguments.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002367 // FIXME: Should the Sema create the expression and embed it in the syntax
2368 // tree? Or should the consumer just recalculate the value?
Richard Smithb2f0f052016-10-10 18:54:32 +00002369 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002370 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00002371 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00002372 Context.getSizeType(),
2373 SourceLocation());
Richard Smithb2f0f052016-10-10 18:54:32 +00002374 AllocArgs.push_back(&Size);
2375
2376 QualType AlignValT = Context.VoidTy;
2377 if (PassAlignment) {
2378 DeclareGlobalNewDelete();
2379 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2380 }
2381 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2382 if (PassAlignment)
2383 AllocArgs.push_back(&Align);
2384
2385 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
Sebastian Redlfaf68082008-12-03 20:26:15 +00002386
Douglas Gregor6642ca22010-02-26 05:06:18 +00002387 // C++ [expr.new]p8:
2388 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002389 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00002390 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002391 // type, the allocation function's name is operator new[] and the
2392 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00002393 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
Richard Smithb2f0f052016-10-10 18:54:32 +00002394 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002395
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002396 QualType AllocElemType = Context.getBaseElementType(AllocType);
2397
Richard Smithb2f0f052016-10-10 18:54:32 +00002398 // Find the allocation function.
2399 {
2400 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2401
2402 // C++1z [expr.new]p9:
2403 // If the new-expression begins with a unary :: operator, the allocation
2404 // function's name is looked up in the global scope. Otherwise, if the
2405 // allocated type is a class type T or array thereof, the allocation
2406 // function's name is looked up in the scope of T.
Brian Gesiakcb024022018-04-01 22:59:22 +00002407 if (AllocElemType->isRecordType() && NewScope != AFS_Global)
Richard Smithb2f0f052016-10-10 18:54:32 +00002408 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2409
2410 // We can see ambiguity here if the allocation function is found in
2411 // multiple base classes.
2412 if (R.isAmbiguous())
2413 return true;
2414
2415 // If this lookup fails to find the name, or if the allocated type is not
2416 // a class type, the allocation function's name is looked up in the
2417 // global scope.
Brian Gesiakcb024022018-04-01 22:59:22 +00002418 if (R.empty()) {
2419 if (NewScope == AFS_Class)
2420 return true;
2421
Richard Smithb2f0f052016-10-10 18:54:32 +00002422 LookupQualifiedName(R, Context.getTranslationUnitDecl());
Brian Gesiakcb024022018-04-01 22:59:22 +00002423 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002424
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002425 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2426 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2427 return true;
2428 }
2429
Richard Smithb2f0f052016-10-10 18:54:32 +00002430 assert(!R.empty() && "implicitly declared allocation functions not found");
2431 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2432
2433 // We do our own custom access checks below.
2434 R.suppressDiagnostics();
2435
2436 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002437 OperatorNew, /*Candidates=*/nullptr,
2438 /*AlignArg=*/nullptr, Diagnose))
Sebastian Redlfaf68082008-12-03 20:26:15 +00002439 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002440 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00002441
Richard Smithb2f0f052016-10-10 18:54:32 +00002442 // We don't need an operator delete if we're running under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002443 if (!getLangOpts().Exceptions) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002444 OperatorDelete = nullptr;
John McCall0f55a032010-04-20 02:18:25 +00002445 return false;
2446 }
2447
Richard Smithb2f0f052016-10-10 18:54:32 +00002448 // Note, the name of OperatorNew might have been changed from array to
2449 // non-array by resolveAllocationOverload.
2450 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2451 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2452 ? OO_Array_Delete
2453 : OO_Delete);
2454
Douglas Gregor6642ca22010-02-26 05:06:18 +00002455 // C++ [expr.new]p19:
2456 //
2457 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002458 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00002459 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002460 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00002461 // the scope of T. If this lookup fails to find the name, or if
2462 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002463 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002464 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Brian Gesiakcb024022018-04-01 22:59:22 +00002465 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002466 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002467 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00002468 LookupQualifiedName(FoundDelete, RD);
2469 }
John McCallfb6f5262010-03-18 08:19:33 +00002470 if (FoundDelete.isAmbiguous())
2471 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00002472
Richard Smithb2f0f052016-10-10 18:54:32 +00002473 bool FoundGlobalDelete = FoundDelete.empty();
Douglas Gregor6642ca22010-02-26 05:06:18 +00002474 if (FoundDelete.empty()) {
Brian Gesiakcb024022018-04-01 22:59:22 +00002475 if (DeleteScope == AFS_Class)
2476 return true;
2477
Douglas Gregor6642ca22010-02-26 05:06:18 +00002478 DeclareGlobalNewDelete();
2479 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2480 }
2481
2482 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00002483
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002484 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00002485
John McCalld3be2c82010-09-14 21:34:24 +00002486 // Whether we're looking for a placement operator delete is dictated
2487 // by whether we selected a placement operator new, not by whether
2488 // we had explicit placement arguments. This matters for things like
2489 // struct A { void *operator new(size_t, int = 0); ... };
2490 // A *a = new A()
Richard Smithb2f0f052016-10-10 18:54:32 +00002491 //
2492 // We don't have any definition for what a "placement allocation function"
2493 // is, but we assume it's any allocation function whose
2494 // parameter-declaration-clause is anything other than (size_t).
2495 //
2496 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2497 // This affects whether an exception from the constructor of an overaligned
2498 // type uses the sized or non-sized form of aligned operator delete.
2499 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2500 OperatorNew->isVariadic();
John McCalld3be2c82010-09-14 21:34:24 +00002501
2502 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002503 // C++ [expr.new]p20:
2504 // A declaration of a placement deallocation function matches the
2505 // declaration of a placement allocation function if it has the
2506 // same number of parameters and, after parameter transformations
2507 // (8.3.5), all parameter types except the first are
2508 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002509 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00002510 // To perform this comparison, we compute the function type that
2511 // the deallocation function should have, and use that type both
2512 // for template argument deduction and for comparison purposes.
2513 QualType ExpectedFunctionType;
2514 {
2515 const FunctionProtoType *Proto
2516 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002517
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002518 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002519 ArgTypes.push_back(Context.VoidPtrTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00002520 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2521 ArgTypes.push_back(Proto->getParamType(I));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002522
John McCalldb40c7f2010-12-14 08:05:40 +00002523 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithb2f0f052016-10-10 18:54:32 +00002524 // FIXME: This is not part of the standard's rule.
John McCalldb40c7f2010-12-14 08:05:40 +00002525 EPI.Variadic = Proto->isVariadic();
2526
Douglas Gregor6642ca22010-02-26 05:06:18 +00002527 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00002528 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002529 }
2530
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002531 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00002532 DEnd = FoundDelete.end();
2533 D != DEnd; ++D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002534 FunctionDecl *Fn = nullptr;
Richard Smithbaa47832016-12-01 02:11:49 +00002535 if (FunctionTemplateDecl *FnTmpl =
2536 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002537 // Perform template argument deduction to try to match the
2538 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00002539 TemplateDeductionInfo Info(StartLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002540 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2541 Info))
Douglas Gregor6642ca22010-02-26 05:06:18 +00002542 continue;
2543 } else
2544 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2545
Richard Smithbaa47832016-12-01 02:11:49 +00002546 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2547 ExpectedFunctionType,
2548 /*AdjustExcpetionSpec*/true),
2549 ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00002550 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002551 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00002552
Richard Smithb2f0f052016-10-10 18:54:32 +00002553 if (getLangOpts().CUDA)
2554 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2555 } else {
Richard Smith1cdec012013-09-29 04:40:38 +00002556 // C++1y [expr.new]p22:
2557 // For a non-placement allocation function, the normal deallocation
2558 // function lookup is used
Richard Smithb2f0f052016-10-10 18:54:32 +00002559 //
2560 // Per [expr.delete]p10, this lookup prefers a member operator delete
2561 // without a size_t argument, but prefers a non-member operator delete
2562 // with a size_t where possible (which it always is in this case).
2563 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2564 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2565 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2566 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2567 &BestDeallocFns);
2568 if (Selected)
2569 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2570 else {
2571 // If we failed to select an operator, all remaining functions are viable
2572 // but ambiguous.
2573 for (auto Fn : BestDeallocFns)
2574 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
Richard Smith1cdec012013-09-29 04:40:38 +00002575 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002576 }
2577
2578 // C++ [expr.new]p20:
2579 // [...] If the lookup finds a single matching deallocation
2580 // function, that function will be called; otherwise, no
2581 // deallocation function will be called.
2582 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00002583 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002584
Richard Smithb2f0f052016-10-10 18:54:32 +00002585 // C++1z [expr.new]p23:
2586 // If the lookup finds a usual deallocation function (3.7.4.2)
2587 // with a parameter of type std::size_t and that function, considered
Douglas Gregor6642ca22010-02-26 05:06:18 +00002588 // as a placement deallocation function, would have been
2589 // selected as a match for the allocation function, the program
2590 // is ill-formed.
Richard Smithb2f0f052016-10-10 18:54:32 +00002591 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
Richard Smith1cdec012013-09-29 04:40:38 +00002592 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00002593 UsualDeallocFnInfo Info(*this,
2594 DeclAccessPair::make(OperatorDelete, AS_public));
Richard Smithb2f0f052016-10-10 18:54:32 +00002595 // Core issue, per mail to core reflector, 2016-10-09:
2596 // If this is a member operator delete, and there is a corresponding
2597 // non-sized member operator delete, this isn't /really/ a sized
2598 // deallocation function, it just happens to have a size_t parameter.
2599 bool IsSizedDelete = Info.HasSizeT;
2600 if (IsSizedDelete && !FoundGlobalDelete) {
2601 auto NonSizedDelete =
2602 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2603 /*WantAlign*/Info.HasAlignValT);
2604 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2605 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2606 IsSizedDelete = false;
2607 }
2608
2609 if (IsSizedDelete) {
2610 SourceRange R = PlaceArgs.empty()
2611 ? SourceRange()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002612 : SourceRange(PlaceArgs.front()->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002613 PlaceArgs.back()->getEndLoc());
Richard Smithb2f0f052016-10-10 18:54:32 +00002614 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2615 if (!OperatorDelete->isImplicit())
2616 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2617 << DeleteName;
2618 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002619 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002620
2621 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2622 Matches[0].first);
2623 } else if (!Matches.empty()) {
2624 // We found multiple suitable operators. Per [expr.new]p20, that means we
2625 // call no 'operator delete' function, but we should at least warn the user.
2626 // FIXME: Suppress this warning if the construction cannot throw.
2627 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2628 << DeleteName << AllocElemType;
2629
2630 for (auto &Match : Matches)
2631 Diag(Match.second->getLocation(),
2632 diag::note_member_declared_here) << DeleteName;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002633 }
2634
Sebastian Redlfaf68082008-12-03 20:26:15 +00002635 return false;
2636}
2637
2638/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2639/// delete. These are:
2640/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00002641/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00002642/// void* operator new(std::size_t) throw(std::bad_alloc);
2643/// void* operator new[](std::size_t) throw(std::bad_alloc);
2644/// void operator delete(void *) throw();
2645/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002646/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002647/// void* operator new(std::size_t);
2648/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002649/// void operator delete(void *) noexcept;
2650/// void operator delete[](void *) noexcept;
2651/// // C++1y:
2652/// void* operator new(std::size_t);
2653/// void* operator new[](std::size_t);
2654/// void operator delete(void *) noexcept;
2655/// void operator delete[](void *) noexcept;
2656/// void operator delete(void *, std::size_t) noexcept;
2657/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002658/// @endcode
2659/// Note that the placement and nothrow forms of new are *not* implicitly
2660/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00002661void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002662 if (GlobalNewDeleteDeclared)
2663 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002664
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002665 // OpenCL C++ 1.0 s2.9: the implicitly declared new and delete operators
2666 // are not supported.
2667 if (getLangOpts().OpenCLCPlusPlus)
2668 return;
2669
Douglas Gregor87f54062009-09-15 22:30:29 +00002670 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002671 // [...] The following allocation and deallocation functions (18.4) are
2672 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00002673 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002674 //
Sebastian Redl37588092011-03-14 18:08:30 +00002675 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00002676 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002677 // void* operator new[](std::size_t) throw(std::bad_alloc);
2678 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00002679 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002680 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002681 // void* operator new(std::size_t);
2682 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002683 // void operator delete(void*) noexcept;
2684 // void operator delete[](void*) noexcept;
2685 // C++1y:
2686 // void* operator new(std::size_t);
2687 // void* operator new[](std::size_t);
2688 // void operator delete(void*) noexcept;
2689 // void operator delete[](void*) noexcept;
2690 // void operator delete(void*, std::size_t) noexcept;
2691 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00002692 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002693 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00002694 // new, operator new[], operator delete, operator delete[].
2695 //
2696 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2697 // "std" or "bad_alloc" as necessary to form the exception specification.
2698 // However, we do not make these implicit declarations visible to name
2699 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002700 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00002701 // The "std::bad_alloc" class has not yet been declared, so build it
2702 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002703 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2704 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002705 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002706 &PP.getIdentifierTable().get("bad_alloc"),
Craig Topperc3ec1492014-05-26 06:22:03 +00002707 nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002708 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00002709 }
Richard Smith59139022016-09-30 22:41:36 +00002710 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
Richard Smith96269c52016-09-29 22:49:46 +00002711 // The "std::align_val_t" enum class has not yet been declared, so build it
2712 // implicitly.
2713 auto *AlignValT = EnumDecl::Create(
2714 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2715 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2716 AlignValT->setIntegerType(Context.getSizeType());
2717 AlignValT->setPromotionType(Context.getSizeType());
2718 AlignValT->setImplicit(true);
2719 StdAlignValT = AlignValT;
2720 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002721
Sebastian Redlfaf68082008-12-03 20:26:15 +00002722 GlobalNewDeleteDeclared = true;
2723
2724 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2725 QualType SizeT = Context.getSizeType();
2726
Richard Smith96269c52016-09-29 22:49:46 +00002727 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2728 QualType Return, QualType Param) {
2729 llvm::SmallVector<QualType, 3> Params;
2730 Params.push_back(Param);
2731
2732 // Create up to four variants of the function (sized/aligned).
2733 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2734 (Kind == OO_Delete || Kind == OO_Array_Delete);
Richard Smith59139022016-09-30 22:41:36 +00002735 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002736
2737 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2738 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2739 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
Richard Smith96269c52016-09-29 22:49:46 +00002740 if (Sized)
2741 Params.push_back(SizeT);
2742
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002743 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
Richard Smith96269c52016-09-29 22:49:46 +00002744 if (Aligned)
2745 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2746
2747 DeclareGlobalAllocationFunction(
2748 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2749
2750 if (Aligned)
2751 Params.pop_back();
2752 }
2753 }
2754 };
2755
2756 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2757 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2758 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2759 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002760}
2761
2762/// DeclareGlobalAllocationFunction - Declares a single implicit global
2763/// allocation function if it doesn't already exist.
2764void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002765 QualType Return,
Richard Smith96269c52016-09-29 22:49:46 +00002766 ArrayRef<QualType> Params) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002767 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2768
2769 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002770 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2771 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2772 Alloc != AllocEnd; ++Alloc) {
2773 // Only look at non-template functions, as it is the predefined,
2774 // non-templated allocation function we are trying to declare here.
2775 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith96269c52016-09-29 22:49:46 +00002776 if (Func->getNumParams() == Params.size()) {
2777 llvm::SmallVector<QualType, 3> FuncParams;
2778 for (auto *P : Func->parameters())
2779 FuncParams.push_back(
2780 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2781 if (llvm::makeArrayRef(FuncParams) == Params) {
Serge Pavlovd5489072013-09-14 12:00:01 +00002782 // Make the function visible to name lookup, even if we found it in
2783 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002784 // allocation function, or is suppressing that function.
Richard Smith90dc5252017-06-23 01:04:34 +00002785 Func->setVisibleDespiteOwningModule();
Chandler Carruth93538422010-02-03 11:02:14 +00002786 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002787 }
Chandler Carruth93538422010-02-03 11:02:14 +00002788 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002789 }
2790 }
Reid Kleckner7270ef52015-03-19 17:03:58 +00002791
Richard Smithc015bc22014-02-07 22:39:53 +00002792 FunctionProtoType::ExtProtoInfo EPI;
2793
Richard Smithf8b417c2014-02-08 00:42:45 +00002794 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002795 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002796 = (Name.getCXXOverloadedOperator() == OO_New ||
2797 Name.getCXXOverloadedOperator() == OO_Array_New);
John McCalldb40c7f2010-12-14 08:05:40 +00002798 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002799 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8b417c2014-02-08 00:42:45 +00002800 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Richard Smithc015bc22014-02-07 22:39:53 +00002801 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Richard Smith8acb4282014-07-31 21:57:55 +00002802 EPI.ExceptionSpec.Type = EST_Dynamic;
2803 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
Sebastian Redl37588092011-03-14 18:08:30 +00002804 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002805 } else {
Richard Smith8acb4282014-07-31 21:57:55 +00002806 EPI.ExceptionSpec =
2807 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002808 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002809
Artem Belevich07db5cf2016-10-21 20:34:05 +00002810 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2811 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2812 FunctionDecl *Alloc = FunctionDecl::Create(
2813 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2814 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2815 Alloc->setImplicit();
Vassil Vassilev41cafcd2017-06-09 21:36:28 +00002816 // Global allocation functions should always be visible.
Richard Smith90dc5252017-06-23 01:04:34 +00002817 Alloc->setVisibleDespiteOwningModule();
Simon Pilgrim75c26882016-09-30 14:25:09 +00002818
Artem Belevich07db5cf2016-10-21 20:34:05 +00002819 // Implicit sized deallocation functions always have default visibility.
2820 Alloc->addAttr(
2821 VisibilityAttr::CreateImplicit(Context, VisibilityAttr::Default));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002822
Artem Belevich07db5cf2016-10-21 20:34:05 +00002823 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2824 for (QualType T : Params) {
2825 ParamDecls.push_back(ParmVarDecl::Create(
2826 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2827 /*TInfo=*/nullptr, SC_None, nullptr));
2828 ParamDecls.back()->setImplicit();
2829 }
2830 Alloc->setParams(ParamDecls);
2831 if (ExtraAttr)
2832 Alloc->addAttr(ExtraAttr);
2833 Context.getTranslationUnitDecl()->addDecl(Alloc);
2834 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2835 };
2836
2837 if (!LangOpts.CUDA)
2838 CreateAllocationFunctionDecl(nullptr);
2839 else {
2840 // Host and device get their own declaration so each can be
2841 // defined or re-declared independently.
2842 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2843 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
Richard Smithbdd14642014-02-04 01:14:30 +00002844 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002845}
2846
Richard Smith1cdec012013-09-29 04:40:38 +00002847FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2848 bool CanProvideSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00002849 bool Overaligned,
Richard Smith1cdec012013-09-29 04:40:38 +00002850 DeclarationName Name) {
2851 DeclareGlobalNewDelete();
2852
2853 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2854 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2855
Richard Smithb2f0f052016-10-10 18:54:32 +00002856 // FIXME: It's possible for this to result in ambiguity, through a
2857 // user-declared variadic operator delete or the enable_if attribute. We
2858 // should probably not consider those cases to be usual deallocation
2859 // functions. But for now we just make an arbitrary choice in that case.
2860 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2861 Overaligned);
2862 assert(Result.FD && "operator delete missing from global scope?");
2863 return Result.FD;
2864}
Richard Smith1cdec012013-09-29 04:40:38 +00002865
Richard Smithb2f0f052016-10-10 18:54:32 +00002866FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2867 CXXRecordDecl *RD) {
2868 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Richard Smith1cdec012013-09-29 04:40:38 +00002869
Richard Smithb2f0f052016-10-10 18:54:32 +00002870 FunctionDecl *OperatorDelete = nullptr;
2871 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2872 return nullptr;
2873 if (OperatorDelete)
2874 return OperatorDelete;
Artem Belevich94a55e82015-09-22 17:22:59 +00002875
Richard Smithb2f0f052016-10-10 18:54:32 +00002876 // If there's no class-specific operator delete, look up the global
2877 // non-array delete.
2878 return FindUsualDeallocationFunction(
2879 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2880 Name);
Richard Smith1cdec012013-09-29 04:40:38 +00002881}
2882
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002883bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2884 DeclarationName Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00002885 FunctionDecl *&Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002886 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002887 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00002888 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002889
John McCall27b18f82009-11-17 02:14:36 +00002890 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002891 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002892
Chandler Carruthb6f99172010-06-28 00:30:51 +00002893 Found.suppressDiagnostics();
2894
Richard Smithb2f0f052016-10-10 18:54:32 +00002895 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
Chandler Carruth9b418232010-08-08 07:04:00 +00002896
Richard Smithb2f0f052016-10-10 18:54:32 +00002897 // C++17 [expr.delete]p10:
2898 // If the deallocation functions have class scope, the one without a
2899 // parameter of type std::size_t is selected.
2900 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2901 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2902 /*WantAlign*/ Overaligned, &Matches);
Chandler Carruth9b418232010-08-08 07:04:00 +00002903
Richard Smithb2f0f052016-10-10 18:54:32 +00002904 // If we could find an overload, use it.
John McCall66a87592010-08-04 00:31:26 +00002905 if (Matches.size() == 1) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002906 Operator = cast<CXXMethodDecl>(Matches[0].FD);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002907
Richard Smithb2f0f052016-10-10 18:54:32 +00002908 // FIXME: DiagnoseUseOfDecl?
Alexis Hunt1f69a022011-05-12 22:46:29 +00002909 if (Operator->isDeleted()) {
2910 if (Diagnose) {
2911 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00002912 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002913 }
2914 return true;
2915 }
2916
Richard Smith921bd202012-02-26 09:11:52 +00002917 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Richard Smithb2f0f052016-10-10 18:54:32 +00002918 Matches[0].Found, Diagnose) == AR_inaccessible)
Richard Smith921bd202012-02-26 09:11:52 +00002919 return true;
2920
John McCall66a87592010-08-04 00:31:26 +00002921 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002922 }
John McCall66a87592010-08-04 00:31:26 +00002923
Richard Smithb2f0f052016-10-10 18:54:32 +00002924 // We found multiple suitable operators; complain about the ambiguity.
2925 // FIXME: The standard doesn't say to do this; it appears that the intent
2926 // is that this should never happen.
2927 if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002928 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002929 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2930 << Name << RD;
Richard Smithb2f0f052016-10-10 18:54:32 +00002931 for (auto &Match : Matches)
2932 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
Alexis Huntf91729462011-05-12 22:46:25 +00002933 }
John McCall66a87592010-08-04 00:31:26 +00002934 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002935 }
2936
2937 // We did find operator delete/operator delete[] declarations, but
2938 // none of them were suitable.
2939 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002940 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002941 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2942 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002943
Richard Smithb2f0f052016-10-10 18:54:32 +00002944 for (NamedDecl *D : Found)
2945 Diag(D->getUnderlyingDecl()->getLocation(),
Alexis Huntf91729462011-05-12 22:46:25 +00002946 diag::note_member_declared_here) << Name;
2947 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002948 return true;
2949 }
2950
Craig Topperc3ec1492014-05-26 06:22:03 +00002951 Operator = nullptr;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002952 return false;
2953}
2954
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002955namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002956/// Checks whether delete-expression, and new-expression used for
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002957/// initializing deletee have the same array form.
2958class MismatchingNewDeleteDetector {
2959public:
2960 enum MismatchResult {
2961 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2962 NoMismatch,
2963 /// Indicates that variable is initialized with mismatching form of \a new.
2964 VarInitMismatches,
2965 /// Indicates that member is initialized with mismatching form of \a new.
2966 MemberInitMismatches,
2967 /// Indicates that 1 or more constructors' definitions could not been
2968 /// analyzed, and they will be checked again at the end of translation unit.
2969 AnalyzeLater
2970 };
2971
2972 /// \param EndOfTU True, if this is the final analysis at the end of
2973 /// translation unit. False, if this is the initial analysis at the point
2974 /// delete-expression was encountered.
2975 explicit MismatchingNewDeleteDetector(bool EndOfTU)
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002976 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002977 HasUndefinedConstructors(false) {}
2978
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002979 /// Checks whether pointee of a delete-expression is initialized with
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002980 /// matching form of new-expression.
2981 ///
2982 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2983 /// point where delete-expression is encountered, then a warning will be
2984 /// issued immediately. If return value is \c AnalyzeLater at the point where
2985 /// delete-expression is seen, then member will be analyzed at the end of
2986 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2987 /// couldn't be analyzed. If at least one constructor initializes the member
2988 /// with matching type of new, the return value is \c NoMismatch.
2989 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002990 /// Analyzes a class member.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002991 /// \param Field Class member to analyze.
2992 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2993 /// for deleting the \p Field.
2994 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002995 FieldDecl *Field;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002996 /// List of mismatching new-expressions used for initialization of the pointee
2997 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2998 /// Indicates whether delete-expression was in array form.
2999 bool IsArrayForm;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003000
3001private:
3002 const bool EndOfTU;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003003 /// Indicates that there is at least one constructor without body.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003004 bool HasUndefinedConstructors;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003005 /// Returns \c CXXNewExpr from given initialization expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003006 /// \param E Expression used for initializing pointee in delete-expression.
NAKAMURA Takumi4bd67d82015-05-19 06:47:23 +00003007 /// E can be a single-element \c InitListExpr consisting of new-expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003008 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003009 /// Returns whether member is initialized with mismatching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003010 /// \c new either by the member initializer or in-class initialization.
3011 ///
3012 /// If bodies of all constructors are not visible at the end of translation
3013 /// unit or at least one constructor initializes member with the matching
3014 /// form of \c new, mismatch cannot be proven, and this function will return
3015 /// \c NoMismatch.
3016 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003017 /// Returns whether variable is initialized with mismatching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003018 /// \c new.
3019 ///
3020 /// If variable is initialized with matching form of \c new or variable is not
3021 /// initialized with a \c new expression, this function will return true.
3022 /// If variable is initialized with mismatching form of \c new, returns false.
3023 /// \param D Variable to analyze.
3024 bool hasMatchingVarInit(const DeclRefExpr *D);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003025 /// Checks whether the constructor initializes pointee with mismatching
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003026 /// form of \c new.
3027 ///
3028 /// Returns true, if member is initialized with matching form of \c new in
3029 /// member initializer list. Returns false, if member is initialized with the
3030 /// matching form of \c new in this constructor's initializer or given
3031 /// constructor isn't defined at the point where delete-expression is seen, or
3032 /// member isn't initialized by the constructor.
3033 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003034 /// Checks whether member is initialized with matching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003035 /// \c new in member initializer list.
3036 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3037 /// Checks whether member is initialized with mismatching form of \c new by
3038 /// in-class initializer.
3039 MismatchResult analyzeInClassInitializer();
3040};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003041}
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003042
3043MismatchingNewDeleteDetector::MismatchResult
3044MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3045 NewExprs.clear();
3046 assert(DE && "Expected delete-expression");
3047 IsArrayForm = DE->isArrayForm();
3048 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3049 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3050 return analyzeMemberExpr(ME);
3051 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3052 if (!hasMatchingVarInit(D))
3053 return VarInitMismatches;
3054 }
3055 return NoMismatch;
3056}
3057
3058const CXXNewExpr *
3059MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3060 assert(E != nullptr && "Expected a valid initializer expression");
3061 E = E->IgnoreParenImpCasts();
3062 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3063 if (ILE->getNumInits() == 1)
3064 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3065 }
3066
3067 return dyn_cast_or_null<const CXXNewExpr>(E);
3068}
3069
3070bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3071 const CXXCtorInitializer *CI) {
3072 const CXXNewExpr *NE = nullptr;
3073 if (Field == CI->getMember() &&
3074 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3075 if (NE->isArray() == IsArrayForm)
3076 return true;
3077 else
3078 NewExprs.push_back(NE);
3079 }
3080 return false;
3081}
3082
3083bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3084 const CXXConstructorDecl *CD) {
3085 if (CD->isImplicit())
3086 return false;
3087 const FunctionDecl *Definition = CD;
3088 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3089 HasUndefinedConstructors = true;
3090 return EndOfTU;
3091 }
3092 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3093 if (hasMatchingNewInCtorInit(CI))
3094 return true;
3095 }
3096 return false;
3097}
3098
3099MismatchingNewDeleteDetector::MismatchResult
3100MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3101 assert(Field != nullptr && "This should be called only for members");
Ismail Pazarbasi7ff18362015-10-26 19:20:24 +00003102 const Expr *InitExpr = Field->getInClassInitializer();
3103 if (!InitExpr)
3104 return EndOfTU ? NoMismatch : AnalyzeLater;
3105 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003106 if (NE->isArray() != IsArrayForm) {
3107 NewExprs.push_back(NE);
3108 return MemberInitMismatches;
3109 }
3110 }
3111 return NoMismatch;
3112}
3113
3114MismatchingNewDeleteDetector::MismatchResult
3115MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3116 bool DeleteWasArrayForm) {
3117 assert(Field != nullptr && "Analysis requires a valid class member.");
3118 this->Field = Field;
3119 IsArrayForm = DeleteWasArrayForm;
3120 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3121 for (const auto *CD : RD->ctors()) {
3122 if (hasMatchingNewInCtor(CD))
3123 return NoMismatch;
3124 }
3125 if (HasUndefinedConstructors)
3126 return EndOfTU ? NoMismatch : AnalyzeLater;
3127 if (!NewExprs.empty())
3128 return MemberInitMismatches;
3129 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3130 : NoMismatch;
3131}
3132
3133MismatchingNewDeleteDetector::MismatchResult
3134MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3135 assert(ME != nullptr && "Expected a member expression");
3136 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3137 return analyzeField(F, IsArrayForm);
3138 return NoMismatch;
3139}
3140
3141bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3142 const CXXNewExpr *NE = nullptr;
3143 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3144 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3145 NE->isArray() != IsArrayForm) {
3146 NewExprs.push_back(NE);
3147 }
3148 }
3149 return NewExprs.empty();
3150}
3151
3152static void
3153DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3154 const MismatchingNewDeleteDetector &Detector) {
3155 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3156 FixItHint H;
3157 if (!Detector.IsArrayForm)
3158 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3159 else {
3160 SourceLocation RSquare = Lexer::findLocationAfterToken(
3161 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3162 SemaRef.getLangOpts(), true);
3163 if (RSquare.isValid())
3164 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3165 }
3166 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3167 << Detector.IsArrayForm << H;
3168
3169 for (const auto *NE : Detector.NewExprs)
3170 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3171 << Detector.IsArrayForm;
3172}
3173
3174void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3175 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3176 return;
3177 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3178 switch (Detector.analyzeDeleteExpr(DE)) {
3179 case MismatchingNewDeleteDetector::VarInitMismatches:
3180 case MismatchingNewDeleteDetector::MemberInitMismatches: {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003181 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003182 break;
3183 }
3184 case MismatchingNewDeleteDetector::AnalyzeLater: {
3185 DeleteExprs[Detector.Field].push_back(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003186 std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003187 break;
3188 }
3189 case MismatchingNewDeleteDetector::NoMismatch:
3190 break;
3191 }
3192}
3193
3194void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3195 bool DeleteWasArrayForm) {
3196 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3197 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3198 case MismatchingNewDeleteDetector::VarInitMismatches:
3199 llvm_unreachable("This analysis should have been done for class members.");
3200 case MismatchingNewDeleteDetector::AnalyzeLater:
3201 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3202 "translation unit.");
3203 case MismatchingNewDeleteDetector::MemberInitMismatches:
3204 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3205 break;
3206 case MismatchingNewDeleteDetector::NoMismatch:
3207 break;
3208 }
3209}
3210
Sebastian Redlbd150f42008-11-21 19:14:01 +00003211/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3212/// @code ::delete ptr; @endcode
3213/// or
3214/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00003215ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00003216Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00003217 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003218 // C++ [expr.delete]p1:
3219 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00003220 // non-explicit conversion function to a pointer type. The result has type
3221 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003222 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00003223 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3224
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003225 ExprResult Ex = ExE;
Craig Topperc3ec1492014-05-26 06:22:03 +00003226 FunctionDecl *OperatorDelete = nullptr;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003227 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00003228 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00003229
John Wiegley01296292011-04-08 18:41:53 +00003230 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00003231 // Perform lvalue-to-rvalue cast, if needed.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003232 Ex = DefaultLvalueConversion(Ex.get());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00003233 if (Ex.isInvalid())
3234 return ExprError();
John McCallef429022012-03-09 04:08:29 +00003235
John Wiegley01296292011-04-08 18:41:53 +00003236 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003237
Richard Smithccc11812013-05-21 19:05:48 +00003238 class DeleteConverter : public ContextualImplicitConverter {
3239 public:
3240 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003241
Craig Toppere14c0f82014-03-12 04:55:44 +00003242 bool match(QualType ConvType) override {
Richard Smithccc11812013-05-21 19:05:48 +00003243 // FIXME: If we have an operator T* and an operator void*, we must pick
3244 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003245 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00003246 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00003247 return true;
3248 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003249 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003250
Richard Smithccc11812013-05-21 19:05:48 +00003251 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003252 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003253 return S.Diag(Loc, diag::err_delete_operand) << T;
3254 }
3255
3256 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003257 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003258 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3259 }
3260
3261 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003262 QualType T,
3263 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003264 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3265 }
3266
3267 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003268 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003269 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3270 << ConvTy;
3271 }
3272
3273 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003274 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003275 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3276 }
3277
3278 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003279 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003280 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3281 << ConvTy;
3282 }
3283
3284 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003285 QualType T,
3286 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003287 llvm_unreachable("conversion functions are permitted");
3288 }
3289 } Converter;
3290
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003291 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
Richard Smithccc11812013-05-21 19:05:48 +00003292 if (Ex.isInvalid())
3293 return ExprError();
3294 Type = Ex.get()->getType();
3295 if (!Converter.match(Type))
3296 // FIXME: PerformContextualImplicitConversion should return ExprError
3297 // itself in this case.
3298 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003299
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003300 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003301 QualType PointeeElem = Context.getBaseElementType(Pointee);
3302
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00003303 if (Pointee.getAddressSpace() != LangAS::Default &&
3304 !getLangOpts().OpenCLCPlusPlus)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003305 return Diag(Ex.get()->getBeginLoc(),
Eli Friedmanae4280f2011-07-26 22:25:31 +00003306 diag::err_address_space_qualified_delete)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003307 << Pointee.getUnqualifiedType()
3308 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003309
Craig Topperc3ec1492014-05-26 06:22:03 +00003310 CXXRecordDecl *PointeeRD = nullptr;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003311 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003312 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003313 // effectively bans deletion of "void*". However, most compilers support
3314 // this, so we treat it as a warning unless we're in a SFINAE context.
3315 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00003316 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003317 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003318 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00003319 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00003320 } else if (!Pointee->isDependentType()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003321 // FIXME: This can result in errors if the definition was imported from a
3322 // module but is hidden.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003323 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003324 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00003325 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3326 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3327 }
3328 }
3329
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003330 if (Pointee->isArrayType() && !ArrayForm) {
3331 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00003332 << Type << Ex.get()->getSourceRange()
Craig Topper07fa1762015-11-15 02:31:46 +00003333 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003334 ArrayForm = true;
3335 }
3336
Anders Carlssona471db02009-08-16 20:29:29 +00003337 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3338 ArrayForm ? OO_Array_Delete : OO_Delete);
3339
Eli Friedmanae4280f2011-07-26 22:25:31 +00003340 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003341 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00003342 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3343 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00003344 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003345
John McCall284c48f2011-01-27 09:37:56 +00003346 // If we're allocating an array of records, check whether the
3347 // usual operator delete[] has a size_t parameter.
3348 if (ArrayForm) {
3349 // If the user specifically asked to use the global allocator,
3350 // we'll need to do the lookup into the class.
3351 if (UseGlobal)
3352 UsualArrayDeleteWantsSize =
3353 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3354
3355 // Otherwise, the usual operator delete[] should be the
3356 // function we just found.
Richard Smithf03bd302013-12-05 08:30:59 +00003357 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
Richard Smithb2f0f052016-10-10 18:54:32 +00003358 UsualArrayDeleteWantsSize =
Richard Smithf75dcbe2016-10-11 00:21:10 +00003359 UsualDeallocFnInfo(*this,
3360 DeclAccessPair::make(OperatorDelete, AS_public))
3361 .HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00003362 }
3363
Richard Smitheec915d62012-02-18 04:13:32 +00003364 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00003365 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003366 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003367 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00003368 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3369 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003370 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00003371
Nico Weber5a9259c2016-01-15 21:45:31 +00003372 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3373 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3374 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3375 SourceLocation());
Anders Carlssona471db02009-08-16 20:29:29 +00003376 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003377
Richard Smithb2f0f052016-10-10 18:54:32 +00003378 if (!OperatorDelete) {
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00003379 if (getLangOpts().OpenCLCPlusPlus) {
3380 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3381 return ExprError();
3382 }
3383
Richard Smithb2f0f052016-10-10 18:54:32 +00003384 bool IsComplete = isCompleteType(StartLoc, Pointee);
3385 bool CanProvideSize =
3386 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3387 Pointee.isDestructedType());
3388 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3389
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003390 // Look for a global declaration.
Richard Smithb2f0f052016-10-10 18:54:32 +00003391 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3392 Overaligned, DeleteName);
3393 }
Mike Stump11289f42009-09-09 15:08:12 +00003394
Eli Friedmanfa0df832012-02-02 03:46:19 +00003395 MarkFunctionReferenced(StartLoc, OperatorDelete);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003396
Richard Smith5b349582017-10-13 01:55:36 +00003397 // Check access and ambiguity of destructor if we're going to call it.
3398 // Note that this is required even for a virtual delete.
3399 bool IsVirtualDelete = false;
Eli Friedmanae4280f2011-07-26 22:25:31 +00003400 if (PointeeRD) {
3401 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Richard Smith5b349582017-10-13 01:55:36 +00003402 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3403 PDiag(diag::err_access_dtor) << PointeeElem);
3404 IsVirtualDelete = Dtor->isVirtual();
Douglas Gregorfa778132011-02-01 15:50:11 +00003405 }
3406 }
Akira Hatanakacae83f72017-06-29 18:48:40 +00003407
3408 diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true,
3409 *this);
Richard Smith5b349582017-10-13 01:55:36 +00003410
3411 // Convert the operand to the type of the first parameter of operator
3412 // delete. This is only necessary if we selected a destroying operator
3413 // delete that we are going to call (non-virtually); converting to void*
3414 // is trivial and left to AST consumers to handle.
3415 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3416 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
Richard Smith25172012017-12-05 23:54:25 +00003417 Qualifiers Qs = Pointee.getQualifiers();
3418 if (Qs.hasCVRQualifiers()) {
3419 // Qualifiers are irrelevant to this conversion; we're only looking
3420 // for access and ambiguity.
3421 Qs.removeCVRQualifiers();
3422 QualType Unqual = Context.getPointerType(
3423 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3424 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3425 }
Richard Smith5b349582017-10-13 01:55:36 +00003426 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3427 if (Ex.isInvalid())
3428 return ExprError();
3429 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00003430 }
3431
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003432 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003433 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3434 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003435 AnalyzeDeleteExprMismatch(Result);
3436 return Result;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003437}
3438
Eric Fiselierfa752f22018-03-21 19:19:48 +00003439static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
3440 bool IsDelete,
3441 FunctionDecl *&Operator) {
3442
3443 DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
3444 IsDelete ? OO_Delete : OO_New);
3445
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003446 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
Eric Fiselierfa752f22018-03-21 19:19:48 +00003447 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
3448 assert(!R.empty() && "implicitly declared allocation functions not found");
3449 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3450
3451 // We do our own custom access checks below.
3452 R.suppressDiagnostics();
3453
3454 SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end());
3455 OverloadCandidateSet Candidates(R.getNameLoc(),
3456 OverloadCandidateSet::CSK_Normal);
3457 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3458 FnOvl != FnOvlEnd; ++FnOvl) {
3459 // Even member operator new/delete are implicitly treated as
3460 // static, so don't use AddMemberCandidate.
3461 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3462
3463 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3464 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3465 /*ExplicitTemplateArgs=*/nullptr, Args,
3466 Candidates,
3467 /*SuppressUserConversions=*/false);
3468 continue;
3469 }
3470
3471 FunctionDecl *Fn = cast<FunctionDecl>(D);
3472 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3473 /*SuppressUserConversions=*/false);
3474 }
3475
3476 SourceRange Range = TheCall->getSourceRange();
3477
3478 // Do the resolution.
3479 OverloadCandidateSet::iterator Best;
3480 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3481 case OR_Success: {
3482 // Got one!
3483 FunctionDecl *FnDecl = Best->Function;
3484 assert(R.getNamingClass() == nullptr &&
3485 "class members should not be considered");
3486
3487 if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3488 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3489 << (IsDelete ? 1 : 0) << Range;
3490 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3491 << R.getLookupName() << FnDecl->getSourceRange();
3492 return true;
3493 }
3494
3495 Operator = FnDecl;
3496 return false;
3497 }
3498
3499 case OR_No_Viable_Function:
3500 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
3501 << R.getLookupName() << Range;
3502 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
3503 return true;
3504
3505 case OR_Ambiguous:
3506 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
3507 << R.getLookupName() << Range;
3508 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
3509 return true;
3510
3511 case OR_Deleted: {
3512 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
3513 << Best->Function->isDeleted() << R.getLookupName()
3514 << S.getDeletedOrUnavailableSuffix(Best->Function) << Range;
3515 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
3516 return true;
3517 }
3518 }
3519 llvm_unreachable("Unreachable, bad result from BestViableFunction");
3520}
3521
3522ExprResult
3523Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3524 bool IsDelete) {
3525 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3526 if (!getLangOpts().CPlusPlus) {
3527 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3528 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3529 << "C++";
3530 return ExprError();
3531 }
3532 // CodeGen assumes it can find the global new and delete to call,
3533 // so ensure that they are declared.
3534 DeclareGlobalNewDelete();
3535
3536 FunctionDecl *OperatorNewOrDelete = nullptr;
3537 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3538 OperatorNewOrDelete))
3539 return ExprError();
3540 assert(OperatorNewOrDelete && "should be found");
3541
3542 TheCall->setType(OperatorNewOrDelete->getReturnType());
3543 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3544 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3545 InitializedEntity Entity =
3546 InitializedEntity::InitializeParameter(Context, ParamTy, false);
3547 ExprResult Arg = PerformCopyInitialization(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003548 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
Eric Fiselierfa752f22018-03-21 19:19:48 +00003549 if (Arg.isInvalid())
3550 return ExprError();
3551 TheCall->setArg(i, Arg.get());
3552 }
3553 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3554 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3555 "Callee expected to be implicit cast to a builtin function pointer");
3556 Callee->setType(OperatorNewOrDelete->getType());
3557
3558 return TheCallResult;
3559}
3560
Nico Weber5a9259c2016-01-15 21:45:31 +00003561void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3562 bool IsDelete, bool CallCanBeVirtual,
3563 bool WarnOnNonAbstractTypes,
3564 SourceLocation DtorLoc) {
Nico Weber955bb842017-08-30 20:25:22 +00003565 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
Nico Weber5a9259c2016-01-15 21:45:31 +00003566 return;
3567
3568 // C++ [expr.delete]p3:
3569 // In the first alternative (delete object), if the static type of the
3570 // object to be deleted is different from its dynamic type, the static
3571 // type shall be a base class of the dynamic type of the object to be
3572 // deleted and the static type shall have a virtual destructor or the
3573 // behavior is undefined.
3574 //
3575 const CXXRecordDecl *PointeeRD = dtor->getParent();
3576 // Note: a final class cannot be derived from, no issue there
3577 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3578 return;
3579
Nico Weberbf2260c2017-08-31 06:17:08 +00003580 // If the superclass is in a system header, there's nothing that can be done.
3581 // The `delete` (where we emit the warning) can be in a system header,
3582 // what matters for this warning is where the deleted type is defined.
3583 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3584 return;
3585
Nico Weber5a9259c2016-01-15 21:45:31 +00003586 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3587 if (PointeeRD->isAbstract()) {
3588 // If the class is abstract, we warn by default, because we're
3589 // sure the code has undefined behavior.
3590 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3591 << ClassType;
3592 } else if (WarnOnNonAbstractTypes) {
3593 // Otherwise, if this is not an array delete, it's a bit suspect,
3594 // but not necessarily wrong.
3595 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3596 << ClassType;
3597 }
3598 if (!IsDelete) {
3599 std::string TypeStr;
3600 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3601 Diag(DtorLoc, diag::note_delete_non_virtual)
3602 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3603 }
3604}
3605
Richard Smith03a4aa32016-06-23 19:02:52 +00003606Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3607 SourceLocation StmtLoc,
3608 ConditionKind CK) {
3609 ExprResult E =
3610 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3611 if (E.isInvalid())
3612 return ConditionError();
Richard Smithb130fe72016-06-23 19:16:49 +00003613 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3614 CK == ConditionKind::ConstexprIf);
Richard Smith03a4aa32016-06-23 19:02:52 +00003615}
3616
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003617/// Check the use of the given variable as a C++ condition in an if,
Douglas Gregor633caca2009-11-23 23:44:04 +00003618/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00003619ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00003620 SourceLocation StmtLoc,
Richard Smith03a4aa32016-06-23 19:02:52 +00003621 ConditionKind CK) {
Richard Smith27d807c2013-04-30 13:56:41 +00003622 if (ConditionVar->isInvalidDecl())
3623 return ExprError();
3624
Douglas Gregor633caca2009-11-23 23:44:04 +00003625 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003626
Douglas Gregor633caca2009-11-23 23:44:04 +00003627 // C++ [stmt.select]p2:
3628 // The declarator shall not specify a function or an array.
3629 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003630 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003631 diag::err_invalid_use_of_function_type)
3632 << ConditionVar->getSourceRange());
3633 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003634 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003635 diag::err_invalid_use_of_array_type)
3636 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00003637
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003638 ExprResult Condition = DeclRefExpr::Create(
3639 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3640 /*enclosing*/ false, ConditionVar->getLocation(),
3641 ConditionVar->getType().getNonReferenceType(), VK_LValue);
Eli Friedman2dfa7932012-01-16 21:00:51 +00003642
Eli Friedmanfa0df832012-02-02 03:46:19 +00003643 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedman2dfa7932012-01-16 21:00:51 +00003644
Richard Smith03a4aa32016-06-23 19:02:52 +00003645 switch (CK) {
3646 case ConditionKind::Boolean:
3647 return CheckBooleanCondition(StmtLoc, Condition.get());
3648
Richard Smithb130fe72016-06-23 19:16:49 +00003649 case ConditionKind::ConstexprIf:
3650 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3651
Richard Smith03a4aa32016-06-23 19:02:52 +00003652 case ConditionKind::Switch:
3653 return CheckSwitchCondition(StmtLoc, Condition.get());
John Wiegley01296292011-04-08 18:41:53 +00003654 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003655
Richard Smith03a4aa32016-06-23 19:02:52 +00003656 llvm_unreachable("unexpected condition kind");
Douglas Gregor633caca2009-11-23 23:44:04 +00003657}
3658
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003659/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
Richard Smithb130fe72016-06-23 19:16:49 +00003660ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003661 // C++ 6.4p4:
3662 // The value of a condition that is an initialized declaration in a statement
3663 // other than a switch statement is the value of the declared variable
3664 // implicitly converted to type bool. If that conversion is ill-formed, the
3665 // program is ill-formed.
3666 // The value of a condition that is an expression is the value of the
3667 // expression, implicitly converted to bool.
3668 //
Richard Smithb130fe72016-06-23 19:16:49 +00003669 // FIXME: Return this value to the caller so they don't need to recompute it.
3670 llvm::APSInt Value(/*BitWidth*/1);
3671 return (IsConstexpr && !CondExpr->isValueDependent())
3672 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3673 CCEK_ConstexprIf)
3674 : PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003675}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003676
3677/// Helper function to determine whether this is the (deprecated) C++
3678/// conversion from a string literal to a pointer to non-const char or
3679/// non-const wchar_t (for narrow and wide string literals,
3680/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00003681bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003682Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3683 // Look inside the implicit cast, if it exists.
3684 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3685 From = Cast->getSubExpr();
3686
3687 // A string literal (2.13.4) that is not a wide string literal can
3688 // be converted to an rvalue of type "pointer to char"; a wide
3689 // string literal can be converted to an rvalue of type "pointer
3690 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00003691 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003692 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00003693 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00003694 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003695 // This conversion is considered only when there is an
3696 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00003697 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3698 switch (StrLit->getKind()) {
3699 case StringLiteral::UTF8:
3700 case StringLiteral::UTF16:
3701 case StringLiteral::UTF32:
3702 // We don't allow UTF literals to be implicitly converted
3703 break;
3704 case StringLiteral::Ascii:
3705 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3706 ToPointeeType->getKind() == BuiltinType::Char_S);
3707 case StringLiteral::Wide:
Dmitry Polukhin9d64f722016-04-14 09:52:06 +00003708 return Context.typesAreCompatible(Context.getWideCharType(),
3709 QualType(ToPointeeType, 0));
Douglas Gregorfb65e592011-07-27 05:40:30 +00003710 }
3711 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003712 }
3713
3714 return false;
3715}
Douglas Gregor39c16d42008-10-24 04:54:22 +00003716
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003717static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00003718 SourceLocation CastLoc,
3719 QualType Ty,
3720 CastKind Kind,
3721 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00003722 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003723 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00003724 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00003725 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003726 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00003727 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00003728 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00003729 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003730
Richard Smith72d74052013-07-20 19:41:36 +00003731 if (S.RequireNonAbstractType(CastLoc, Ty,
3732 diag::err_allocation_of_abstract_type))
3733 return ExprError();
3734
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003735 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003736 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003737
Richard Smith5179eb72016-06-28 19:03:57 +00003738 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3739 InitializedEntity::InitializeTemporary(Ty));
Richard Smith7c9442a2015-02-24 21:44:43 +00003740 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003741 return ExprError();
Richard Smithd59b8322012-12-19 01:39:02 +00003742
Richard Smithf8adcdc2014-07-17 05:12:35 +00003743 ExprResult Result = S.BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003744 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003745 ConstructorArgs, HadMultipleCandidates,
3746 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3747 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00003748 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003749 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003750
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003751 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00003752 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003753
John McCalle3027922010-08-25 11:45:40 +00003754 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00003755 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003756
Richard Smithd3f2d322015-02-24 21:16:19 +00003757 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
Richard Smith7c9442a2015-02-24 21:44:43 +00003758 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003759 return ExprError();
3760
Douglas Gregora4253922010-04-16 22:17:36 +00003761 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00003762 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3763 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003764 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00003765 if (Result.isInvalid())
3766 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00003767 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003768 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3769 CK_UserDefinedConversion, Result.get(),
3770 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003771
Douglas Gregor668443e2011-01-20 00:18:04 +00003772 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00003773 }
3774 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003775}
Douglas Gregora4253922010-04-16 22:17:36 +00003776
Douglas Gregor5fb53972009-01-14 15:45:31 +00003777/// PerformImplicitConversion - Perform an implicit conversion of the
3778/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00003779/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003780/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003781/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00003782ExprResult
3783Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003784 const ImplicitConversionSequence &ICS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003785 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003786 CheckedConversionKind CCK) {
Richard Smith1ef75542018-06-27 20:30:34 +00003787 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
3788 if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType())
3789 return From;
3790
John McCall0d1da222010-01-12 00:44:57 +00003791 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00003792 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003793 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3794 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00003795 if (Res.isInvalid())
3796 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003797 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003798 break;
John Wiegley01296292011-04-08 18:41:53 +00003799 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003800
Anders Carlsson110b07b2009-09-15 06:28:28 +00003801 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003802
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00003803 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00003804 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00003805 QualType BeforeToType;
Richard Smithd3f2d322015-02-24 21:16:19 +00003806 assert(FD && "no conversion function for user-defined conversion seq");
Anders Carlsson110b07b2009-09-15 06:28:28 +00003807 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00003808 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003809
Anders Carlsson110b07b2009-09-15 06:28:28 +00003810 // If the user-defined conversion is specified by a conversion function,
3811 // the initial standard conversion sequence converts the source type to
3812 // the implicit object parameter of the conversion function.
3813 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00003814 } else {
3815 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00003816 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003817 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00003818 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003819 // If the user-defined conversion is specified by a constructor, the
Nico Weberb58e51c2014-11-19 05:21:39 +00003820 // initial standard conversion sequence converts the source type to
3821 // the type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00003822 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3823 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003824 }
Richard Smith72d74052013-07-20 19:41:36 +00003825 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00003826 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00003827 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00003828 PerformImplicitConversion(From, BeforeToType,
3829 ICS.UserDefined.Before, AA_Converting,
3830 CCK);
John Wiegley01296292011-04-08 18:41:53 +00003831 if (Res.isInvalid())
3832 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003833 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00003834 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003835
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003836 ExprResult CastArg = BuildCXXCastArgument(
3837 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
3838 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
3839 ICS.UserDefined.HadMultipleCandidates, From);
Anders Carlssone9766d52009-09-09 21:33:21 +00003840
3841 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00003842 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003843
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003844 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003845
Richard Smith1ef75542018-06-27 20:30:34 +00003846 // C++ [over.match.oper]p7:
3847 // [...] the second standard conversion sequence of a user-defined
3848 // conversion sequence is not applied.
3849 if (CCK == CCK_ForBuiltinOverloadedOp)
3850 return From;
3851
Richard Smith507840d2011-11-29 22:48:16 +00003852 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3853 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00003854 }
John McCall0d1da222010-01-12 00:44:57 +00003855
3856 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00003857 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00003858 PDiag(diag::err_typecheck_ambiguous_condition)
3859 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00003860 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003861
Douglas Gregor39c16d42008-10-24 04:54:22 +00003862 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003863 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003864
3865 case ImplicitConversionSequence::BadConversion:
Richard Smithe15a3702016-10-06 23:12:58 +00003866 bool Diagnosed =
3867 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3868 From->getType(), From, Action);
3869 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
John Wiegley01296292011-04-08 18:41:53 +00003870 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003871 }
3872
3873 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003874 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003875}
3876
Richard Smith507840d2011-11-29 22:48:16 +00003877/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00003878/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00003879/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00003880/// expression. Flavor is the context in which we're performing this
3881/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00003882ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00003883Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00003884 const StandardConversionSequence& SCS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003885 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003886 CheckedConversionKind CCK) {
3887 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003888
Mike Stump87c57ac2009-05-16 07:39:55 +00003889 // Overall FIXME: we are recomputing too many types here and doing far too
3890 // much extra work. What this means is that we need to keep track of more
3891 // information that is computed when we try the implicit conversion initially,
3892 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003893 QualType FromType = From->getType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00003894
Douglas Gregor2fe98832008-11-03 19:09:14 +00003895 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00003896 // FIXME: When can ToType be a reference type?
3897 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003898 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00003899 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003900 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003901 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003902 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00003903 return ExprError();
Richard Smithf8adcdc2014-07-17 05:12:35 +00003904 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003905 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3906 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003907 ConstructorArgs, /*HadMultipleCandidates*/ false,
3908 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3909 CXXConstructExpr::CK_Complete, SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003910 }
Richard Smithf8adcdc2014-07-17 05:12:35 +00003911 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003912 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3913 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003914 From, /*HadMultipleCandidates*/ false,
3915 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3916 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00003917 }
3918
Douglas Gregor980fb162010-04-29 18:24:40 +00003919 // Resolve overloaded function references.
3920 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3921 DeclAccessPair Found;
3922 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3923 true, Found);
3924 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00003925 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00003926
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003927 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
John Wiegley01296292011-04-08 18:41:53 +00003928 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003929
Douglas Gregor980fb162010-04-29 18:24:40 +00003930 From = FixOverloadedFunctionReference(From, Found, Fn);
3931 FromType = From->getType();
3932 }
3933
Richard Smitha23ab512013-05-23 00:30:41 +00003934 // If we're converting to an atomic type, first convert to the corresponding
3935 // non-atomic type.
3936 QualType ToAtomicType;
3937 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3938 ToAtomicType = ToType;
3939 ToType = ToAtomic->getValueType();
3940 }
3941
George Burgess IV8d141e02015-12-14 22:00:49 +00003942 QualType InitialFromType = FromType;
Richard Smith507840d2011-11-29 22:48:16 +00003943 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003944 switch (SCS.First) {
3945 case ICK_Identity:
David Majnemer3087a2b2014-12-28 21:47:31 +00003946 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3947 FromType = FromAtomic->getValueType().getUnqualifiedType();
3948 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3949 From, /*BasePath=*/nullptr, VK_RValue);
3950 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003951 break;
3952
Eli Friedman946b7b52012-01-24 22:51:26 +00003953 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00003954 assert(From->getObjectKind() != OK_ObjCProperty);
Eli Friedman946b7b52012-01-24 22:51:26 +00003955 ExprResult FromRes = DefaultLvalueConversion(From);
3956 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003957 From = FromRes.get();
David Majnemere7029bc2014-12-16 06:31:17 +00003958 FromType = From->getType();
John McCall34376a62010-12-04 03:47:34 +00003959 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00003960 }
John McCall34376a62010-12-04 03:47:34 +00003961
Douglas Gregor39c16d42008-10-24 04:54:22 +00003962 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003963 FromType = Context.getArrayDecayedType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003964 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003965 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003966 break;
3967
3968 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003969 FromType = Context.getPointerType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003970 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003971 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003972 break;
3973
3974 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003975 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003976 }
3977
Richard Smith507840d2011-11-29 22:48:16 +00003978 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00003979 switch (SCS.Second) {
3980 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00003981 // C++ [except.spec]p5:
3982 // [For] assignment to and initialization of pointers to functions,
3983 // pointers to member functions, and references to functions: the
3984 // target entity shall allow at least the exceptions allowed by the
3985 // source value in the assignment or initialization.
3986 switch (Action) {
3987 case AA_Assigning:
3988 case AA_Initializing:
3989 // Note, function argument passing and returning are initialization.
3990 case AA_Passing:
3991 case AA_Returning:
3992 case AA_Sending:
3993 case AA_Passing_CFAudited:
3994 if (CheckExceptionSpecCompatibility(From, ToType))
3995 return ExprError();
3996 break;
3997
3998 case AA_Casting:
3999 case AA_Converting:
4000 // Casts and implicit conversions are not initialization, so are not
4001 // checked for exception specification mismatches.
4002 break;
4003 }
Sebastian Redl5d431642009-10-10 12:04:10 +00004004 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00004005 break;
4006
4007 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00004008 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00004009 if (ToType->isBooleanType()) {
4010 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4011 SCS.Second == ICK_Integral_Promotion &&
4012 "only enums with fixed underlying type can promote to bool");
4013 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004014 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00004015 } else {
4016 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004017 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00004018 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004019 break;
4020
4021 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00004022 case ICK_Floating_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004023 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004024 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004025 break;
4026
4027 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00004028 case ICK_Complex_Conversion: {
4029 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
4030 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
4031 CastKind CK;
4032 if (FromEl->isRealFloatingType()) {
4033 if (ToEl->isRealFloatingType())
4034 CK = CK_FloatingComplexCast;
4035 else
4036 CK = CK_FloatingComplexToIntegralComplex;
4037 } else if (ToEl->isRealFloatingType()) {
4038 CK = CK_IntegralComplexToFloatingComplex;
4039 } else {
4040 CK = CK_IntegralComplexCast;
4041 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004042 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004043 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004044 break;
John McCall8cb679e2010-11-15 09:13:47 +00004045 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004046
Douglas Gregor39c16d42008-10-24 04:54:22 +00004047 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00004048 if (ToType->isRealFloatingType())
Simon Pilgrim75c26882016-09-30 14:25:09 +00004049 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004050 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004051 else
Simon Pilgrim75c26882016-09-30 14:25:09 +00004052 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004053 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004054 break;
4055
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00004056 case ICK_Compatible_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004057 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004058 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004059 break;
4060
John McCall31168b02011-06-15 23:02:42 +00004061 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004062 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004063 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00004064 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00004065 if (Action == AA_Initializing || Action == AA_Assigning)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004066 Diag(From->getBeginLoc(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004067 diag::ext_typecheck_convert_incompatible_pointer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004068 << ToType << From->getType() << Action << From->getSourceRange()
4069 << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004070 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004071 Diag(From->getBeginLoc(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004072 diag::ext_typecheck_convert_incompatible_pointer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004073 << From->getType() << ToType << Action << From->getSourceRange()
4074 << 0;
John McCall31168b02011-06-15 23:02:42 +00004075
Douglas Gregor33823722011-06-11 01:09:30 +00004076 if (From->getType()->isObjCObjectPointerType() &&
4077 ToType->isObjCObjectPointerType())
4078 EmitRelatedResultTypeNote(From);
Brian Kelley11352a82017-03-29 18:09:02 +00004079 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4080 !CheckObjCARCUnavailableWeakConversion(ToType,
4081 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00004082 if (Action == AA_Initializing)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004083 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
John McCall9c3467e2011-09-09 06:12:06 +00004084 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004085 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4086 << (Action == AA_Casting) << From->getType() << ToType
4087 << From->getSourceRange();
John McCall9c3467e2011-09-09 06:12:06 +00004088 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004089
Richard Smith354abec2017-12-08 23:29:59 +00004090 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00004091 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00004092 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004093 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00004094
4095 // Make sure we extend blocks if necessary.
4096 // FIXME: doing this here is really ugly.
4097 if (Kind == CK_BlockPointerToObjCPointerCast) {
4098 ExprResult E = From;
4099 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004100 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00004101 }
Brian Kelley11352a82017-03-29 18:09:02 +00004102 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4103 CheckObjCConversion(SourceRange(), ToType, From, CCK);
Richard Smith507840d2011-11-29 22:48:16 +00004104 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004105 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004106 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004107 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004108
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004109 case ICK_Pointer_Member: {
Richard Smith354abec2017-12-08 23:29:59 +00004110 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00004111 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00004112 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004113 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00004114 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00004115 return ExprError();
David Majnemerd96b9972014-08-08 00:10:39 +00004116
4117 // We may not have been able to figure out what this member pointer resolved
4118 // to up until this exact point. Attempt to lock-in it's inheritance model.
David Majnemerfc22e472015-06-12 17:55:44 +00004119 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00004120 (void)isCompleteType(From->getExprLoc(), From->getType());
4121 (void)isCompleteType(From->getExprLoc(), ToType);
David Majnemerfc22e472015-06-12 17:55:44 +00004122 }
David Majnemerd96b9972014-08-08 00:10:39 +00004123
Richard Smith507840d2011-11-29 22:48:16 +00004124 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004125 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004126 break;
4127 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004128
Abramo Bagnara7ccce982011-04-07 09:26:19 +00004129 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004130 // Perform half-to-boolean conversion via float.
4131 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004132 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004133 FromType = Context.FloatTy;
4134 }
4135
Richard Smith507840d2011-11-29 22:48:16 +00004136 From = ImpCastExprToType(From, Context.BoolTy,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004137 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004138 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004139 break;
4140
Douglas Gregor88d292c2010-05-13 16:44:06 +00004141 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00004142 CXXCastPath BasePath;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004143 if (CheckDerivedToBaseConversion(
4144 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4145 From->getSourceRange(), &BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004146 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004147
Richard Smith507840d2011-11-29 22:48:16 +00004148 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4149 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004150 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00004151 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00004152 }
4153
Douglas Gregor46188682010-05-18 22:42:18 +00004154 case ICK_Vector_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004155 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004156 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00004157 break;
4158
George Burgess IVdf1ed002016-01-13 01:52:39 +00004159 case ICK_Vector_Splat: {
Fariborz Jahanian28d94b12015-03-05 23:06:09 +00004160 // Vector splat from any arithmetic type to a vector.
George Burgess IVdf1ed002016-01-13 01:52:39 +00004161 Expr *Elem = prepareVectorSplat(ToType, From).get();
4162 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
4163 /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00004164 break;
George Burgess IVdf1ed002016-01-13 01:52:39 +00004165 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004166
Douglas Gregor46188682010-05-18 22:42:18 +00004167 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00004168 // Case 1. x -> _Complex y
4169 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4170 QualType ElType = ToComplex->getElementType();
4171 bool isFloatingComplex = ElType->isRealFloatingType();
4172
4173 // x -> y
4174 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4175 // do nothing
4176 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00004177 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004178 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00004179 } else {
4180 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00004181 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004182 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00004183 }
4184 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00004185 From = ImpCastExprToType(From, ToType,
4186 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004187 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00004188
4189 // Case 2. _Complex x -> y
4190 } else {
4191 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
4192 assert(FromComplex);
4193
4194 QualType ElType = FromComplex->getElementType();
4195 bool isFloatingComplex = ElType->isRealFloatingType();
4196
4197 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00004198 From = ImpCastExprToType(From, ElType,
4199 isFloatingComplex ? CK_FloatingComplexToReal
Simon Pilgrim75c26882016-09-30 14:25:09 +00004200 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004201 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004202
4203 // x -> y
4204 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4205 // do nothing
4206 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00004207 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004208 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004209 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004210 } else {
4211 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00004212 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004213 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004214 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004215 }
4216 }
Douglas Gregor46188682010-05-18 22:42:18 +00004217 break;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004218
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00004219 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00004220 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004221 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00004222 break;
4223 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004224
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004225 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004226 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004227 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004228 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4229 if (FromRes.isInvalid())
4230 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004231 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004232 assert ((ConvTy == Sema::Compatible) &&
4233 "Improper transparent union conversion");
4234 (void)ConvTy;
4235 break;
4236 }
4237
Guy Benyei259f9f42013-02-07 16:05:33 +00004238 case ICK_Zero_Event_Conversion:
Egor Churaev89831422016-12-23 14:55:49 +00004239 case ICK_Zero_Queue_Conversion:
4240 From = ImpCastExprToType(From, ToType,
Andrew Savonichevb555b762018-10-23 15:19:20 +00004241 CK_ZeroToOCLOpaqueType,
Egor Churaev89831422016-12-23 14:55:49 +00004242 From->getValueKind()).get();
4243 break;
4244
Douglas Gregor46188682010-05-18 22:42:18 +00004245 case ICK_Lvalue_To_Rvalue:
4246 case ICK_Array_To_Pointer:
4247 case ICK_Function_To_Pointer:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004248 case ICK_Function_Conversion:
Douglas Gregor46188682010-05-18 22:42:18 +00004249 case ICK_Qualification:
4250 case ICK_Num_Conversion_Kinds:
George Burgess IV78ed9b42015-10-11 20:37:14 +00004251 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00004252 case ICK_Incompatible_Pointer_Conversion:
David Blaikie83d382b2011-09-23 05:06:16 +00004253 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004254 }
4255
4256 switch (SCS.Third) {
4257 case ICK_Identity:
4258 // Nothing to do.
4259 break;
4260
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004261 case ICK_Function_Conversion:
4262 // If both sides are functions (or pointers/references to them), there could
4263 // be incompatible exception declarations.
4264 if (CheckExceptionSpecCompatibility(From, ToType))
4265 return ExprError();
4266
4267 From = ImpCastExprToType(From, ToType, CK_NoOp,
4268 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4269 break;
4270
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004271 case ICK_Qualification: {
4272 // The qualification keeps the category of the inner expression, unless the
4273 // target type isn't a reference.
Anastasia Stulova04307942018-11-16 16:22:56 +00004274 ExprValueKind VK =
4275 ToType->isReferenceType() ? From->getValueKind() : VK_RValue;
4276
4277 CastKind CK = CK_NoOp;
4278
4279 if (ToType->isReferenceType() &&
4280 ToType->getPointeeType().getAddressSpace() !=
4281 From->getType().getAddressSpace())
4282 CK = CK_AddressSpaceConversion;
4283
4284 if (ToType->isPointerType() &&
4285 ToType->getPointeeType().getAddressSpace() !=
4286 From->getType()->getPointeeType().getAddressSpace())
4287 CK = CK_AddressSpaceConversion;
4288
4289 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4290 /*BasePath=*/nullptr, CCK)
4291 .get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00004292
Douglas Gregore981bb02011-03-14 16:13:32 +00004293 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004294 !getLangOpts().WritableStrings) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004295 Diag(From->getBeginLoc(),
4296 getLangOpts().CPlusPlus11
4297 ? diag::ext_deprecated_string_literal_conversion
4298 : diag::warn_deprecated_string_literal_conversion)
4299 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004300 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00004301
Douglas Gregor39c16d42008-10-24 04:54:22 +00004302 break;
Richard Smitha23ab512013-05-23 00:30:41 +00004303 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004304
Douglas Gregor39c16d42008-10-24 04:54:22 +00004305 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004306 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004307 }
4308
Douglas Gregor298f43d2012-04-12 20:42:30 +00004309 // If this conversion sequence involved a scalar -> atomic conversion, perform
4310 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00004311 if (!ToAtomicType.isNull()) {
4312 assert(Context.hasSameType(
4313 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4314 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004315 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00004316 }
4317
George Burgess IV8d141e02015-12-14 22:00:49 +00004318 // If this conversion sequence succeeded and involved implicitly converting a
4319 // _Nullable type to a _Nonnull one, complain.
Richard Smith1ef75542018-06-27 20:30:34 +00004320 if (!isCast(CCK))
George Burgess IV8d141e02015-12-14 22:00:49 +00004321 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004322 From->getBeginLoc());
George Burgess IV8d141e02015-12-14 22:00:49 +00004323
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004324 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00004325}
4326
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004327/// Check the completeness of a type in a unary type trait.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004328///
4329/// If the particular type trait requires a complete type, tries to complete
4330/// it. If completing the type fails, a diagnostic is emitted and false
4331/// returned. If completing the type succeeds or no completion was required,
4332/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00004333static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004334 SourceLocation Loc,
4335 QualType ArgTy) {
4336 // C++0x [meta.unary.prop]p3:
4337 // For all of the class templates X declared in this Clause, instantiating
4338 // that template with a template argument that is a class template
4339 // specialization may result in the implicit instantiation of the template
4340 // argument if and only if the semantics of X require that the argument
4341 // must be a complete type.
4342 // We apply this rule to all the type trait expressions used to implement
4343 // these class templates. We also try to follow any GCC documented behavior
4344 // in these expressions to ensure portability of standard libraries.
4345 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004346 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00004347 // is_complete_type somewhat obviously cannot require a complete type.
4348 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004349 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004350
4351 // These traits are modeled on the type predicates in C++0x
4352 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4353 // requiring a complete type, as whether or not they return true cannot be
4354 // impacted by the completeness of the type.
4355 case UTT_IsVoid:
4356 case UTT_IsIntegral:
4357 case UTT_IsFloatingPoint:
4358 case UTT_IsArray:
4359 case UTT_IsPointer:
4360 case UTT_IsLvalueReference:
4361 case UTT_IsRvalueReference:
4362 case UTT_IsMemberFunctionPointer:
4363 case UTT_IsMemberObjectPointer:
4364 case UTT_IsEnum:
4365 case UTT_IsUnion:
4366 case UTT_IsClass:
4367 case UTT_IsFunction:
4368 case UTT_IsReference:
4369 case UTT_IsArithmetic:
4370 case UTT_IsFundamental:
4371 case UTT_IsObject:
4372 case UTT_IsScalar:
4373 case UTT_IsCompound:
4374 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004375 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004376
4377 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4378 // which requires some of its traits to have the complete type. However,
4379 // the completeness of the type cannot impact these traits' semantics, and
4380 // so they don't require it. This matches the comments on these traits in
4381 // Table 49.
4382 case UTT_IsConst:
4383 case UTT_IsVolatile:
4384 case UTT_IsSigned:
4385 case UTT_IsUnsigned:
David Majnemer213bea32015-11-16 06:58:51 +00004386
4387 // This type trait always returns false, checking the type is moot.
4388 case UTT_IsInterfaceClass:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004389 return true;
4390
David Majnemer213bea32015-11-16 06:58:51 +00004391 // C++14 [meta.unary.prop]:
4392 // If T is a non-union class type, T shall be a complete type.
4393 case UTT_IsEmpty:
4394 case UTT_IsPolymorphic:
4395 case UTT_IsAbstract:
4396 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4397 if (!RD->isUnion())
4398 return !S.RequireCompleteType(
4399 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4400 return true;
4401
4402 // C++14 [meta.unary.prop]:
4403 // If T is a class type, T shall be a complete type.
4404 case UTT_IsFinal:
4405 case UTT_IsSealed:
4406 if (ArgTy->getAsCXXRecordDecl())
4407 return !S.RequireCompleteType(
4408 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4409 return true;
4410
Richard Smithf03e9082017-06-01 00:28:16 +00004411 // C++1z [meta.unary.prop]:
4412 // remove_all_extents_t<T> shall be a complete type or cv void.
Eric Fiselier07360662017-04-12 22:12:15 +00004413 case UTT_IsAggregate:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004414 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004415 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004416 case UTT_IsStandardLayout:
4417 case UTT_IsPOD:
4418 case UTT_IsLiteral:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004419 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4420 // or an array of unknown bound. But GCC actually imposes the same constraints
4421 // as above.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004422 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004423 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004424 case UTT_HasNothrowConstructor:
4425 case UTT_HasNothrowCopy:
4426 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004427 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00004428 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004429 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004430 case UTT_HasTrivialCopy:
4431 case UTT_HasTrivialDestructor:
4432 case UTT_HasVirtualDestructor:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004433 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4434 LLVM_FALLTHROUGH;
4435
4436 // C++1z [meta.unary.prop]:
4437 // T shall be a complete type, cv void, or an array of unknown bound.
4438 case UTT_IsDestructible:
4439 case UTT_IsNothrowDestructible:
4440 case UTT_IsTriviallyDestructible:
Erich Keanee63e9d72017-10-24 21:31:50 +00004441 case UTT_HasUniqueObjectRepresentations:
Richard Smithf03e9082017-06-01 00:28:16 +00004442 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
Chandler Carruth8e172c62011-05-01 06:51:22 +00004443 return true;
4444
4445 return !S.RequireCompleteType(
Richard Smithf03e9082017-06-01 00:28:16 +00004446 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00004447 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00004448}
4449
Joao Matosc9523d42013-03-27 01:34:16 +00004450static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4451 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004452 bool (CXXRecordDecl::*HasTrivial)() const,
4453 bool (CXXRecordDecl::*HasNonTrivial)() const,
Joao Matosc9523d42013-03-27 01:34:16 +00004454 bool (CXXMethodDecl::*IsDesiredOp)() const)
4455{
4456 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4457 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4458 return true;
4459
4460 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4461 DeclarationNameInfo NameInfo(Name, KeyLoc);
4462 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4463 if (Self.LookupQualifiedName(Res, RD)) {
4464 bool FoundOperator = false;
4465 Res.suppressDiagnostics();
4466 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4467 Op != OpEnd; ++Op) {
4468 if (isa<FunctionTemplateDecl>(*Op))
4469 continue;
4470
4471 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4472 if((Operator->*IsDesiredOp)()) {
4473 FoundOperator = true;
4474 const FunctionProtoType *CPT =
4475 Operator->getType()->getAs<FunctionProtoType>();
4476 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Richard Smitheaf11ad2018-05-03 03:58:32 +00004477 if (!CPT || !CPT->isNothrow())
Joao Matosc9523d42013-03-27 01:34:16 +00004478 return false;
4479 }
4480 }
4481 return FoundOperator;
4482 }
4483 return false;
4484}
4485
Alp Toker95e7ff22014-01-01 05:57:51 +00004486static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004487 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004488 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00004489
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004490 ASTContext &C = Self.Context;
4491 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004492 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004493 // Type trait expressions corresponding to the primary type category
4494 // predicates in C++0x [meta.unary.cat].
4495 case UTT_IsVoid:
4496 return T->isVoidType();
4497 case UTT_IsIntegral:
4498 return T->isIntegralType(C);
4499 case UTT_IsFloatingPoint:
4500 return T->isFloatingType();
4501 case UTT_IsArray:
4502 return T->isArrayType();
4503 case UTT_IsPointer:
4504 return T->isPointerType();
4505 case UTT_IsLvalueReference:
4506 return T->isLValueReferenceType();
4507 case UTT_IsRvalueReference:
4508 return T->isRValueReferenceType();
4509 case UTT_IsMemberFunctionPointer:
4510 return T->isMemberFunctionPointerType();
4511 case UTT_IsMemberObjectPointer:
4512 return T->isMemberDataPointerType();
4513 case UTT_IsEnum:
4514 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00004515 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00004516 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004517 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00004518 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004519 case UTT_IsFunction:
4520 return T->isFunctionType();
4521
4522 // Type trait expressions which correspond to the convenient composition
4523 // predicates in C++0x [meta.unary.comp].
4524 case UTT_IsReference:
4525 return T->isReferenceType();
4526 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00004527 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004528 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00004529 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004530 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00004531 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004532 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00004533 // Note: semantic analysis depends on Objective-C lifetime types to be
4534 // considered scalar types. However, such types do not actually behave
4535 // like scalar types at run time (since they may require retain/release
4536 // operations), so we report them as non-scalar.
4537 if (T->isObjCLifetimeType()) {
4538 switch (T.getObjCLifetime()) {
4539 case Qualifiers::OCL_None:
4540 case Qualifiers::OCL_ExplicitNone:
4541 return true;
4542
4543 case Qualifiers::OCL_Strong:
4544 case Qualifiers::OCL_Weak:
4545 case Qualifiers::OCL_Autoreleasing:
4546 return false;
4547 }
4548 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004549
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00004550 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004551 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00004552 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004553 case UTT_IsMemberPointer:
4554 return T->isMemberPointerType();
4555
4556 // Type trait expressions which correspond to the type property predicates
4557 // in C++0x [meta.unary.prop].
4558 case UTT_IsConst:
4559 return T.isConstQualified();
4560 case UTT_IsVolatile:
4561 return T.isVolatileQualified();
4562 case UTT_IsTrivial:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004563 return T.isTrivialType(C);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004564 case UTT_IsTriviallyCopyable:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004565 return T.isTriviallyCopyableType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004566 case UTT_IsStandardLayout:
4567 return T->isStandardLayoutType();
4568 case UTT_IsPOD:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004569 return T.isPODType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004570 case UTT_IsLiteral:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004571 return T->isLiteralType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004572 case UTT_IsEmpty:
4573 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4574 return !RD->isUnion() && RD->isEmpty();
4575 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004576 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004577 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004578 return !RD->isUnion() && RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004579 return false;
4580 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004581 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004582 return !RD->isUnion() && RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004583 return false;
Eric Fiselier07360662017-04-12 22:12:15 +00004584 case UTT_IsAggregate:
4585 // Report vector extensions and complex types as aggregates because they
4586 // support aggregate initialization. GCC mirrors this behavior for vectors
4587 // but not _Complex.
4588 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4589 T->isAnyComplexType();
David Majnemer213bea32015-11-16 06:58:51 +00004590 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4591 // even then only when it is used with the 'interface struct ...' syntax
4592 // Clang doesn't support /CLR which makes this type trait moot.
John McCallbf4a7d72012-09-25 07:32:49 +00004593 case UTT_IsInterfaceClass:
John McCallbf4a7d72012-09-25 07:32:49 +00004594 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00004595 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00004596 case UTT_IsSealed:
4597 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004598 return RD->hasAttr<FinalAttr>();
David Majnemera5433082013-10-18 00:33:31 +00004599 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00004600 case UTT_IsSigned:
4601 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00004602 case UTT_IsUnsigned:
4603 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004604
4605 // Type trait expressions which query classes regarding their construction,
4606 // destruction, and copying. Rather than being based directly on the
4607 // related type predicates in the standard, they are specified by both
4608 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4609 // specifications.
4610 //
4611 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4612 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00004613 //
4614 // Note that these builtins do not behave as documented in g++: if a class
4615 // has both a trivial and a non-trivial special member of a particular kind,
4616 // they return false! For now, we emulate this behavior.
4617 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4618 // does not correctly compute triviality in the presence of multiple special
4619 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00004620 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004621 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4622 // If __is_pod (type) is true then the trait is true, else if type is
4623 // a cv class or union type (or array thereof) with a trivial default
4624 // constructor ([class.ctor]) then the trait is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004625 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004626 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004627 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4628 return RD->hasTrivialDefaultConstructor() &&
4629 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004630 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004631 case UTT_HasTrivialMoveConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004632 // This trait is implemented by MSVC 2012 and needed to parse the
4633 // standard library headers. Specifically this is used as the logic
4634 // behind std::is_trivially_move_constructible (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004635 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004636 return true;
4637 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4638 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4639 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004640 case UTT_HasTrivialCopy:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004641 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4642 // If __is_pod (type) is true or type is a reference type then
4643 // the trait is true, else if type is a cv class or union type
4644 // with a trivial copy constructor ([class.copy]) then the trait
4645 // is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004646 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004647 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004648 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4649 return RD->hasTrivialCopyConstructor() &&
4650 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004651 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004652 case UTT_HasTrivialMoveAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004653 // This trait is implemented by MSVC 2012 and needed to parse the
4654 // standard library headers. Specifically it is used as the logic
4655 // behind std::is_trivially_move_assignable (20.9.4.3)
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004656 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004657 return true;
4658 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4659 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4660 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004661 case UTT_HasTrivialAssign:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004662 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4663 // If type is const qualified or is a reference type then the
4664 // trait is false. Otherwise if __is_pod (type) is true then the
4665 // trait is true, else if type is a cv class or union type with
4666 // a trivial copy assignment ([class.copy]) then the trait is
4667 // true, else it is false.
4668 // Note: the const and reference restrictions are interesting,
4669 // given that const and reference members don't prevent a class
4670 // from having a trivial copy assignment operator (but do cause
4671 // errors if the copy assignment operator is actually used, q.v.
4672 // [class.copy]p12).
4673
Richard Smith92f241f2012-12-08 02:53:02 +00004674 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004675 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004676 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004677 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004678 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4679 return RD->hasTrivialCopyAssignment() &&
4680 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004681 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004682 case UTT_IsDestructible:
Richard Smithf03e9082017-06-01 00:28:16 +00004683 case UTT_IsTriviallyDestructible:
Alp Toker73287bf2014-01-20 00:24:09 +00004684 case UTT_IsNothrowDestructible:
David Majnemerac73de92015-08-11 03:03:28 +00004685 // C++14 [meta.unary.prop]:
4686 // For reference types, is_destructible<T>::value is true.
4687 if (T->isReferenceType())
4688 return true;
4689
4690 // Objective-C++ ARC: autorelease types don't require destruction.
4691 if (T->isObjCLifetimeType() &&
4692 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4693 return true;
4694
4695 // C++14 [meta.unary.prop]:
4696 // For incomplete types and function types, is_destructible<T>::value is
4697 // false.
4698 if (T->isIncompleteType() || T->isFunctionType())
4699 return false;
4700
Richard Smithf03e9082017-06-01 00:28:16 +00004701 // A type that requires destruction (via a non-trivial destructor or ARC
4702 // lifetime semantics) is not trivially-destructible.
4703 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4704 return false;
4705
David Majnemerac73de92015-08-11 03:03:28 +00004706 // C++14 [meta.unary.prop]:
4707 // For object types and given U equal to remove_all_extents_t<T>, if the
4708 // expression std::declval<U&>().~U() is well-formed when treated as an
4709 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4710 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4711 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4712 if (!Destructor)
4713 return false;
4714 // C++14 [dcl.fct.def.delete]p2:
4715 // A program that refers to a deleted function implicitly or
4716 // explicitly, other than to declare it, is ill-formed.
4717 if (Destructor->isDeleted())
4718 return false;
4719 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4720 return false;
4721 if (UTT == UTT_IsNothrowDestructible) {
4722 const FunctionProtoType *CPT =
4723 Destructor->getType()->getAs<FunctionProtoType>();
4724 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Richard Smitheaf11ad2018-05-03 03:58:32 +00004725 if (!CPT || !CPT->isNothrow())
David Majnemerac73de92015-08-11 03:03:28 +00004726 return false;
4727 }
4728 }
4729 return true;
4730
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004731 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00004732 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004733 // If __is_pod (type) is true or type is a reference type
4734 // then the trait is true, else if type is a cv class or union
4735 // type (or array thereof) with a trivial destructor
4736 // ([class.dtor]) then the trait is true, else it is
4737 // false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004738 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004739 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004740
John McCall31168b02011-06-15 23:02:42 +00004741 // Objective-C++ ARC: autorelease types don't require destruction.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004742 if (T->isObjCLifetimeType() &&
John McCall31168b02011-06-15 23:02:42 +00004743 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4744 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004745
Richard Smith92f241f2012-12-08 02:53:02 +00004746 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4747 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004748 return false;
4749 // TODO: Propagate nothrowness for implicitly declared special members.
4750 case UTT_HasNothrowAssign:
4751 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4752 // If type is const qualified or is a reference type then the
4753 // trait is false. Otherwise if __has_trivial_assign (type)
4754 // is true then the trait is true, else if type is a cv class
4755 // or union type with copy assignment operators that are known
4756 // not to throw an exception then the trait is true, else it is
4757 // false.
4758 if (C.getBaseElementType(T).isConstQualified())
4759 return false;
4760 if (T->isReferenceType())
4761 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004762 if (T.isPODType(C) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00004763 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004764
Joao Matosc9523d42013-03-27 01:34:16 +00004765 if (const RecordType *RT = T->getAs<RecordType>())
4766 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4767 &CXXRecordDecl::hasTrivialCopyAssignment,
4768 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4769 &CXXMethodDecl::isCopyAssignmentOperator);
4770 return false;
4771 case UTT_HasNothrowMoveAssign:
4772 // This trait is implemented by MSVC 2012 and needed to parse the
4773 // standard library headers. Specifically this is used as the logic
4774 // behind std::is_nothrow_move_assignable (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004775 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004776 return true;
4777
4778 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4779 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4780 &CXXRecordDecl::hasTrivialMoveAssignment,
4781 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4782 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004783 return false;
4784 case UTT_HasNothrowCopy:
4785 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4786 // If __has_trivial_copy (type) is true then the trait is true, else
4787 // if type is a cv class or union type with copy constructors that are
4788 // known not to throw an exception then the trait is true, else it is
4789 // false.
John McCall31168b02011-06-15 23:02:42 +00004790 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004791 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004792 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4793 if (RD->hasTrivialCopyConstructor() &&
4794 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004795 return true;
4796
4797 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004798 unsigned FoundTQs;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004799 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004800 // A template constructor is never a copy constructor.
4801 // FIXME: However, it may actually be selected at the actual overload
4802 // resolution point.
Hal Finkelfec83452016-11-27 16:26:14 +00004803 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004804 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004805 // UsingDecl itself is not a constructor
4806 if (isa<UsingDecl>(ND))
4807 continue;
4808 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004809 if (Constructor->isCopyConstructor(FoundTQs)) {
4810 FoundConstructor = true;
4811 const FunctionProtoType *CPT
4812 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004813 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4814 if (!CPT)
4815 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004816 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004817 // For now, we'll be conservative and assume that they can throw.
Richard Smitheaf11ad2018-05-03 03:58:32 +00004818 if (!CPT->isNothrow() || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00004819 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004820 }
4821 }
4822
Richard Smith938f40b2011-06-11 17:19:42 +00004823 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004824 }
4825 return false;
4826 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00004827 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004828 // If __has_trivial_constructor (type) is true then the trait is
4829 // true, else if type is a cv class or union type (or array
4830 // thereof) with a default constructor that is known not to
4831 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00004832 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004833 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004834 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4835 if (RD->hasTrivialDefaultConstructor() &&
4836 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004837 return true;
4838
Alp Tokerb4bca412014-01-20 00:23:47 +00004839 bool FoundConstructor = false;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004840 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004841 // FIXME: In C++0x, a constructor template can be a default constructor.
Hal Finkelfec83452016-11-27 16:26:14 +00004842 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004843 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004844 // UsingDecl itself is not a constructor
4845 if (isa<UsingDecl>(ND))
4846 continue;
4847 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redlc15c3262010-09-13 22:02:47 +00004848 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00004849 FoundConstructor = true;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004850 const FunctionProtoType *CPT
4851 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004852 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4853 if (!CPT)
4854 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00004855 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004856 // For now, we'll be conservative and assume that they can throw.
Richard Smitheaf11ad2018-05-03 03:58:32 +00004857 if (!CPT->isNothrow() || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00004858 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004859 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004860 }
Alp Tokerb4bca412014-01-20 00:23:47 +00004861 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004862 }
4863 return false;
4864 case UTT_HasVirtualDestructor:
4865 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4866 // If type is a class type with a virtual destructor ([class.dtor])
4867 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00004868 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00004869 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004870 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004871 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004872
4873 // These type trait expressions are modeled on the specifications for the
4874 // Embarcadero C++0x type trait functions:
4875 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4876 case UTT_IsCompleteType:
4877 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4878 // Returns True if and only if T is a complete type at the point of the
4879 // function call.
4880 return !T->isIncompleteType();
Erich Keanee63e9d72017-10-24 21:31:50 +00004881 case UTT_HasUniqueObjectRepresentations:
Erich Keane8a6b7402017-11-30 16:37:02 +00004882 return C.hasUniqueObjectRepresentations(T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004883 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004884}
Sebastian Redl5822f082009-02-07 20:10:22 +00004885
Alp Tokercbb90342013-12-13 20:49:58 +00004886static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4887 QualType RhsT, SourceLocation KeyLoc);
4888
Douglas Gregor29c42f22012-02-24 07:38:34 +00004889static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4890 ArrayRef<TypeSourceInfo *> Args,
4891 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004892 if (Kind <= UTT_Last)
4893 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4894
Eric Fiselier1af6c112018-01-12 00:09:37 +00004895 // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
4896 // traits to avoid duplication.
4897 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
Alp Tokercbb90342013-12-13 20:49:58 +00004898 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4899 Args[1]->getType(), RParenLoc);
4900
Douglas Gregor29c42f22012-02-24 07:38:34 +00004901 switch (Kind) {
Eric Fiselier1af6c112018-01-12 00:09:37 +00004902 case clang::BTT_ReferenceBindsToTemporary:
Alp Toker73287bf2014-01-20 00:24:09 +00004903 case clang::TT_IsConstructible:
4904 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004905 case clang::TT_IsTriviallyConstructible: {
4906 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004907 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004908 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004909 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00004910 // definition for is_constructible, as defined below, is known to call
4911 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00004912 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004913 // The predicate condition for a template specialization
4914 // is_constructible<T, Args...> shall be satisfied if and only if the
4915 // following variable definition would be well-formed for some invented
Douglas Gregor29c42f22012-02-24 07:38:34 +00004916 // variable t:
4917 //
4918 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00004919 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00004920
4921 // Precondition: T and all types in the parameter pack Args shall be
4922 // complete types, (possibly cv-qualified) void, or arrays of
4923 // unknown bound.
Aaron Ballman2bf2cad2015-07-21 21:18:29 +00004924 for (const auto *TSI : Args) {
4925 QualType ArgTy = TSI->getType();
Eli Friedman9ea1e162013-09-11 02:53:02 +00004926 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004927 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004928
Simon Pilgrim75c26882016-09-30 14:25:09 +00004929 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004930 diag::err_incomplete_type_used_in_type_trait_expr))
4931 return false;
4932 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00004933
David Majnemer9658ecc2015-11-13 05:32:43 +00004934 // Make sure the first argument is not incomplete nor a function type.
4935 QualType T = Args[0]->getType();
4936 if (T->isIncompleteType() || T->isFunctionType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004937 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004938
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004939 // Make sure the first argument is not an abstract type.
David Majnemer9658ecc2015-11-13 05:32:43 +00004940 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004941 if (RD && RD->isAbstract())
4942 return false;
4943
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004944 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4945 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004946 ArgExprs.reserve(Args.size() - 1);
4947 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
David Majnemer9658ecc2015-11-13 05:32:43 +00004948 QualType ArgTy = Args[I]->getType();
4949 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4950 ArgTy = S.Context.getRValueReferenceType(ArgTy);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004951 OpaqueArgExprs.push_back(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004952 OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
David Majnemer9658ecc2015-11-13 05:32:43 +00004953 ArgTy.getNonLValueExprType(S.Context),
4954 Expr::getValueKindForType(ArgTy)));
Douglas Gregor29c42f22012-02-24 07:38:34 +00004955 }
Richard Smitha507bfc2014-07-23 20:07:08 +00004956 for (Expr &E : OpaqueArgExprs)
4957 ArgExprs.push_back(&E);
4958
Simon Pilgrim75c26882016-09-30 14:25:09 +00004959 // Perform the initialization in an unevaluated context within a SFINAE
Douglas Gregor29c42f22012-02-24 07:38:34 +00004960 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00004961 EnterExpressionEvaluationContext Unevaluated(
4962 S, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004963 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4964 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4965 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4966 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4967 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004968 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004969 if (Init.Failed())
4970 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004971
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004972 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004973 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4974 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004975
Alp Toker73287bf2014-01-20 00:24:09 +00004976 if (Kind == clang::TT_IsConstructible)
4977 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004978
Eric Fiselier1af6c112018-01-12 00:09:37 +00004979 if (Kind == clang::BTT_ReferenceBindsToTemporary) {
4980 if (!T->isReferenceType())
4981 return false;
4982
4983 return !Init.isDirectReferenceBinding();
4984 }
4985
Alp Toker73287bf2014-01-20 00:24:09 +00004986 if (Kind == clang::TT_IsNothrowConstructible)
4987 return S.canThrow(Result.get()) == CT_Cannot;
4988
4989 if (Kind == clang::TT_IsTriviallyConstructible) {
Brian Kelley93c640b2017-03-29 17:40:35 +00004990 // Under Objective-C ARC and Weak, if the destination has non-trivial
4991 // Objective-C lifetime, this is a non-trivial construction.
4992 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00004993 return false;
4994
4995 // The initialization succeeded; now make sure there are no non-trivial
4996 // calls.
4997 return !Result.get()->hasNonTrivialCall(S.Context);
4998 }
4999
5000 llvm_unreachable("unhandled type trait");
5001 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005002 }
Alp Tokercbb90342013-12-13 20:49:58 +00005003 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00005004 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005005
Douglas Gregor29c42f22012-02-24 07:38:34 +00005006 return false;
5007}
5008
Simon Pilgrim75c26882016-09-30 14:25:09 +00005009ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5010 ArrayRef<TypeSourceInfo *> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00005011 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00005012 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00005013
Alp Toker95e7ff22014-01-01 05:57:51 +00005014 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
5015 *this, Kind, KWLoc, Args[0]->getType()))
5016 return ExprError();
5017
Douglas Gregor29c42f22012-02-24 07:38:34 +00005018 bool Dependent = false;
5019 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5020 if (Args[I]->getType()->isDependentType()) {
5021 Dependent = true;
5022 break;
5023 }
5024 }
Alp Tokercbb90342013-12-13 20:49:58 +00005025
5026 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005027 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00005028 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
5029
5030 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
5031 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005032}
5033
Alp Toker88f64e62013-12-13 21:19:30 +00005034ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5035 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00005036 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005037 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005038 ConvertedArgs.reserve(Args.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00005039
Douglas Gregor29c42f22012-02-24 07:38:34 +00005040 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5041 TypeSourceInfo *TInfo;
5042 QualType T = GetTypeFromParser(Args[I], &TInfo);
5043 if (!TInfo)
5044 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
Simon Pilgrim75c26882016-09-30 14:25:09 +00005045
5046 ConvertedArgs.push_back(TInfo);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005047 }
Alp Tokercbb90342013-12-13 20:49:58 +00005048
Douglas Gregor29c42f22012-02-24 07:38:34 +00005049 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5050}
5051
Alp Tokercbb90342013-12-13 20:49:58 +00005052static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5053 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005054 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
5055 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005056
5057 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00005058 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005059 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00005060 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005061 // Base and Derived are not unions and name the same class type without
5062 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005063
John McCall388ef532011-01-28 22:02:36 +00005064 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
John McCall388ef532011-01-28 22:02:36 +00005065 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
Erik Pilkington07f8c432017-05-10 17:18:56 +00005066 if (!rhsRecord || !lhsRecord) {
5067 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5068 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5069 if (!LHSObjTy || !RHSObjTy)
5070 return false;
5071
5072 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5073 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5074 if (!BaseInterface || !DerivedInterface)
5075 return false;
5076
5077 if (Self.RequireCompleteType(
5078 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5079 return false;
5080
5081 return BaseInterface->isSuperClassOf(DerivedInterface);
5082 }
John McCall388ef532011-01-28 22:02:36 +00005083
5084 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
5085 == (lhsRecord == rhsRecord));
5086
5087 if (lhsRecord == rhsRecord)
5088 return !lhsRecord->getDecl()->isUnion();
5089
5090 // C++0x [meta.rel]p2:
5091 // If Base and Derived are class types and are different types
5092 // (ignoring possible cv-qualifiers) then Derived shall be a
5093 // complete type.
Simon Pilgrim75c26882016-09-30 14:25:09 +00005094 if (Self.RequireCompleteType(KeyLoc, RhsT,
John McCall388ef532011-01-28 22:02:36 +00005095 diag::err_incomplete_type_used_in_type_trait_expr))
5096 return false;
5097
5098 return cast<CXXRecordDecl>(rhsRecord->getDecl())
5099 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5100 }
John Wiegley65497cc2011-04-27 23:09:49 +00005101 case BTT_IsSame:
5102 return Self.Context.hasSameType(LhsT, RhsT);
George Burgess IV31ac1fa2017-10-16 22:58:37 +00005103 case BTT_TypeCompatible: {
5104 // GCC ignores cv-qualifiers on arrays for this builtin.
5105 Qualifiers LhsQuals, RhsQuals;
5106 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5107 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5108 return Self.Context.typesAreCompatible(Lhs, Rhs);
5109 }
John Wiegley65497cc2011-04-27 23:09:49 +00005110 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00005111 case BTT_IsConvertibleTo: {
5112 // C++0x [meta.rel]p4:
5113 // Given the following function prototype:
5114 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005115 // template <class T>
Douglas Gregor8006e762011-01-27 20:28:01 +00005116 // typename add_rvalue_reference<T>::type create();
5117 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005118 // the predicate condition for a template specialization
5119 // is_convertible<From, To> shall be satisfied if and only if
5120 // the return expression in the following code would be
Douglas Gregor8006e762011-01-27 20:28:01 +00005121 // well-formed, including any implicit conversions to the return
5122 // type of the function:
5123 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005124 // To test() {
Douglas Gregor8006e762011-01-27 20:28:01 +00005125 // return create<From>();
5126 // }
5127 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005128 // Access checking is performed as if in a context unrelated to To and
5129 // From. Only the validity of the immediate context of the expression
Douglas Gregor8006e762011-01-27 20:28:01 +00005130 // of the return-statement (including conversions to the return type)
5131 // is considered.
5132 //
5133 // We model the initialization as a copy-initialization of a temporary
5134 // of the appropriate type, which for this expression is identical to the
5135 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005136
5137 // Functions aren't allowed to return function or array types.
5138 if (RhsT->isFunctionType() || RhsT->isArrayType())
5139 return false;
5140
5141 // A return statement in a void function must have void type.
5142 if (RhsT->isVoidType())
5143 return LhsT->isVoidType();
5144
5145 // A function definition requires a complete, non-abstract return type.
Richard Smithdb0ac552015-12-18 22:40:25 +00005146 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005147 return false;
5148
5149 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00005150 if (LhsT->isObjectType() || LhsT->isFunctionType())
5151 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005152
5153 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00005154 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00005155 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00005156 Expr::getValueKindForType(LhsT));
5157 Expr *FromPtr = &From;
Simon Pilgrim75c26882016-09-30 14:25:09 +00005158 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
Douglas Gregor8006e762011-01-27 20:28:01 +00005159 SourceLocation()));
Simon Pilgrim75c26882016-09-30 14:25:09 +00005160
5161 // Perform the initialization in an unevaluated context within a SFINAE
Eli Friedmana59b1902012-01-25 01:05:57 +00005162 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005163 EnterExpressionEvaluationContext Unevaluated(
5164 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00005165 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5166 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005167 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005168 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00005169 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00005170
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005171 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00005172 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5173 }
Alp Toker73287bf2014-01-20 00:24:09 +00005174
David Majnemerb3d96882016-05-23 17:21:55 +00005175 case BTT_IsAssignable:
Alp Toker73287bf2014-01-20 00:24:09 +00005176 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00005177 case BTT_IsTriviallyAssignable: {
5178 // C++11 [meta.unary.prop]p3:
5179 // is_trivially_assignable is defined as:
5180 // is_assignable<T, U>::value is true and the assignment, as defined by
5181 // is_assignable, is known to call no operation that is not trivial
5182 //
5183 // is_assignable is defined as:
Simon Pilgrim75c26882016-09-30 14:25:09 +00005184 // The expression declval<T>() = declval<U>() is well-formed when
Douglas Gregor1be329d2012-02-23 07:33:15 +00005185 // treated as an unevaluated operand (Clause 5).
5186 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005187 // For both, T and U shall be complete types, (possibly cv-qualified)
Douglas Gregor1be329d2012-02-23 07:33:15 +00005188 // void, or arrays of unknown bound.
5189 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00005190 Self.RequireCompleteType(KeyLoc, LhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00005191 diag::err_incomplete_type_used_in_type_trait_expr))
5192 return false;
5193 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00005194 Self.RequireCompleteType(KeyLoc, RhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00005195 diag::err_incomplete_type_used_in_type_trait_expr))
5196 return false;
5197
5198 // cv void is never assignable.
5199 if (LhsT->isVoidType() || RhsT->isVoidType())
5200 return false;
5201
Simon Pilgrim75c26882016-09-30 14:25:09 +00005202 // Build expressions that emulate the effect of declval<T>() and
Douglas Gregor1be329d2012-02-23 07:33:15 +00005203 // declval<U>().
5204 if (LhsT->isObjectType() || LhsT->isFunctionType())
5205 LhsT = Self.Context.getRValueReferenceType(LhsT);
5206 if (RhsT->isObjectType() || RhsT->isFunctionType())
5207 RhsT = Self.Context.getRValueReferenceType(RhsT);
5208 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5209 Expr::getValueKindForType(LhsT));
5210 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5211 Expr::getValueKindForType(RhsT));
Simon Pilgrim75c26882016-09-30 14:25:09 +00005212
5213 // Attempt the assignment in an unevaluated context within a SFINAE
Douglas Gregor1be329d2012-02-23 07:33:15 +00005214 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005215 EnterExpressionEvaluationContext Unevaluated(
5216 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor1be329d2012-02-23 07:33:15 +00005217 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
Erich Keane1a3b8fd2017-12-12 16:22:31 +00005218 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005219 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5220 &Rhs);
Douglas Gregor1be329d2012-02-23 07:33:15 +00005221 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5222 return false;
5223
David Majnemerb3d96882016-05-23 17:21:55 +00005224 if (BTT == BTT_IsAssignable)
5225 return true;
5226
Alp Toker73287bf2014-01-20 00:24:09 +00005227 if (BTT == BTT_IsNothrowAssignable)
5228 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00005229
Alp Toker73287bf2014-01-20 00:24:09 +00005230 if (BTT == BTT_IsTriviallyAssignable) {
Brian Kelley93c640b2017-03-29 17:40:35 +00005231 // Under Objective-C ARC and Weak, if the destination has non-trivial
5232 // Objective-C lifetime, this is a non-trivial assignment.
5233 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00005234 return false;
5235
5236 return !Result.get()->hasNonTrivialCall(Self.Context);
5237 }
5238
5239 llvm_unreachable("unhandled type trait");
5240 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00005241 }
Alp Tokercbb90342013-12-13 20:49:58 +00005242 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005243 }
5244 llvm_unreachable("Unknown type trait or not implemented");
5245}
5246
John Wiegley6242b6a2011-04-28 00:16:57 +00005247ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5248 SourceLocation KWLoc,
5249 ParsedType Ty,
5250 Expr* DimExpr,
5251 SourceLocation RParen) {
5252 TypeSourceInfo *TSInfo;
5253 QualType T = GetTypeFromParser(Ty, &TSInfo);
5254 if (!TSInfo)
5255 TSInfo = Context.getTrivialTypeSourceInfo(T);
5256
5257 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5258}
5259
5260static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5261 QualType T, Expr *DimExpr,
5262 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005263 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00005264
5265 switch(ATT) {
5266 case ATT_ArrayRank:
5267 if (T->isArrayType()) {
5268 unsigned Dim = 0;
5269 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5270 ++Dim;
5271 T = AT->getElementType();
5272 }
5273 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00005274 }
John Wiegleyd3522222011-04-28 02:06:46 +00005275 return 0;
5276
John Wiegley6242b6a2011-04-28 00:16:57 +00005277 case ATT_ArrayExtent: {
5278 llvm::APSInt Value;
5279 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00005280 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00005281 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00005282 false).isInvalid())
5283 return 0;
5284 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00005285 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5286 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00005287 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00005288 }
Richard Smithf4c51d92012-02-04 09:53:13 +00005289 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00005290
5291 if (T->isArrayType()) {
5292 unsigned D = 0;
5293 bool Matched = false;
5294 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5295 if (Dim == D) {
5296 Matched = true;
5297 break;
5298 }
5299 ++D;
5300 T = AT->getElementType();
5301 }
5302
John Wiegleyd3522222011-04-28 02:06:46 +00005303 if (Matched && T->isArrayType()) {
5304 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5305 return CAT->getSize().getLimitedValue();
5306 }
John Wiegley6242b6a2011-04-28 00:16:57 +00005307 }
John Wiegleyd3522222011-04-28 02:06:46 +00005308 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00005309 }
5310 }
5311 llvm_unreachable("Unknown type trait or not implemented");
5312}
5313
5314ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5315 SourceLocation KWLoc,
5316 TypeSourceInfo *TSInfo,
5317 Expr* DimExpr,
5318 SourceLocation RParen) {
5319 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00005320
Chandler Carruthc5276e52011-05-01 08:48:21 +00005321 // FIXME: This should likely be tracked as an APInt to remove any host
5322 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005323 uint64_t Value = 0;
5324 if (!T->isDependentType())
5325 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5326
Chandler Carruthc5276e52011-05-01 08:48:21 +00005327 // While the specification for these traits from the Embarcadero C++
5328 // compiler's documentation says the return type is 'unsigned int', Clang
5329 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5330 // compiler, there is no difference. On several other platforms this is an
5331 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005332 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5333 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00005334}
5335
John Wiegleyf9f65842011-04-25 06:54:41 +00005336ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005337 SourceLocation KWLoc,
5338 Expr *Queried,
5339 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005340 // If error parsing the expression, ignore.
5341 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005342 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00005343
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005344 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005345
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005346 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00005347}
5348
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005349static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5350 switch (ET) {
5351 case ET_IsLValueExpr: return E->isLValue();
5352 case ET_IsRValueExpr: return E->isRValue();
5353 }
5354 llvm_unreachable("Expression trait not covered by switch");
5355}
5356
John Wiegleyf9f65842011-04-25 06:54:41 +00005357ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005358 SourceLocation KWLoc,
5359 Expr *Queried,
5360 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005361 if (Queried->isTypeDependent()) {
5362 // Delay type-checking for type-dependent expressions.
5363 } else if (Queried->getType()->isPlaceholderType()) {
5364 ExprResult PE = CheckPlaceholderExpr(Queried);
5365 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005366 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005367 }
5368
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005369 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00005370
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005371 return new (Context)
5372 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00005373}
5374
Richard Trieu82402a02011-09-15 21:56:47 +00005375QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00005376 ExprValueKind &VK,
5377 SourceLocation Loc,
5378 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005379 assert(!LHS.get()->getType()->isPlaceholderType() &&
5380 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00005381 "placeholders should have been weeded out by now");
5382
Richard Smith4baaa5a2016-12-03 01:14:32 +00005383 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5384 // temporary materialization conversion otherwise.
5385 if (isIndirect)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005386 LHS = DefaultLvalueConversion(LHS.get());
Richard Smith4baaa5a2016-12-03 01:14:32 +00005387 else if (LHS.get()->isRValue())
5388 LHS = TemporaryMaterializationConversion(LHS.get());
5389 if (LHS.isInvalid())
5390 return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005391
5392 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005393 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00005394 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005395
Sebastian Redl5822f082009-02-07 20:10:22 +00005396 const char *OpSpelling = isIndirect ? "->*" : ".*";
5397 // C++ 5.5p2
5398 // The binary operator .* [p3: ->*] binds its second operand, which shall
5399 // be of type "pointer to member of T" (where T is a completely-defined
5400 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00005401 QualType RHSType = RHS.get()->getType();
5402 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005403 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005404 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005405 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00005406 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005407 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005408
Sebastian Redl5822f082009-02-07 20:10:22 +00005409 QualType Class(MemPtr->getClass(), 0);
5410
Douglas Gregord07ba342010-10-13 20:41:14 +00005411 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5412 // member pointer points must be completely-defined. However, there is no
5413 // reason for this semantic distinction, and the rule is not enforced by
5414 // other compilers. Therefore, we do not check this property, as it is
5415 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00005416
Sebastian Redl5822f082009-02-07 20:10:22 +00005417 // C++ 5.5p2
5418 // [...] to its first operand, which shall be of class T or of a class of
5419 // which T is an unambiguous and accessible base class. [p3: a pointer to
5420 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00005421 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005422 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005423 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5424 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005425 else {
5426 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005427 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00005428 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00005429 return QualType();
5430 }
5431 }
5432
Richard Trieu82402a02011-09-15 21:56:47 +00005433 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005434 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005435 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5436 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005437 return QualType();
5438 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005439
Richard Smith0f59cb32015-12-18 21:45:41 +00005440 if (!IsDerivedFrom(Loc, LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005441 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00005442 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005443 return QualType();
5444 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005445
5446 CXXCastPath BasePath;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005447 if (CheckDerivedToBaseConversion(
5448 LHSType, Class, Loc,
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005449 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005450 &BasePath))
Richard Smithdb05cd32013-12-12 03:40:18 +00005451 return QualType();
5452
Eli Friedman1fcf66b2010-01-16 00:00:48 +00005453 // Cast LHS to type of use.
Richard Smith01e4a7f22017-06-09 22:25:28 +00005454 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5455 if (isIndirect)
5456 UseType = Context.getPointerType(UseType);
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005457 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005458 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00005459 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00005460 }
5461
Richard Trieu82402a02011-09-15 21:56:47 +00005462 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00005463 // Diagnose use of pointer-to-member type which when used as
5464 // the functional cast in a pointer-to-member expression.
5465 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5466 return QualType();
5467 }
John McCall7decc9e2010-11-18 06:31:45 +00005468
Sebastian Redl5822f082009-02-07 20:10:22 +00005469 // C++ 5.5p2
5470 // The result is an object or a function of the type specified by the
5471 // second operand.
5472 // The cv qualifiers are the union of those in the pointer and the left side,
5473 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00005474 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00005475 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00005476
Douglas Gregor1d042092011-01-26 16:40:18 +00005477 // C++0x [expr.mptr.oper]p6:
5478 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005479 // ill-formed if the second operand is a pointer to member function with
5480 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5481 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00005482 // is a pointer to member function with ref-qualifier &&.
5483 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5484 switch (Proto->getRefQualifier()) {
5485 case RQ_None:
5486 // Do nothing
5487 break;
5488
5489 case RQ_LValue:
Richard Smith25923272017-08-25 01:47:55 +00005490 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
Nicolas Lesser1ad0e9f2018-07-13 16:27:45 +00005491 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
5492 // is (exactly) 'const'.
5493 if (Proto->isConst() && !Proto->isVolatile())
Richard Smith25923272017-08-25 01:47:55 +00005494 Diag(Loc, getLangOpts().CPlusPlus2a
5495 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5496 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5497 else
5498 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5499 << RHSType << 1 << LHS.get()->getSourceRange();
5500 }
Douglas Gregor1d042092011-01-26 16:40:18 +00005501 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005502
Douglas Gregor1d042092011-01-26 16:40:18 +00005503 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005504 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005505 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005506 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005507 break;
5508 }
5509 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005510
John McCall7decc9e2010-11-18 06:31:45 +00005511 // C++ [expr.mptr.oper]p6:
5512 // The result of a .* expression whose second operand is a pointer
5513 // to a data member is of the same value category as its
5514 // first operand. The result of a .* expression whose second
5515 // operand is a pointer to a member function is a prvalue. The
5516 // result of an ->* expression is an lvalue if its second operand
5517 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00005518 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00005519 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00005520 return Context.BoundMemberTy;
5521 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00005522 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00005523 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00005524 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00005525 }
John McCall7decc9e2010-11-18 06:31:45 +00005526
Sebastian Redl5822f082009-02-07 20:10:22 +00005527 return Result;
5528}
Sebastian Redl1a99f442009-04-16 17:51:27 +00005529
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005530/// Try to convert a type to another according to C++11 5.16p3.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005531///
5532/// This is part of the parameter validation for the ? operator. If either
5533/// value operand is a class type, the two operands are attempted to be
5534/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005535/// It returns true if the program is ill-formed and has already been diagnosed
5536/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005537static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5538 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00005539 bool &HaveConversion,
5540 QualType &ToType) {
5541 HaveConversion = false;
5542 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005543
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005544 InitializationKind Kind =
5545 InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation());
Richard Smith2414bca2016-04-25 19:30:37 +00005546 // C++11 5.16p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005547 // The process for determining whether an operand expression E1 of type T1
5548 // can be converted to match an operand expression E2 of type T2 is defined
5549 // as follows:
Richard Smith2414bca2016-04-25 19:30:37 +00005550 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5551 // implicitly converted to type "lvalue reference to T2", subject to the
5552 // constraint that in the conversion the reference must bind directly to
5553 // an lvalue.
5554 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005555 // implicitly converted to the type "rvalue reference to R2", subject to
Richard Smith2414bca2016-04-25 19:30:37 +00005556 // the constraint that the reference must bind directly.
5557 if (To->isLValue() || To->isXValue()) {
5558 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5559 : Self.Context.getRValueReferenceType(ToType);
5560
Douglas Gregor838fcc32010-03-26 20:14:36 +00005561 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005562
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005563 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005564 if (InitSeq.isDirectReferenceBinding()) {
5565 ToType = T;
5566 HaveConversion = true;
5567 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005568 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005569
Douglas Gregor838fcc32010-03-26 20:14:36 +00005570 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005571 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005572 }
John McCall65eb8792010-02-25 01:37:24 +00005573
Sebastian Redl1a99f442009-04-16 17:51:27 +00005574 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5575 // -- if E1 and E2 have class type, and the underlying class types are
5576 // the same or one is a base class of the other:
5577 QualType FTy = From->getType();
5578 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005579 const RecordType *FRec = FTy->getAs<RecordType>();
5580 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005581 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Richard Smith0f59cb32015-12-18 21:45:41 +00005582 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5583 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5584 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005585 // E1 can be converted to match E2 if the class of T2 is the
5586 // same type as, or a base class of, the class of T1, and
5587 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00005588 if (FRec == TRec || FDerivedFromT) {
5589 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005590 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005591 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005592 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005593 HaveConversion = true;
5594 return false;
5595 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005596
Douglas Gregor838fcc32010-03-26 20:14:36 +00005597 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005598 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005599 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005600 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005601
Douglas Gregor838fcc32010-03-26 20:14:36 +00005602 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005603 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005604
Douglas Gregor838fcc32010-03-26 20:14:36 +00005605 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5606 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005607 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00005608 // an rvalue).
5609 //
5610 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5611 // to the array-to-pointer or function-to-pointer conversions.
Richard Smith16d31502016-12-21 01:31:56 +00005612 TTy = TTy.getNonLValueExprType(Self.Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005613
Douglas Gregor838fcc32010-03-26 20:14:36 +00005614 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005615 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005616 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00005617 ToType = TTy;
5618 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005619 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005620
Sebastian Redl1a99f442009-04-16 17:51:27 +00005621 return false;
5622}
5623
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005624/// Try to find a common type for two according to C++0x 5.16p5.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005625///
5626/// This is part of the parameter validation for the ? operator. If either
5627/// value operand is a class type, overload resolution is used to find a
5628/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00005629static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005630 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005631 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00005632 OverloadCandidateSet CandidateSet(QuestionLoc,
5633 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00005634 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005635 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005636
5637 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005638 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00005639 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005640 // We found a match. Perform the conversions on the arguments and move on.
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005641 ExprResult LHSRes = Self.PerformImplicitConversion(
5642 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5643 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005644 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005645 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005646 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00005647
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005648 ExprResult RHSRes = Self.PerformImplicitConversion(
5649 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5650 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005651 if (RHSRes.isInvalid())
5652 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005653 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00005654 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00005655 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005656 return false;
John Wiegley01296292011-04-08 18:41:53 +00005657 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005658
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005659 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005660
5661 // Emit a better diagnostic if one of the expressions is a null pointer
5662 // constant and the other is a pointer type. In this case, the user most
5663 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005664 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005665 return true;
5666
5667 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005668 << LHS.get()->getType() << RHS.get()->getType()
5669 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005670 return true;
5671
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005672 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005673 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00005674 << LHS.get()->getType() << RHS.get()->getType()
5675 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00005676 // FIXME: Print the possible common types by printing the return types of
5677 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005678 break;
5679
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005680 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00005681 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005682 }
5683 return true;
5684}
5685
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005686/// Perform an "extended" implicit conversion as returned by
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005687/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00005688static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005689 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005690 InitializationKind Kind =
5691 InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005692 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005693 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005694 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005695 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005696 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005697
John Wiegley01296292011-04-08 18:41:53 +00005698 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005699 return false;
5700}
5701
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005702/// Check the operands of ?: under C++ semantics.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005703///
5704/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5705/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smithf2b084f2012-08-08 06:13:49 +00005706QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5707 ExprResult &RHS, ExprValueKind &VK,
5708 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00005709 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00005710 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5711 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005712
Richard Smith45edb702012-08-07 22:06:48 +00005713 // C++11 [expr.cond]p1
Sebastian Redl1a99f442009-04-16 17:51:27 +00005714 // The first expression is contextually converted to bool.
Simon Dardis7cd58762017-05-12 19:11:06 +00005715 //
5716 // FIXME; GCC's vector extension permits the use of a?b:c where the type of
5717 // a is that of a integer vector with the same number of elements and
5718 // size as the vectors of b and c. If one of either b or c is a scalar
5719 // it is implicitly converted to match the type of the vector.
5720 // Otherwise the expression is ill-formed. If both b and c are scalars,
5721 // then b and c are checked and converted to the type of a if possible.
5722 // Unlike the OpenCL ?: operator, the expression is evaluated as
5723 // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
John Wiegley01296292011-04-08 18:41:53 +00005724 if (!Cond.get()->isTypeDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005725 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00005726 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005727 return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005728 Cond = CondRes;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005729 }
5730
John McCall7decc9e2010-11-18 06:31:45 +00005731 // Assume r-value.
5732 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005733 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00005734
Sebastian Redl1a99f442009-04-16 17:51:27 +00005735 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00005736 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005737 return Context.DependentTy;
5738
Richard Smith45edb702012-08-07 22:06:48 +00005739 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00005740 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00005741 QualType LTy = LHS.get()->getType();
5742 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005743 bool LVoid = LTy->isVoidType();
5744 bool RVoid = RTy->isVoidType();
5745 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005746 // ... one of the following shall hold:
5747 // -- The second or the third operand (but not both) is a (possibly
5748 // parenthesized) throw-expression; the result is of the type
5749 // and value category of the other.
5750 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5751 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5752 if (LThrow != RThrow) {
5753 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5754 VK = NonThrow->getValueKind();
5755 // DR (no number yet): the result is a bit-field if the
5756 // non-throw-expression operand is a bit-field.
5757 OK = NonThrow->getObjectKind();
5758 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00005759 }
5760
Sebastian Redl1a99f442009-04-16 17:51:27 +00005761 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00005762 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005763 if (LVoid && RVoid)
5764 return Context.VoidTy;
5765
5766 // Neither holds, error.
5767 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5768 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00005769 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005770 return QualType();
5771 }
5772
5773 // Neither is void.
5774
Richard Smithf2b084f2012-08-08 06:13:49 +00005775 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005776 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00005777 // either has (cv) class type [...] an attempt is made to convert each of
5778 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005779 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00005780 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005781 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005782 QualType L2RType, R2LType;
5783 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00005784 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005785 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005786 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005787 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005788
Sebastian Redl1a99f442009-04-16 17:51:27 +00005789 // If both can be converted, [...] the program is ill-formed.
5790 if (HaveL2R && HaveR2L) {
5791 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00005792 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005793 return QualType();
5794 }
5795
5796 // If exactly one conversion is possible, that conversion is applied to
5797 // the chosen operand and the converted operands are used in place of the
5798 // original operands for the remainder of this section.
5799 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00005800 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005801 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005802 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005803 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00005804 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005805 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005806 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005807 }
5808 }
5809
Richard Smithf2b084f2012-08-08 06:13:49 +00005810 // C++11 [expr.cond]p3
5811 // if both are glvalues of the same value category and the same type except
5812 // for cv-qualification, an attempt is made to convert each of those
5813 // operands to the type of the other.
Richard Smith1be59c52016-10-22 01:32:19 +00005814 // FIXME:
5815 // Resolving a defect in P0012R1: we extend this to cover all cases where
5816 // one of the operands is reference-compatible with the other, in order
5817 // to support conditionals between functions differing in noexcept.
Richard Smithf2b084f2012-08-08 06:13:49 +00005818 ExprValueKind LVK = LHS.get()->getValueKind();
5819 ExprValueKind RVK = RHS.get()->getValueKind();
5820 if (!Context.hasSameType(LTy, RTy) &&
Richard Smithf2b084f2012-08-08 06:13:49 +00005821 LVK == RVK && LVK != VK_RValue) {
Richard Smith1be59c52016-10-22 01:32:19 +00005822 // DerivedToBase was already handled by the class-specific case above.
5823 // FIXME: Should we allow ObjC conversions here?
5824 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5825 if (CompareReferenceRelationship(
5826 QuestionLoc, LTy, RTy, DerivedToBase,
5827 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005828 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5829 // [...] subject to the constraint that the reference must bind
5830 // directly [...]
5831 !RHS.get()->refersToBitField() &&
5832 !RHS.get()->refersToVectorElement()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005833 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005834 RTy = RHS.get()->getType();
Richard Smith1be59c52016-10-22 01:32:19 +00005835 } else if (CompareReferenceRelationship(
5836 QuestionLoc, RTy, LTy, DerivedToBase,
5837 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005838 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5839 !LHS.get()->refersToBitField() &&
5840 !LHS.get()->refersToVectorElement()) {
Richard Smith1be59c52016-10-22 01:32:19 +00005841 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5842 LTy = LHS.get()->getType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005843 }
5844 }
5845
5846 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00005847 // If the second and third operands are glvalues of the same value
5848 // category and have the same type, the result is of that type and
5849 // value category and it is a bit-field if the second or the third
5850 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00005851 // We only extend this to bitfields, not to the crazy other kinds of
5852 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00005853 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00005854 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00005855 LHS.get()->isOrdinaryOrBitFieldObject() &&
5856 RHS.get()->isOrdinaryOrBitFieldObject()) {
5857 VK = LHS.get()->getValueKind();
5858 if (LHS.get()->getObjectKind() == OK_BitField ||
5859 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00005860 OK = OK_BitField;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005861
5862 // If we have function pointer types, unify them anyway to unify their
5863 // exception specifications, if any.
5864 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5865 Qualifiers Qs = LTy.getQualifiers();
Richard Smith5e9746f2016-10-21 22:00:42 +00005866 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005867 /*ConvertArgs*/false);
5868 LTy = Context.getQualifiedType(LTy, Qs);
5869
5870 assert(!LTy.isNull() && "failed to find composite pointer type for "
5871 "canonically equivalent function ptr types");
5872 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
5873 }
5874
John McCall7decc9e2010-11-18 06:31:45 +00005875 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00005876 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005877
Richard Smithf2b084f2012-08-08 06:13:49 +00005878 // C++11 [expr.cond]p5
5879 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00005880 // do not have the same type, and either has (cv) class type, ...
5881 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5882 // ... overload resolution is used to determine the conversions (if any)
5883 // to be applied to the operands. If the overload resolution fails, the
5884 // program is ill-formed.
5885 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5886 return QualType();
5887 }
5888
Richard Smithf2b084f2012-08-08 06:13:49 +00005889 // C++11 [expr.cond]p6
5890 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00005891 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005892 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5893 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00005894 if (LHS.isInvalid() || RHS.isInvalid())
5895 return QualType();
5896 LTy = LHS.get()->getType();
5897 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005898
5899 // After those conversions, one of the following shall hold:
5900 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005901 // is of that type. If the operands have class type, the result
5902 // is a prvalue temporary of the result type, which is
5903 // copy-initialized from either the second operand or the third
5904 // operand depending on the value of the first operand.
5905 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5906 if (LTy->isRecordType()) {
5907 // The operands have class type. Make a temporary copy.
5908 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00005909
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005910 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5911 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005912 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005913 if (LHSCopy.isInvalid())
5914 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005915
5916 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5917 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005918 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005919 if (RHSCopy.isInvalid())
5920 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005921
John Wiegley01296292011-04-08 18:41:53 +00005922 LHS = LHSCopy;
5923 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005924 }
5925
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005926 // If we have function pointer types, unify them anyway to unify their
5927 // exception specifications, if any.
5928 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5929 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5930 assert(!LTy.isNull() && "failed to find composite pointer type for "
5931 "canonically equivalent function ptr types");
5932 }
5933
Sebastian Redl1a99f442009-04-16 17:51:27 +00005934 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005935 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005936
Douglas Gregor46188682010-05-18 22:42:18 +00005937 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005938 if (LTy->isVectorType() || RTy->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00005939 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5940 /*AllowBothBool*/true,
5941 /*AllowBoolConversions*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00005942
Sebastian Redl1a99f442009-04-16 17:51:27 +00005943 // -- The second and third operands have arithmetic or enumeration type;
5944 // the usual arithmetic conversions are performed to bring them to a
5945 // common type, and the result is of that type.
5946 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005947 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005948 if (LHS.isInvalid() || RHS.isInvalid())
5949 return QualType();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005950 if (ResTy.isNull()) {
5951 Diag(QuestionLoc,
5952 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5953 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5954 return QualType();
5955 }
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005956
5957 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5958 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5959
5960 return ResTy;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005961 }
5962
5963 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00005964 // type and the other is a null pointer constant, or both are null
5965 // pointer constants, at least one of which is non-integral; pointer
5966 // conversions and qualification conversions are performed to bring them
5967 // to their composite pointer type. The result is of the composite
5968 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00005969 // -- The second and third operands have pointer to member type, or one has
5970 // pointer to member type and the other is a null pointer constant;
5971 // pointer to member conversions and qualification conversions are
5972 // performed to bring them to a common type, whose cv-qualification
5973 // shall match the cv-qualification of either the second or the third
5974 // operand. The result is of the common type.
Richard Smith5e9746f2016-10-21 22:00:42 +00005975 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5976 if (!Composite.isNull())
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005977 return Composite;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005978
Douglas Gregor697a3912010-04-01 22:47:07 +00005979 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00005980 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5981 if (!Composite.isNull())
5982 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005983
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005984 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005985 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005986 return QualType();
5987
Sebastian Redl1a99f442009-04-16 17:51:27 +00005988 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005989 << LHS.get()->getType() << RHS.get()->getType()
5990 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005991 return QualType();
5992}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005993
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005994static FunctionProtoType::ExceptionSpecInfo
5995mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
5996 FunctionProtoType::ExceptionSpecInfo ESI2,
5997 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
5998 ExceptionSpecificationType EST1 = ESI1.Type;
5999 ExceptionSpecificationType EST2 = ESI2.Type;
6000
6001 // If either of them can throw anything, that is the result.
6002 if (EST1 == EST_None) return ESI1;
6003 if (EST2 == EST_None) return ESI2;
6004 if (EST1 == EST_MSAny) return ESI1;
6005 if (EST2 == EST_MSAny) return ESI2;
Richard Smitheaf11ad2018-05-03 03:58:32 +00006006 if (EST1 == EST_NoexceptFalse) return ESI1;
6007 if (EST2 == EST_NoexceptFalse) return ESI2;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006008
6009 // If either of them is non-throwing, the result is the other.
6010 if (EST1 == EST_DynamicNone) return ESI2;
6011 if (EST2 == EST_DynamicNone) return ESI1;
6012 if (EST1 == EST_BasicNoexcept) return ESI2;
6013 if (EST2 == EST_BasicNoexcept) return ESI1;
Richard Smitheaf11ad2018-05-03 03:58:32 +00006014 if (EST1 == EST_NoexceptTrue) return ESI2;
6015 if (EST2 == EST_NoexceptTrue) return ESI1;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006016
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006017 // If we're left with value-dependent computed noexcept expressions, we're
6018 // stuck. Before C++17, we can just drop the exception specification entirely,
6019 // since it's not actually part of the canonical type. And this should never
6020 // happen in C++17, because it would mean we were computing the composite
6021 // pointer type of dependent types, which should never happen.
Richard Smitheaf11ad2018-05-03 03:58:32 +00006022 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006023 assert(!S.getLangOpts().CPlusPlus17 &&
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006024 "computing composite pointer type of dependent types");
6025 return FunctionProtoType::ExceptionSpecInfo();
6026 }
6027
6028 // Switch over the possibilities so that people adding new values know to
6029 // update this function.
6030 switch (EST1) {
6031 case EST_None:
6032 case EST_DynamicNone:
6033 case EST_MSAny:
6034 case EST_BasicNoexcept:
Richard Smitheaf11ad2018-05-03 03:58:32 +00006035 case EST_DependentNoexcept:
6036 case EST_NoexceptFalse:
6037 case EST_NoexceptTrue:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006038 llvm_unreachable("handled above");
6039
6040 case EST_Dynamic: {
6041 // This is the fun case: both exception specifications are dynamic. Form
6042 // the union of the two lists.
6043 assert(EST2 == EST_Dynamic && "other cases should already be handled");
6044 llvm::SmallPtrSet<QualType, 8> Found;
6045 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
6046 for (QualType E : Exceptions)
6047 if (Found.insert(S.Context.getCanonicalType(E)).second)
6048 ExceptionTypeStorage.push_back(E);
6049
6050 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
6051 Result.Exceptions = ExceptionTypeStorage;
6052 return Result;
6053 }
6054
6055 case EST_Unevaluated:
6056 case EST_Uninstantiated:
6057 case EST_Unparsed:
6058 llvm_unreachable("shouldn't see unresolved exception specifications here");
6059 }
6060
6061 llvm_unreachable("invalid ExceptionSpecificationType");
6062}
6063
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006064/// Find a merged pointer type and convert the two expressions to it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006065///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006066/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006067/// and @p E2 according to C++1z 5p14. It converts both expressions to this
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006068/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006069/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006070///
Douglas Gregor19175ff2010-04-16 23:20:25 +00006071/// \param Loc The location of the operator requiring these two expressions to
6072/// be converted to the composite pointer type.
6073///
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006074/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006075QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00006076 Expr *&E1, Expr *&E2,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006077 bool ConvertArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006078 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006079
6080 // C++1z [expr]p14:
6081 // The composite pointer type of two operands p1 and p2 having types T1
6082 // and T2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006083 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00006084
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006085 // where at least one is a pointer or pointer to member type or
6086 // std::nullptr_t is:
6087 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
6088 T1->isNullPtrType();
6089 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
6090 T2->isNullPtrType();
6091 if (!T1IsPointerLike && !T2IsPointerLike)
Richard Smithf2b084f2012-08-08 06:13:49 +00006092 return QualType();
Richard Smithf2b084f2012-08-08 06:13:49 +00006093
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006094 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
6095 // This can't actually happen, following the standard, but we also use this
6096 // to implement the end of [expr.conv], which hits this case.
6097 //
6098 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6099 if (T1IsPointerLike &&
6100 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006101 if (ConvertArgs)
6102 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
6103 ? CK_NullToMemberPointer
6104 : CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006105 return T1;
6106 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006107 if (T2IsPointerLike &&
6108 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006109 if (ConvertArgs)
6110 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
6111 ? CK_NullToMemberPointer
6112 : CK_NullToPointer).get();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006113 return T2;
6114 }
Mike Stump11289f42009-09-09 15:08:12 +00006115
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006116 // Now both have to be pointers or member pointers.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006117 if (!T1IsPointerLike || !T2IsPointerLike)
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006118 return QualType();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006119 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
6120 "nullptr_t should be a null pointer constant");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006121
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006122 // - if T1 or T2 is "pointer to cv1 void" and the other type is
6123 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
6124 // the union of cv1 and cv2;
6125 // - if T1 or T2 is "pointer to noexcept function" and the other type is
6126 // "pointer to function", where the function types are otherwise the same,
6127 // "pointer to function";
6128 // FIXME: This rule is defective: it should also permit removing noexcept
6129 // from a pointer to member function. As a Clang extension, we also
6130 // permit removing 'noreturn', so we generalize this rule to;
6131 // - [Clang] If T1 and T2 are both of type "pointer to function" or
6132 // "pointer to member function" and the pointee types can be unified
6133 // by a function pointer conversion, that conversion is applied
6134 // before checking the following rules.
6135 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6136 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6137 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6138 // respectively;
6139 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
6140 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
6141 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
6142 // T1 or the cv-combined type of T1 and T2, respectively;
6143 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6144 // T2;
6145 //
6146 // If looked at in the right way, these bullets all do the same thing.
6147 // What we do here is, we build the two possible cv-combined types, and try
6148 // the conversions in both directions. If only one works, or if the two
6149 // composite types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00006150 // FIXME: extended qualifiers?
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006151 //
6152 // Note that this will fail to find a composite pointer type for "pointer
6153 // to void" and "pointer to function". We can't actually perform the final
6154 // conversion in this case, even though a composite pointer type formally
6155 // exists.
6156 SmallVector<unsigned, 4> QualifierUnion;
6157 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006158 QualType Composite1 = T1;
6159 QualType Composite2 = T2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006160 unsigned NeedConstBefore = 0;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006161 while (true) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006162 const PointerType *Ptr1, *Ptr2;
6163 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
6164 (Ptr2 = Composite2->getAs<PointerType>())) {
6165 Composite1 = Ptr1->getPointeeType();
6166 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006167
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006168 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006169 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00006170 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006171 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006172
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006173 QualifierUnion.push_back(
6174 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
Craig Topperc3ec1492014-05-26 06:22:03 +00006175 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006176 continue;
6177 }
Mike Stump11289f42009-09-09 15:08:12 +00006178
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006179 const MemberPointerType *MemPtr1, *MemPtr2;
6180 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
6181 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
6182 Composite1 = MemPtr1->getPointeeType();
6183 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006184
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006185 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006186 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00006187 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006188 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006189
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006190 QualifierUnion.push_back(
6191 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
6192 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
6193 MemPtr2->getClass()));
6194 continue;
6195 }
Mike Stump11289f42009-09-09 15:08:12 +00006196
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006197 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00006198
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006199 // Cannot unwrap any more types.
6200 break;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006201 }
Mike Stump11289f42009-09-09 15:08:12 +00006202
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006203 // Apply the function pointer conversion to unify the types. We've already
6204 // unwrapped down to the function types, and we want to merge rather than
6205 // just convert, so do this ourselves rather than calling
6206 // IsFunctionConversion.
6207 //
6208 // FIXME: In order to match the standard wording as closely as possible, we
6209 // currently only do this under a single level of pointers. Ideally, we would
6210 // allow this in general, and set NeedConstBefore to the relevant depth on
6211 // the side(s) where we changed anything.
6212 if (QualifierUnion.size() == 1) {
6213 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
6214 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
6215 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
6216 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
6217
6218 // The result is noreturn if both operands are.
6219 bool Noreturn =
6220 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
6221 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
6222 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
6223
6224 // The result is nothrow if both operands are.
6225 SmallVector<QualType, 8> ExceptionTypeStorage;
6226 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
6227 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
6228 ExceptionTypeStorage);
6229
6230 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
6231 FPT1->getParamTypes(), EPI1);
6232 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
6233 FPT2->getParamTypes(), EPI2);
6234 }
6235 }
6236 }
6237
Richard Smith5e9746f2016-10-21 22:00:42 +00006238 if (NeedConstBefore) {
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006239 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006240 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006241 // requirements of C++ [conv.qual]p4 bullet 3.
Richard Smith5e9746f2016-10-21 22:00:42 +00006242 for (unsigned I = 0; I != NeedConstBefore; ++I)
6243 if ((QualifierUnion[I] & Qualifiers::Const) == 0)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006244 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006245 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006246
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006247 // Rewrap the composites as pointers or member pointers with the union CVRs.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006248 auto MOC = MemberOfClass.rbegin();
6249 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
6250 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
6251 auto Classes = *MOC++;
6252 if (Classes.first && Classes.second) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006253 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00006254 Composite1 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006255 Context.getQualifiedType(Composite1, Quals), Classes.first);
John McCall8ccfcb52009-09-24 19:53:00 +00006256 Composite2 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006257 Context.getQualifiedType(Composite2, Quals), Classes.second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006258 } else {
6259 // Rebuild pointer type
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006260 Composite1 =
6261 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
6262 Composite2 =
6263 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006264 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006265 }
6266
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006267 struct Conversion {
6268 Sema &S;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006269 Expr *&E1, *&E2;
6270 QualType Composite;
Richard Smithe38da032016-10-20 07:53:17 +00006271 InitializedEntity Entity;
6272 InitializationKind Kind;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006273 InitializationSequence E1ToC, E2ToC;
Richard Smithe38da032016-10-20 07:53:17 +00006274 bool Viable;
Mike Stump11289f42009-09-09 15:08:12 +00006275
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006276 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
6277 QualType Composite)
Richard Smithe38da032016-10-20 07:53:17 +00006278 : S(S), E1(E1), E2(E2), Composite(Composite),
6279 Entity(InitializedEntity::InitializeTemporary(Composite)),
6280 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
6281 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
6282 Viable(E1ToC && E2ToC) {}
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006283
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006284 bool perform() {
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006285 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
6286 if (E1Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006287 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006288 E1 = E1Result.getAs<Expr>();
6289
6290 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
6291 if (E2Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006292 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006293 E2 = E2Result.getAs<Expr>();
6294
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006295 return false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006296 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006297 };
Douglas Gregor19175ff2010-04-16 23:20:25 +00006298
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006299 // Try to convert to each composite pointer type.
6300 Conversion C1(*this, Loc, E1, E2, Composite1);
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006301 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
6302 if (ConvertArgs && C1.perform())
6303 return QualType();
6304 return C1.Composite;
6305 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006306 Conversion C2(*this, Loc, E1, E2, Composite2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00006307
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006308 if (C1.Viable == C2.Viable) {
6309 // Either Composite1 and Composite2 are viable and are different, or
6310 // neither is viable.
6311 // FIXME: How both be viable and different?
6312 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006313 }
6314
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006315 // Convert to the chosen type.
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006316 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
6317 return QualType();
6318
6319 return C1.Viable ? C1.Composite : C2.Composite;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006320}
Anders Carlsson85a307d2009-05-17 18:41:29 +00006321
John McCalldadc5752010-08-24 06:29:42 +00006322ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00006323 if (!E)
6324 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006325
John McCall31168b02011-06-15 23:02:42 +00006326 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6327
6328 // If the result is a glvalue, we shouldn't bind it.
6329 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006330 return E;
Mike Stump11289f42009-09-09 15:08:12 +00006331
John McCall31168b02011-06-15 23:02:42 +00006332 // In ARC, calls that return a retainable type can return retained,
6333 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006334 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00006335 E->getType()->isObjCRetainableType()) {
6336
6337 bool ReturnsRetained;
6338
6339 // For actual calls, we compute this by examining the type of the
6340 // called value.
6341 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6342 Expr *Callee = Call->getCallee()->IgnoreParens();
6343 QualType T = Callee->getType();
6344
6345 if (T == Context.BoundMemberTy) {
6346 // Handle pointer-to-members.
6347 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6348 T = BinOp->getRHS()->getType();
6349 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6350 T = Mem->getMemberDecl()->getType();
6351 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006352
John McCall31168b02011-06-15 23:02:42 +00006353 if (const PointerType *Ptr = T->getAs<PointerType>())
6354 T = Ptr->getPointeeType();
6355 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6356 T = Ptr->getPointeeType();
6357 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6358 T = MemPtr->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006359
John McCall31168b02011-06-15 23:02:42 +00006360 const FunctionType *FTy = T->getAs<FunctionType>();
6361 assert(FTy && "call to value not of function type?");
6362 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6363
6364 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6365 // type always produce a +1 object.
6366 } else if (isa<StmtExpr>(E)) {
6367 ReturnsRetained = true;
6368
Ted Kremeneke65b0862012-03-06 20:05:56 +00006369 // We hit this case with the lambda conversion-to-block optimization;
6370 // we don't want any extra casts here.
6371 } else if (isa<CastExpr>(E) &&
6372 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006373 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006374
John McCall31168b02011-06-15 23:02:42 +00006375 // For message sends and property references, we try to find an
6376 // actual method. FIXME: we should infer retention by selector in
6377 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00006378 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00006379 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006380 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6381 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00006382 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6383 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00006384 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006385 // Don't do reclaims if we're using the zero-element array
6386 // constant.
6387 if (ArrayLit->getNumElements() == 0 &&
6388 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6389 return E;
6390
Ted Kremeneke65b0862012-03-06 20:05:56 +00006391 D = ArrayLit->getArrayWithObjectsMethod();
6392 } else if (ObjCDictionaryLiteral *DictLit
6393 = dyn_cast<ObjCDictionaryLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006394 // Don't do reclaims if we're using the zero-element dictionary
6395 // constant.
6396 if (DictLit->getNumElements() == 0 &&
6397 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6398 return E;
6399
Ted Kremeneke65b0862012-03-06 20:05:56 +00006400 D = DictLit->getDictWithObjectsMethod();
6401 }
John McCall31168b02011-06-15 23:02:42 +00006402
6403 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00006404
6405 // Don't do reclaims on performSelector calls; despite their
6406 // return type, the invoked method doesn't necessarily actually
6407 // return an object.
6408 if (!ReturnsRetained &&
6409 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006410 return E;
John McCall31168b02011-06-15 23:02:42 +00006411 }
6412
John McCall16de4d22011-11-14 19:53:16 +00006413 // Don't reclaim an object of Class type.
6414 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006415 return E;
John McCall16de4d22011-11-14 19:53:16 +00006416
Tim Shen4a05bb82016-06-21 20:29:17 +00006417 Cleanup.setExprNeedsCleanups(true);
John McCall4db5c3c2011-07-07 06:58:02 +00006418
John McCall2d637d22011-09-10 06:18:15 +00006419 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6420 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006421 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6422 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00006423 }
6424
David Blaikiebbafb8a2012-03-11 07:00:24 +00006425 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006426 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00006427
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006428 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6429 // a fast path for the common case that the type is directly a RecordType.
6430 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00006431 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006432 while (!RT) {
6433 switch (T->getTypeClass()) {
6434 case Type::Record:
6435 RT = cast<RecordType>(T);
6436 break;
6437 case Type::ConstantArray:
6438 case Type::IncompleteArray:
6439 case Type::VariableArray:
6440 case Type::DependentSizedArray:
6441 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6442 break;
6443 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006444 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006445 }
6446 }
Mike Stump11289f42009-09-09 15:08:12 +00006447
Richard Smithfd555f62012-02-22 02:04:18 +00006448 // That should be enough to guarantee that this type is complete, if we're
6449 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00006450 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00006451 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006452 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006453
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006454 bool IsDecltype = ExprEvalContexts.back().ExprContext ==
6455 ExpressionEvaluationContextRecord::EK_Decltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00006456 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00006457
John McCall31168b02011-06-15 23:02:42 +00006458 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00006459 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00006460 CheckDestructorAccess(E->getExprLoc(), Destructor,
6461 PDiag(diag::err_access_dtor_temp)
6462 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006463 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6464 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00006465
Richard Smithfd555f62012-02-22 02:04:18 +00006466 // If destructor is trivial, we can avoid the extra copy.
6467 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006468 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00006469
John McCall28fc7092011-11-10 05:35:25 +00006470 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006471 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006472 }
Richard Smitheec915d62012-02-18 04:13:32 +00006473
6474 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00006475 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6476
6477 if (IsDecltype)
6478 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6479
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006480 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00006481}
6482
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006483ExprResult
John McCall5d413782010-12-06 08:20:24 +00006484Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006485 if (SubExpr.isInvalid())
6486 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006487
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006488 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006489}
6490
John McCall28fc7092011-11-10 05:35:25 +00006491Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00006492 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00006493
Eli Friedman3bda6b12012-02-02 23:15:15 +00006494 CleanupVarDeclMarking();
6495
John McCall28fc7092011-11-10 05:35:25 +00006496 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6497 assert(ExprCleanupObjects.size() >= FirstCleanup);
Tim Shen4a05bb82016-06-21 20:29:17 +00006498 assert(Cleanup.exprNeedsCleanups() ||
6499 ExprCleanupObjects.size() == FirstCleanup);
6500 if (!Cleanup.exprNeedsCleanups())
John McCall28fc7092011-11-10 05:35:25 +00006501 return SubExpr;
6502
Craig Topper5fc8fc22014-08-27 06:28:36 +00006503 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6504 ExprCleanupObjects.size() - FirstCleanup);
John McCall28fc7092011-11-10 05:35:25 +00006505
Tim Shen4a05bb82016-06-21 20:29:17 +00006506 auto *E = ExprWithCleanups::Create(
6507 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
John McCall28fc7092011-11-10 05:35:25 +00006508 DiscardCleanupsInEvaluationContext();
6509
6510 return E;
6511}
6512
John McCall5d413782010-12-06 08:20:24 +00006513Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00006514 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006515
Eli Friedman3bda6b12012-02-02 23:15:15 +00006516 CleanupVarDeclMarking();
6517
Tim Shen4a05bb82016-06-21 20:29:17 +00006518 if (!Cleanup.exprNeedsCleanups())
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006519 return SubStmt;
6520
6521 // FIXME: In order to attach the temporaries, wrap the statement into
6522 // a StmtExpr; currently this is only used for asm statements.
6523 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6524 // a new AsmStmtWithTemporaries.
Benjamin Kramer07420902017-12-24 16:24:20 +00006525 CompoundStmt *CompStmt = CompoundStmt::Create(
6526 Context, SubStmt, SourceLocation(), SourceLocation());
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006527 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6528 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00006529 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006530}
6531
Richard Smithfd555f62012-02-22 02:04:18 +00006532/// Process the expression contained within a decltype. For such expressions,
6533/// certain semantic checks on temporaries are delayed until this point, and
6534/// are omitted for the 'topmost' call in the decltype expression. If the
6535/// topmost call bound a temporary, strip that temporary off the expression.
6536ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006537 assert(ExprEvalContexts.back().ExprContext ==
6538 ExpressionEvaluationContextRecord::EK_Decltype &&
6539 "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00006540
6541 // C++11 [expr.call]p11:
6542 // If a function call is a prvalue of object type,
6543 // -- if the function call is either
6544 // -- the operand of a decltype-specifier, or
6545 // -- the right operand of a comma operator that is the operand of a
6546 // decltype-specifier,
6547 // a temporary object is not introduced for the prvalue.
6548
6549 // Recursively rebuild ParenExprs and comma expressions to strip out the
6550 // outermost CXXBindTemporaryExpr, if any.
6551 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6552 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6553 if (SubExpr.isInvalid())
6554 return ExprError();
6555 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006556 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006557 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00006558 }
6559 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6560 if (BO->getOpcode() == BO_Comma) {
6561 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6562 if (RHS.isInvalid())
6563 return ExprError();
6564 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006565 return E;
6566 return new (Context) BinaryOperator(
6567 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
Adam Nemet484aa452017-03-27 19:17:25 +00006568 BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
Richard Smithfd555f62012-02-22 02:04:18 +00006569 }
6570 }
6571
6572 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00006573 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6574 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00006575 if (TopCall)
6576 E = TopCall;
6577 else
Craig Topperc3ec1492014-05-26 06:22:03 +00006578 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00006579
6580 // Disable the special decltype handling now.
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006581 ExprEvalContexts.back().ExprContext =
6582 ExpressionEvaluationContextRecord::EK_Other;
Richard Smithfd555f62012-02-22 02:04:18 +00006583
Richard Smithf86b0ae2012-07-28 19:54:11 +00006584 // In MS mode, don't perform any extra checking of call return types within a
6585 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00006586 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006587 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00006588
Richard Smithfd555f62012-02-22 02:04:18 +00006589 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006590 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6591 I != N; ++I) {
6592 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006593 if (Call == TopCall)
6594 continue;
6595
David Majnemerced8bdf2015-02-25 17:36:15 +00006596 if (CheckCallReturnType(Call->getCallReturnType(Context),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006597 Call->getBeginLoc(), Call, Call->getDirectCallee()))
Richard Smithfd555f62012-02-22 02:04:18 +00006598 return ExprError();
6599 }
6600
6601 // Now all relevant types are complete, check the destructors are accessible
6602 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006603 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6604 I != N; ++I) {
6605 CXXBindTemporaryExpr *Bind =
6606 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006607 if (Bind == TopBind)
6608 continue;
6609
6610 CXXTemporary *Temp = Bind->getTemporary();
6611
6612 CXXRecordDecl *RD =
6613 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6614 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6615 Temp->setDestructor(Destructor);
6616
Richard Smith7d847b12012-05-11 22:20:10 +00006617 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6618 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00006619 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00006620 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006621 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6622 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00006623
6624 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006625 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006626 }
6627
6628 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006629 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006630}
6631
Richard Smith79c927b2013-11-06 19:31:51 +00006632/// Note a set of 'operator->' functions that were used for a member access.
6633static void noteOperatorArrows(Sema &S,
Craig Topper00bbdcf2014-06-28 23:22:23 +00006634 ArrayRef<FunctionDecl *> OperatorArrows) {
Richard Smith79c927b2013-11-06 19:31:51 +00006635 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6636 // FIXME: Make this configurable?
6637 unsigned Limit = 9;
6638 if (OperatorArrows.size() > Limit) {
6639 // Produce Limit-1 normal notes and one 'skipping' note.
6640 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6641 SkipCount = OperatorArrows.size() - (Limit - 1);
6642 }
6643
6644 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6645 if (I == SkipStart) {
6646 S.Diag(OperatorArrows[I]->getLocation(),
6647 diag::note_operator_arrows_suppressed)
6648 << SkipCount;
6649 I += SkipCount;
6650 } else {
6651 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6652 << OperatorArrows[I]->getCallResultType();
6653 ++I;
6654 }
6655 }
6656}
6657
Nico Weber964d3322015-02-16 22:35:45 +00006658ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6659 SourceLocation OpLoc,
6660 tok::TokenKind OpKind,
6661 ParsedType &ObjectType,
6662 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006663 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00006664 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00006665 if (Result.isInvalid()) return ExprError();
6666 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00006667
John McCall526ab472011-10-25 17:37:35 +00006668 Result = CheckPlaceholderExpr(Base);
6669 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006670 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00006671
John McCallb268a282010-08-23 23:25:46 +00006672 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00006673 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006674 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00006675 // If we have a pointer to a dependent type and are using the -> operator,
6676 // the object type is the type that the pointer points to. We might still
6677 // have enough information about that type to do something useful.
6678 if (OpKind == tok::arrow)
6679 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6680 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006681
John McCallba7bf592010-08-24 05:47:05 +00006682 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00006683 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006684 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006685 }
Mike Stump11289f42009-09-09 15:08:12 +00006686
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006687 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00006688 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006689 // returned, with the original second operand.
6690 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00006691 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006692 bool NoArrowOperatorFound = false;
6693 bool FirstIteration = true;
6694 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00006695 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00006696 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00006697 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00006698 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006699
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006700 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00006701 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6702 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00006703 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00006704 noteOperatorArrows(*this, OperatorArrows);
6705 Diag(OpLoc, diag::note_operator_arrow_depth)
6706 << getLangOpts().ArrowDepth;
6707 return ExprError();
6708 }
6709
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006710 Result = BuildOverloadedArrowExpr(
6711 S, Base, OpLoc,
6712 // When in a template specialization and on the first loop iteration,
6713 // potentially give the default diagnostic (with the fixit in a
6714 // separate note) instead of having the error reported back to here
6715 // and giving a diagnostic with a fixit attached to the error itself.
6716 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00006717 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006718 : &NoArrowOperatorFound);
6719 if (Result.isInvalid()) {
6720 if (NoArrowOperatorFound) {
6721 if (FirstIteration) {
6722 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00006723 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006724 << FixItHint::CreateReplacement(OpLoc, ".");
6725 OpKind = tok::period;
6726 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006727 }
6728 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6729 << BaseType << Base->getSourceRange();
6730 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00006731 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006732 Diag(CD->getBeginLoc(),
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006733 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006734 }
6735 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006736 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006737 }
John McCallb268a282010-08-23 23:25:46 +00006738 Base = Result.get();
6739 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00006740 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00006741 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00006742 CanQualType CBaseType = Context.getCanonicalType(BaseType);
David Blaikie82e95a32014-11-19 07:49:47 +00006743 if (!CTypes.insert(CBaseType).second) {
Richard Smith79c927b2013-11-06 19:31:51 +00006744 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6745 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00006746 return ExprError();
6747 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006748 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006749 }
Mike Stump11289f42009-09-09 15:08:12 +00006750
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006751 if (OpKind == tok::arrow &&
6752 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
Douglas Gregore4f764f2009-11-20 19:58:21 +00006753 BaseType = BaseType->getPointeeType();
6754 }
Mike Stump11289f42009-09-09 15:08:12 +00006755
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006756 // Objective-C properties allow "." access on Objective-C pointer types,
6757 // so adjust the base type to the object type itself.
6758 if (BaseType->isObjCObjectPointerType())
6759 BaseType = BaseType->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006760
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006761 // C++ [basic.lookup.classref]p2:
6762 // [...] If the type of the object expression is of pointer to scalar
6763 // type, the unqualified-id is looked up in the context of the complete
6764 // postfix-expression.
6765 //
6766 // This also indicates that we could be parsing a pseudo-destructor-name.
6767 // Note that Objective-C class and object types can be pseudo-destructor
John McCall9d145df2015-12-14 19:12:54 +00006768 // expressions or normal member (ivar or property) access expressions, and
6769 // it's legal for the type to be incomplete if this is a pseudo-destructor
6770 // call. We'll do more incomplete-type checks later in the lookup process,
6771 // so just skip this check for ObjC types.
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006772 if (BaseType->isObjCObjectOrInterfaceType()) {
John McCall9d145df2015-12-14 19:12:54 +00006773 ObjectType = ParsedType::make(BaseType);
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006774 MayBePseudoDestructor = true;
John McCall9d145df2015-12-14 19:12:54 +00006775 return Base;
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006776 } else if (!BaseType->isRecordType()) {
David Blaikieefdccaa2016-01-15 23:43:34 +00006777 ObjectType = nullptr;
Douglas Gregore610ada2010-02-24 18:44:31 +00006778 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006779 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006780 }
Mike Stump11289f42009-09-09 15:08:12 +00006781
Douglas Gregor3024f072012-04-16 07:05:22 +00006782 // The object type must be complete (or dependent), or
6783 // C++11 [expr.prim.general]p3:
6784 // Unlike the object expression in other contexts, *this is not required to
Simon Pilgrim75c26882016-09-30 14:25:09 +00006785 // be of complete type for purposes of class member access (5.2.5) outside
Douglas Gregor3024f072012-04-16 07:05:22 +00006786 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00006787 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00006788 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006789 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00006790 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006791
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006792 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006793 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00006794 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006795 // type C (or of pointer to a class type C), the unqualified-id is looked
6796 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00006797 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006798 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006799}
6800
Simon Pilgrim75c26882016-09-30 14:25:09 +00006801static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00006802 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00006803 if (Base->hasPlaceholderType()) {
6804 ExprResult result = S.CheckPlaceholderExpr(Base);
6805 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006806 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00006807 }
6808 ObjectType = Base->getType();
6809
David Blaikie1d578782011-12-16 16:03:09 +00006810 // C++ [expr.pseudo]p2:
6811 // The left-hand side of the dot operator shall be of scalar type. The
6812 // left-hand side of the arrow operator shall be of pointer to scalar type.
6813 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00006814 // Note that this is rather different from the normal handling for the
6815 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00006816 if (OpKind == tok::arrow) {
6817 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6818 ObjectType = Ptr->getPointeeType();
6819 } else if (!Base->isTypeDependent()) {
Nico Webera6916892016-06-10 18:53:04 +00006820 // The user wrote "p->" when they probably meant "p."; fix it.
David Blaikie1d578782011-12-16 16:03:09 +00006821 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6822 << ObjectType << true
6823 << FixItHint::CreateReplacement(OpLoc, ".");
6824 if (S.isSFINAEContext())
6825 return true;
6826
6827 OpKind = tok::period;
6828 }
6829 }
6830
6831 return false;
6832}
6833
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006834/// Check if it's ok to try and recover dot pseudo destructor calls on
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006835/// pointer objects.
6836static bool
6837canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
6838 QualType DestructedType) {
6839 // If this is a record type, check if its destructor is callable.
6840 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
6841 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
6842 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
6843 return false;
6844 }
6845
6846 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
6847 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
6848 DestructedType->isVectorType();
6849}
6850
John McCalldadc5752010-08-24 06:29:42 +00006851ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006852 SourceLocation OpLoc,
6853 tok::TokenKind OpKind,
6854 const CXXScopeSpec &SS,
6855 TypeSourceInfo *ScopeTypeInfo,
6856 SourceLocation CCLoc,
6857 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006858 PseudoDestructorTypeStorage Destructed) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00006859 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006860
Eli Friedman0ce4de42012-01-25 04:35:06 +00006861 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006862 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6863 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006864
Douglas Gregorc5c57342012-09-10 14:57:06 +00006865 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6866 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00006867 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00006868 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006869 else {
Nico Weber58829272012-01-23 05:50:57 +00006870 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6871 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006872 return ExprError();
6873 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006874 }
6875
6876 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006877 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006878 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006879 if (DestructedTypeInfo) {
6880 QualType DestructedType = DestructedTypeInfo->getType();
6881 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006882 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00006883 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6884 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006885 // Detect dot pseudo destructor calls on pointer objects, e.g.:
6886 // Foo *foo;
6887 // foo.~Foo();
6888 if (OpKind == tok::period && ObjectType->isPointerType() &&
6889 Context.hasSameUnqualifiedType(DestructedType,
6890 ObjectType->getPointeeType())) {
6891 auto Diagnostic =
6892 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6893 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006894
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006895 // Issue a fixit only when the destructor is valid.
6896 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
6897 *this, DestructedType))
6898 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
6899
6900 // Recover by setting the object type to the destructed type and the
6901 // operator to '->'.
6902 ObjectType = DestructedType;
6903 OpKind = tok::arrow;
6904 } else {
6905 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6906 << ObjectType << DestructedType << Base->getSourceRange()
6907 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6908
6909 // Recover by setting the destructed type to the object type.
6910 DestructedType = ObjectType;
6911 DestructedTypeInfo =
6912 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
6913 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6914 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006915 } else if (DestructedType.getObjCLifetime() !=
John McCall31168b02011-06-15 23:02:42 +00006916 ObjectType.getObjCLifetime()) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00006917
John McCall31168b02011-06-15 23:02:42 +00006918 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6919 // Okay: just pretend that the user provided the correctly-qualified
6920 // type.
6921 } else {
6922 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6923 << ObjectType << DestructedType << Base->getSourceRange()
6924 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6925 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006926
John McCall31168b02011-06-15 23:02:42 +00006927 // Recover by setting the destructed type to the object type.
6928 DestructedType = ObjectType;
6929 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6930 DestructedTypeStart);
6931 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6932 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00006933 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006934 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006935
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006936 // C++ [expr.pseudo]p2:
6937 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6938 // form
6939 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006940 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006941 //
6942 // shall designate the same scalar type.
6943 if (ScopeTypeInfo) {
6944 QualType ScopeType = ScopeTypeInfo->getType();
6945 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00006946 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006947
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006948 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006949 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00006950 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006951 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006952
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006953 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00006954 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006955 }
6956 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006957
John McCallb268a282010-08-23 23:25:46 +00006958 Expr *Result
6959 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6960 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006961 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00006962 ScopeTypeInfo,
6963 CCLoc,
6964 TildeLoc,
6965 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006966
David Majnemerced8bdf2015-02-25 17:36:15 +00006967 return Result;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006968}
6969
John McCalldadc5752010-08-24 06:29:42 +00006970ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006971 SourceLocation OpLoc,
6972 tok::TokenKind OpKind,
6973 CXXScopeSpec &SS,
6974 UnqualifiedId &FirstTypeName,
6975 SourceLocation CCLoc,
6976 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006977 UnqualifiedId &SecondTypeName) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00006978 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
6979 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006980 "Invalid first type name in pseudo-destructor");
Faisal Vali2ab8c152017-12-30 04:15:27 +00006981 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
6982 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006983 "Invalid second type name in pseudo-destructor");
6984
Eli Friedman0ce4de42012-01-25 04:35:06 +00006985 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006986 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6987 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00006988
6989 // Compute the object type that we should use for name lookup purposes. Only
6990 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00006991 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006992 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00006993 if (ObjectType->isRecordType())
6994 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00006995 else if (ObjectType->isDependentType())
6996 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006997 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006998
6999 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007000 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007001 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00007002 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00007003 PseudoDestructorTypeStorage Destructed;
Faisal Vali2ab8c152017-12-30 04:15:27 +00007004 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007005 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00007006 SecondTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00007007 S, &SS, true, false, ObjectTypePtrForLookup,
7008 /*IsCtorOrDtorName*/true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007009 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00007010 ((SS.isSet() && !computeDeclContext(SS, false)) ||
7011 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007012 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00007013 // couldn't find anything useful in scope. Just store the identifier and
7014 // it's location, and we'll perform (qualified) name lookup again at
7015 // template instantiation time.
7016 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
7017 SecondTypeName.StartLocation);
7018 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007019 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007020 diag::err_pseudo_dtor_destructor_non_type)
7021 << SecondTypeName.Identifier << ObjectType;
7022 if (isSFINAEContext())
7023 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007024
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007025 // Recover by assuming we had the right type all along.
7026 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007027 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007028 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007029 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007030 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007031 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007032 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007033 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00007034 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007035 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00007036 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00007037 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007038 TemplateId->TemplateNameLoc,
7039 TemplateId->LAngleLoc,
7040 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00007041 TemplateId->RAngleLoc,
7042 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007043 if (T.isInvalid() || !T.get()) {
7044 // Recover by assuming we had the right type all along.
7045 DestructedType = ObjectType;
7046 } else
7047 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007048 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007049
7050 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007051 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00007052 if (!DestructedType.isNull()) {
7053 if (!DestructedTypeInfo)
7054 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007055 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00007056 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7057 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007058
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007059 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00007060 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007061 QualType ScopeType;
Faisal Vali2ab8c152017-12-30 04:15:27 +00007062 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007063 FirstTypeName.Identifier) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00007064 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007065 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00007066 FirstTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00007067 S, &SS, true, false, ObjectTypePtrForLookup,
7068 /*IsCtorOrDtorName*/true);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007069 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007070 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007071 diag::err_pseudo_dtor_destructor_non_type)
7072 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007073
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007074 if (isSFINAEContext())
7075 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007076
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007077 // Just drop this type. It's unnecessary anyway.
7078 ScopeType = QualType();
7079 } else
7080 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007081 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007082 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007083 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007084 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007085 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00007086 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007087 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00007088 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00007089 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007090 TemplateId->TemplateNameLoc,
7091 TemplateId->LAngleLoc,
7092 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00007093 TemplateId->RAngleLoc,
7094 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007095 if (T.isInvalid() || !T.get()) {
7096 // Recover by dropping this type.
7097 ScopeType = QualType();
7098 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007099 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007100 }
7101 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007102
Douglas Gregor90ad9222010-02-24 23:02:30 +00007103 if (!ScopeType.isNull() && !ScopeTypeInfo)
7104 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
7105 FirstTypeName.StartLocation);
7106
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007107
John McCallb268a282010-08-23 23:25:46 +00007108 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00007109 ScopeTypeInfo, CCLoc, TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007110 Destructed);
Douglas Gregore610ada2010-02-24 18:44:31 +00007111}
7112
David Blaikie1d578782011-12-16 16:03:09 +00007113ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7114 SourceLocation OpLoc,
7115 tok::TokenKind OpKind,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007116 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007117 const DeclSpec& DS) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00007118 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00007119 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7120 return ExprError();
7121
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00007122 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
7123 false);
David Blaikie1d578782011-12-16 16:03:09 +00007124
7125 TypeLocBuilder TLB;
7126 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
7127 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
7128 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
7129 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
7130
7131 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00007132 nullptr, SourceLocation(), TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007133 Destructed);
David Blaikie1d578782011-12-16 16:03:09 +00007134}
7135
John Wiegley01296292011-04-08 18:41:53 +00007136ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00007137 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007138 bool HadMultipleCandidates) {
Richard Smith7ed5fb22018-07-27 17:13:18 +00007139 // Convert the expression to match the conversion function's implicit object
7140 // parameter.
7141 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
7142 FoundDecl, Method);
7143 if (Exp.isInvalid())
7144 return true;
7145
Eli Friedman98b01ed2012-03-01 04:01:32 +00007146 if (Method->getParent()->isLambda() &&
7147 Method->getConversionType()->isBlockPointerType()) {
7148 // This is a lambda coversion to block pointer; check if the argument
Richard Smith7ed5fb22018-07-27 17:13:18 +00007149 // was a LambdaExpr.
Eli Friedman98b01ed2012-03-01 04:01:32 +00007150 Expr *SubE = E;
7151 CastExpr *CE = dyn_cast<CastExpr>(SubE);
7152 if (CE && CE->getCastKind() == CK_NoOp)
7153 SubE = CE->getSubExpr();
7154 SubE = SubE->IgnoreParens();
7155 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
7156 SubE = BE->getSubExpr();
7157 if (isa<LambdaExpr>(SubE)) {
7158 // For the conversion to block pointer on a lambda expression, we
7159 // construct a special BlockLiteral instead; this doesn't really make
7160 // a difference in ARC, but outside of ARC the resulting block literal
7161 // follows the normal lifetime rules for block literals instead of being
7162 // autoreleased.
7163 DiagnosticErrorTrap Trap(Diags);
Faisal Valid143a0c2017-04-01 21:30:49 +00007164 PushExpressionEvaluationContext(
7165 ExpressionEvaluationContext::PotentiallyEvaluated);
Richard Smith7ed5fb22018-07-27 17:13:18 +00007166 ExprResult BlockExp = BuildBlockForLambdaConversion(
7167 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
Akira Hatanakac482acd2016-05-04 18:07:20 +00007168 PopExpressionEvaluationContext();
7169
Richard Smith7ed5fb22018-07-27 17:13:18 +00007170 if (BlockExp.isInvalid())
7171 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
7172 return BlockExp;
Eli Friedman98b01ed2012-03-01 04:01:32 +00007173 }
7174 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00007175
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00007176 MemberExpr *ME = new (Context) MemberExpr(
7177 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
7178 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007179 if (HadMultipleCandidates)
7180 ME->setHadMultipleCandidates(true);
Nick Lewyckya096b142013-02-12 08:08:54 +00007181 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007182
Alp Toker314cc812014-01-25 16:55:45 +00007183 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00007184 ExprValueKind VK = Expr::getValueKindForType(ResultType);
7185 ResultType = ResultType.getNonLValueExprType(Context);
7186
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007187 CXXMemberCallExpr *CE = new (Context) CXXMemberCallExpr(
7188 Context, ME, None, ResultType, VK, Exp.get()->getEndLoc());
George Burgess IVce6284b2017-01-28 02:19:40 +00007189
7190 if (CheckFunctionCall(Method, CE,
7191 Method->getType()->castAs<FunctionProtoType>()))
7192 return ExprError();
7193
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007194 return CE;
7195}
7196
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007197ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
7198 SourceLocation RParen) {
Aaron Ballmanedc80842015-04-27 22:31:12 +00007199 // If the operand is an unresolved lookup expression, the expression is ill-
7200 // formed per [over.over]p1, because overloaded function names cannot be used
7201 // without arguments except in explicit contexts.
7202 ExprResult R = CheckPlaceholderExpr(Operand);
7203 if (R.isInvalid())
7204 return R;
7205
7206 // The operand may have been modified when checking the placeholder type.
7207 Operand = R.get();
7208
Richard Smith51ec0cf2017-02-21 01:17:38 +00007209 if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00007210 // The expression operand for noexcept is in an unevaluated expression
7211 // context, so side effects could result in unintended consequences.
7212 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7213 }
7214
Richard Smithf623c962012-04-17 00:58:00 +00007215 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007216 return new (Context)
7217 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007218}
7219
7220ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
7221 Expr *Operand, SourceLocation RParen) {
7222 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00007223}
7224
Eli Friedmanf798f652012-05-24 22:04:19 +00007225static bool IsSpecialDiscardedValue(Expr *E) {
7226 // In C++11, discarded-value expressions of a certain form are special,
7227 // according to [expr]p10:
7228 // The lvalue-to-rvalue conversion (4.1) is applied only if the
7229 // expression is an lvalue of volatile-qualified type and it has
7230 // one of the following forms:
7231 E = E->IgnoreParens();
7232
Eli Friedmanc49c2262012-05-24 22:36:31 +00007233 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007234 if (isa<DeclRefExpr>(E))
7235 return true;
7236
Eli Friedmanc49c2262012-05-24 22:36:31 +00007237 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007238 if (isa<ArraySubscriptExpr>(E))
7239 return true;
7240
Eli Friedmanc49c2262012-05-24 22:36:31 +00007241 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007242 if (isa<MemberExpr>(E))
7243 return true;
7244
Eli Friedmanc49c2262012-05-24 22:36:31 +00007245 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007246 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
7247 if (UO->getOpcode() == UO_Deref)
7248 return true;
7249
7250 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00007251 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007252 if (BO->isPtrMemOp())
7253 return true;
7254
Eli Friedmanc49c2262012-05-24 22:36:31 +00007255 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00007256 if (BO->getOpcode() == BO_Comma)
7257 return IsSpecialDiscardedValue(BO->getRHS());
7258 }
7259
Eli Friedmanc49c2262012-05-24 22:36:31 +00007260 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00007261 // operands are one of the above, or
7262 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
7263 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
7264 IsSpecialDiscardedValue(CO->getFalseExpr());
7265 // The related edge case of "*x ?: *x".
7266 if (BinaryConditionalOperator *BCO =
7267 dyn_cast<BinaryConditionalOperator>(E)) {
7268 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
7269 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
7270 IsSpecialDiscardedValue(BCO->getFalseExpr());
7271 }
7272
7273 // Objective-C++ extensions to the rule.
7274 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
7275 return true;
7276
7277 return false;
7278}
7279
John McCall34376a62010-12-04 03:47:34 +00007280/// Perform the conversions required for an expression used in a
7281/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00007282ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00007283 if (E->hasPlaceholderType()) {
7284 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007285 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007286 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00007287 }
7288
John McCallfee942d2010-12-02 02:07:15 +00007289 // C99 6.3.2.1:
7290 // [Except in specific positions,] an lvalue that does not have
7291 // array type is converted to the value stored in the
7292 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00007293 if (E->isRValue()) {
7294 // In C, function designators (i.e. expressions of function type)
7295 // are r-values, but we still want to do function-to-pointer decay
7296 // on them. This is both technically correct and convenient for
7297 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007298 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00007299 return DefaultFunctionArrayConversion(E);
7300
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007301 return E;
John McCalld68b2d02011-06-27 21:24:11 +00007302 }
John McCallfee942d2010-12-02 02:07:15 +00007303
Eli Friedmanf798f652012-05-24 22:04:19 +00007304 if (getLangOpts().CPlusPlus) {
7305 // The C++11 standard defines the notion of a discarded-value expression;
7306 // normally, we don't need to do anything to handle it, but if it is a
7307 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7308 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007309 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmanf798f652012-05-24 22:04:19 +00007310 E->getType().isVolatileQualified() &&
7311 IsSpecialDiscardedValue(E)) {
7312 ExprResult Res = DefaultLvalueConversion(E);
7313 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007314 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007315 E = Res.get();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007316 }
Richard Smith122f88d2016-12-06 23:52:28 +00007317
7318 // C++1z:
7319 // If the expression is a prvalue after this optional conversion, the
7320 // temporary materialization conversion is applied.
7321 //
7322 // We skip this step: IR generation is able to synthesize the storage for
7323 // itself in the aggregate case, and adding the extra node to the AST is
7324 // just clutter.
7325 // FIXME: We don't emit lifetime markers for the temporaries due to this.
7326 // FIXME: Do any other AST consumers care about this?
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007327 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00007328 }
John McCall34376a62010-12-04 03:47:34 +00007329
7330 // GCC seems to also exclude expressions of incomplete enum type.
7331 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
7332 if (!T->getDecl()->isComplete()) {
7333 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007334 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007335 return E;
John McCall34376a62010-12-04 03:47:34 +00007336 }
7337 }
7338
John Wiegley01296292011-04-08 18:41:53 +00007339 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
7340 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007341 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007342 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00007343
John McCallca61b652010-12-04 12:29:11 +00007344 if (!E->getType()->isVoidType())
7345 RequireCompleteType(E->getExprLoc(), E->getType(),
7346 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007347 return E;
John McCall34376a62010-12-04 03:47:34 +00007348}
7349
Faisal Valia17d19f2013-11-07 05:17:06 +00007350// If we can unambiguously determine whether Var can never be used
7351// in a constant expression, return true.
7352// - if the variable and its initializer are non-dependent, then
7353// we can unambiguously check if the variable is a constant expression.
7354// - if the initializer is not value dependent - we can determine whether
7355// it can be used to initialize a constant expression. If Init can not
Simon Pilgrim75c26882016-09-30 14:25:09 +00007356// be used to initialize a constant expression we conclude that Var can
Faisal Valia17d19f2013-11-07 05:17:06 +00007357// never be a constant expression.
7358// - FXIME: if the initializer is dependent, we can still do some analysis and
7359// identify certain cases unambiguously as non-const by using a Visitor:
7360// - such as those that involve odr-use of a ParmVarDecl, involve a new
7361// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
Simon Pilgrim75c26882016-09-30 14:25:09 +00007362static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
Faisal Valia17d19f2013-11-07 05:17:06 +00007363 ASTContext &Context) {
7364 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007365 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007366
7367 // If there is no initializer - this can not be a constant expression.
7368 if (!Var->getAnyInitializer(DefVD)) return true;
7369 assert(DefVD);
7370 if (DefVD->isWeak()) return false;
7371 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00007372
Faisal Valia17d19f2013-11-07 05:17:06 +00007373 Expr *Init = cast<Expr>(Eval->Value);
7374
7375 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00007376 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7377 // of value-dependent expressions, and use it here to determine whether the
7378 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007379 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00007380 }
7381
Simon Pilgrim75c26882016-09-30 14:25:09 +00007382 return !IsVariableAConstantExpression(Var, Context);
Faisal Valia17d19f2013-11-07 05:17:06 +00007383}
7384
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007385/// Check if the current lambda has any potential captures
Simon Pilgrim75c26882016-09-30 14:25:09 +00007386/// that must be captured by any of its enclosing lambdas that are ready to
7387/// capture. If there is a lambda that can capture a nested
7388/// potential-capture, go ahead and do so. Also, check to see if any
7389/// variables are uncaptureable or do not involve an odr-use so do not
Faisal Valiab3d6462013-12-07 20:22:44 +00007390/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007391
Faisal Valiab3d6462013-12-07 20:22:44 +00007392static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7393 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7394
Simon Pilgrim75c26882016-09-30 14:25:09 +00007395 assert(!S.isUnevaluatedContext());
7396 assert(S.CurContext->isDependentContext());
Alexey Bataev31939e32016-11-11 12:36:20 +00007397#ifndef NDEBUG
7398 DeclContext *DC = S.CurContext;
7399 while (DC && isa<CapturedDecl>(DC))
7400 DC = DC->getParent();
7401 assert(
7402 CurrentLSI->CallOperator == DC &&
Faisal Valiab3d6462013-12-07 20:22:44 +00007403 "The current call operator must be synchronized with Sema's CurContext");
Alexey Bataev31939e32016-11-11 12:36:20 +00007404#endif // NDEBUG
Faisal Valiab3d6462013-12-07 20:22:44 +00007405
7406 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7407
Faisal Valiab3d6462013-12-07 20:22:44 +00007408 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00007409 // lambda (within a generic outer lambda), must be captured by an
7410 // outer lambda that is enclosed within a non-dependent context.
Faisal Valiab3d6462013-12-07 20:22:44 +00007411 const unsigned NumPotentialCaptures =
7412 CurrentLSI->getNumPotentialVariableCaptures();
7413 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007414 Expr *VarExpr = nullptr;
7415 VarDecl *Var = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007416 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
Faisal Valiab3d6462013-12-07 20:22:44 +00007417 // If the variable is clearly identified as non-odr-used and the full
Simon Pilgrim75c26882016-09-30 14:25:09 +00007418 // expression is not instantiation dependent, only then do we not
Faisal Valiab3d6462013-12-07 20:22:44 +00007419 // need to check enclosing lambda's for speculative captures.
7420 // For e.g.:
7421 // Even though 'x' is not odr-used, it should be captured.
7422 // int test() {
7423 // const int x = 10;
7424 // auto L = [=](auto a) {
7425 // (void) +x + a;
7426 // };
7427 // }
7428 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00007429 !IsFullExprInstantiationDependent)
Faisal Valiab3d6462013-12-07 20:22:44 +00007430 continue;
7431
7432 // If we have a capture-capable lambda for the variable, go ahead and
7433 // capture the variable in that lambda (and all its enclosing lambdas).
7434 if (const Optional<unsigned> Index =
7435 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Reid Kleckner87a31802018-03-12 21:43:02 +00007436 S.FunctionScopes, Var, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007437 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7438 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
7439 &FunctionScopeIndexOfCapturableLambda);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007440 }
7441 const bool IsVarNeverAConstantExpression =
Faisal Valia17d19f2013-11-07 05:17:06 +00007442 VariableCanNeverBeAConstantExpression(Var, S.Context);
7443 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7444 // This full expression is not instantiation dependent or the variable
Simon Pilgrim75c26882016-09-30 14:25:09 +00007445 // can not be used in a constant expression - which means
7446 // this variable must be odr-used here, so diagnose a
Faisal Valia17d19f2013-11-07 05:17:06 +00007447 // capture violation early, if the variable is un-captureable.
7448 // This is purely for diagnosing errors early. Otherwise, this
7449 // error would get diagnosed when the lambda becomes capture ready.
7450 QualType CaptureType, DeclRefType;
7451 SourceLocation ExprLoc = VarExpr->getExprLoc();
7452 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007453 /*EllipsisLoc*/ SourceLocation(),
7454 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007455 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00007456 // We will never be able to capture this variable, and we need
7457 // to be able to in any and all instantiations, so diagnose it.
7458 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007459 /*EllipsisLoc*/ SourceLocation(),
7460 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007461 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007462 }
7463 }
7464 }
7465
Faisal Valiab3d6462013-12-07 20:22:44 +00007466 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007467 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007468 // If we have a capture-capable lambda for 'this', go ahead and capture
7469 // 'this' in that lambda (and all its enclosing lambdas).
7470 if (const Optional<unsigned> Index =
7471 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Reid Kleckner87a31802018-03-12 21:43:02 +00007472 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007473 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7474 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7475 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7476 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00007477 }
7478 }
Faisal Valiab3d6462013-12-07 20:22:44 +00007479
7480 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007481 CurrentLSI->clearPotentialCaptures();
7482}
7483
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007484static ExprResult attemptRecovery(Sema &SemaRef,
7485 const TypoCorrectionConsumer &Consumer,
Benjamin Kramer7320b992016-06-15 14:20:56 +00007486 const TypoCorrection &TC) {
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007487 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7488 Consumer.getLookupResult().getLookupKind());
7489 const CXXScopeSpec *SS = Consumer.getSS();
7490 CXXScopeSpec NewSS;
7491
7492 // Use an approprate CXXScopeSpec for building the expr.
7493 if (auto *NNS = TC.getCorrectionSpecifier())
7494 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7495 else if (SS && !TC.WillReplaceSpecifier())
7496 NewSS = *SS;
7497
Richard Smithde6d6c42015-12-29 19:43:10 +00007498 if (auto *ND = TC.getFoundDecl()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007499 R.setLookupName(ND->getDeclName());
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007500 R.addDecl(ND);
7501 if (ND->isCXXClassMember()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007502 // Figure out the correct naming class to add to the LookupResult.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007503 CXXRecordDecl *Record = nullptr;
7504 if (auto *NNS = TC.getCorrectionSpecifier())
7505 Record = NNS->getAsType()->getAsCXXRecordDecl();
7506 if (!Record)
Olivier Goffarted13fab2015-01-09 09:37:26 +00007507 Record =
7508 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7509 if (Record)
7510 R.setNamingClass(Record);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007511
7512 // Detect and handle the case where the decl might be an implicit
7513 // member.
7514 bool MightBeImplicitMember;
7515 if (!Consumer.isAddressOfOperand())
7516 MightBeImplicitMember = true;
7517 else if (!NewSS.isEmpty())
7518 MightBeImplicitMember = false;
7519 else if (R.isOverloadedResult())
7520 MightBeImplicitMember = false;
7521 else if (R.isUnresolvableResult())
7522 MightBeImplicitMember = true;
7523 else
7524 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7525 isa<IndirectFieldDecl>(ND) ||
7526 isa<MSPropertyDecl>(ND);
7527
7528 if (MightBeImplicitMember)
7529 return SemaRef.BuildPossibleImplicitMemberExpr(
7530 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00007531 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007532 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7533 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7534 Ivar->getIdentifier());
7535 }
7536 }
7537
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00007538 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7539 /*AcceptInvalidDecl*/ true);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007540}
7541
Kaelyn Takata6c759512014-10-27 18:07:37 +00007542namespace {
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007543class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7544 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7545
7546public:
7547 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7548 : TypoExprs(TypoExprs) {}
7549 bool VisitTypoExpr(TypoExpr *TE) {
7550 TypoExprs.insert(TE);
7551 return true;
7552 }
7553};
7554
Kaelyn Takata6c759512014-10-27 18:07:37 +00007555class TransformTypos : public TreeTransform<TransformTypos> {
7556 typedef TreeTransform<TransformTypos> BaseTransform;
7557
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007558 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7559 // process of being initialized.
Kaelyn Takata49d84322014-11-11 23:26:56 +00007560 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007561 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007562 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007563 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007564
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007565 /// Emit diagnostics for all of the TypoExprs encountered.
Kaelyn Takata6c759512014-10-27 18:07:37 +00007566 /// If the TypoExprs were successfully corrected, then the diagnostics should
7567 /// suggest the corrections. Otherwise the diagnostics will not suggest
7568 /// anything (having been passed an empty TypoCorrection).
7569 void EmitAllDiagnostics() {
George Burgess IV00f70bd2018-03-01 05:43:23 +00007570 for (TypoExpr *TE : TypoExprs) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00007571 auto &State = SemaRef.getTypoExprState(TE);
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007572 if (State.DiagHandler) {
7573 TypoCorrection TC = State.Consumer->getCurrentCorrection();
7574 ExprResult Replacement = TransformCache[TE];
7575
7576 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7577 // TypoCorrection, replacing the existing decls. This ensures the right
7578 // NamedDecl is used in diagnostics e.g. in the case where overload
7579 // resolution was used to select one from several possible decls that
7580 // had been stored in the TypoCorrection.
7581 if (auto *ND = getDeclFromExpr(
7582 Replacement.isInvalid() ? nullptr : Replacement.get()))
7583 TC.setCorrectionDecl(ND);
7584
7585 State.DiagHandler(TC);
7586 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007587 SemaRef.clearDelayedTypo(TE);
7588 }
7589 }
7590
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007591 /// If corrections for the first TypoExpr have been exhausted for a
Kaelyn Takata6c759512014-10-27 18:07:37 +00007592 /// given combination of the other TypoExprs, retry those corrections against
7593 /// the next combination of substitutions for the other TypoExprs by advancing
7594 /// to the next potential correction of the second TypoExpr. For the second
7595 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7596 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7597 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7598 /// TransformCache). Returns true if there is still any untried combinations
7599 /// of corrections.
7600 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7601 for (auto TE : TypoExprs) {
7602 auto &State = SemaRef.getTypoExprState(TE);
7603 TransformCache.erase(TE);
7604 if (!State.Consumer->finished())
7605 return true;
7606 State.Consumer->resetCorrectionStream();
7607 }
7608 return false;
7609 }
7610
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007611 NamedDecl *getDeclFromExpr(Expr *E) {
7612 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7613 E = OverloadResolution[OE];
7614
7615 if (!E)
7616 return nullptr;
7617 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007618 return DRE->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007619 if (auto *ME = dyn_cast<MemberExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007620 return ME->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007621 // FIXME: Add any other expr types that could be be seen by the delayed typo
7622 // correction TreeTransform for which the corresponding TypoCorrection could
Nick Lewycky39f9dbc2014-12-16 21:48:39 +00007623 // contain multiple decls.
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007624 return nullptr;
7625 }
7626
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007627 ExprResult TryTransform(Expr *E) {
7628 Sema::SFINAETrap Trap(SemaRef);
7629 ExprResult Res = TransformExpr(E);
7630 if (Trap.hasErrorOccurred() || Res.isInvalid())
7631 return ExprError();
7632
7633 return ExprFilter(Res.get());
7634 }
7635
Kaelyn Takata6c759512014-10-27 18:07:37 +00007636public:
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007637 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7638 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
Kaelyn Takata6c759512014-10-27 18:07:37 +00007639
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007640 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7641 MultiExprArg Args,
7642 SourceLocation RParenLoc,
7643 Expr *ExecConfig = nullptr) {
7644 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7645 RParenLoc, ExecConfig);
7646 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
Reid Klecknera9e65ba2014-12-13 01:11:23 +00007647 if (Result.isUsable()) {
Reid Klecknera7fe33e2014-12-13 00:53:10 +00007648 Expr *ResultCall = Result.get();
7649 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7650 ResultCall = BE->getSubExpr();
7651 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7652 OverloadResolution[OE] = CE->getCallee();
7653 }
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007654 }
7655 return Result;
7656 }
7657
Kaelyn Takata6c759512014-10-27 18:07:37 +00007658 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7659
Saleem Abdulrasoola1742412015-10-31 00:39:15 +00007660 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7661
Kaelyn Takata6c759512014-10-27 18:07:37 +00007662 ExprResult Transform(Expr *E) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007663 ExprResult Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007664 while (true) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007665 Res = TryTransform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007666
Kaelyn Takata6c759512014-10-27 18:07:37 +00007667 // Exit if either the transform was valid or if there were no TypoExprs
7668 // to transform that still have any untried correction candidates..
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007669 if (!Res.isInvalid() ||
Kaelyn Takata6c759512014-10-27 18:07:37 +00007670 !CheckAndAdvanceTypoExprCorrectionStreams())
7671 break;
7672 }
7673
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007674 // Ensure none of the TypoExprs have multiple typo correction candidates
7675 // with the same edit length that pass all the checks and filters.
7676 // TODO: Properly handle various permutations of possible corrections when
7677 // there is more than one potentially ambiguous typo correction.
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007678 // Also, disable typo correction while attempting the transform when
7679 // handling potentially ambiguous typo corrections as any new TypoExprs will
7680 // have been introduced by the application of one of the correction
7681 // candidates and add little to no value if corrected.
7682 SemaRef.DisableTypoCorrection = true;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007683 while (!AmbiguousTypoExprs.empty()) {
7684 auto TE = AmbiguousTypoExprs.back();
7685 auto Cached = TransformCache[TE];
Kaelyn Takata7a503692015-01-27 22:01:39 +00007686 auto &State = SemaRef.getTypoExprState(TE);
7687 State.Consumer->saveCurrentPosition();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007688 TransformCache.erase(TE);
7689 if (!TryTransform(E).isInvalid()) {
Kaelyn Takata7a503692015-01-27 22:01:39 +00007690 State.Consumer->resetCorrectionStream();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007691 TransformCache.erase(TE);
7692 Res = ExprError();
7693 break;
Kaelyn Takata7a503692015-01-27 22:01:39 +00007694 }
7695 AmbiguousTypoExprs.remove(TE);
7696 State.Consumer->restoreSavedPosition();
7697 TransformCache[TE] = Cached;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007698 }
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007699 SemaRef.DisableTypoCorrection = false;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007700
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007701 // Ensure that all of the TypoExprs within the current Expr have been found.
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007702 if (!Res.isUsable())
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007703 FindTypoExprs(TypoExprs).TraverseStmt(E);
7704
Kaelyn Takata6c759512014-10-27 18:07:37 +00007705 EmitAllDiagnostics();
7706
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007707 return Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007708 }
7709
7710 ExprResult TransformTypoExpr(TypoExpr *E) {
7711 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7712 // cached transformation result if there is one and the TypoExpr isn't the
7713 // first one that was encountered.
7714 auto &CacheEntry = TransformCache[E];
7715 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7716 return CacheEntry;
7717 }
7718
7719 auto &State = SemaRef.getTypoExprState(E);
7720 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7721
7722 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7723 // typo correction and return it.
7724 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00007725 if (InitDecl && TC.getFoundDecl() == InitDecl)
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007726 continue;
Richard Smith1cf45412017-01-04 23:14:16 +00007727 // FIXME: If we would typo-correct to an invalid declaration, it's
7728 // probably best to just suppress all errors from this typo correction.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007729 ExprResult NE = State.RecoveryHandler ?
7730 State.RecoveryHandler(SemaRef, E, TC) :
7731 attemptRecovery(SemaRef, *State.Consumer, TC);
7732 if (!NE.isInvalid()) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007733 // Check whether there may be a second viable correction with the same
7734 // edit distance; if so, remember this TypoExpr may have an ambiguous
7735 // correction so it can be more thoroughly vetted later.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007736 TypoCorrection Next;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007737 if ((Next = State.Consumer->peekNextCorrection()) &&
7738 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7739 AmbiguousTypoExprs.insert(E);
7740 } else {
7741 AmbiguousTypoExprs.remove(E);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007742 }
7743 assert(!NE.isUnset() &&
7744 "Typo was transformed into a valid-but-null ExprResult");
Kaelyn Takata6c759512014-10-27 18:07:37 +00007745 return CacheEntry = NE;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007746 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007747 }
7748 return CacheEntry = ExprError();
7749 }
7750};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007751}
Faisal Valia17d19f2013-11-07 05:17:06 +00007752
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007753ExprResult
7754Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7755 llvm::function_ref<ExprResult(Expr *)> Filter) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007756 // If the current evaluation context indicates there are uncorrected typos
7757 // and the current expression isn't guaranteed to not have typos, try to
7758 // resolve any TypoExpr nodes that might be in the expression.
Kaelyn Takatac71dda22014-12-02 22:05:35 +00007759 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
Kaelyn Takata49d84322014-11-11 23:26:56 +00007760 (E->isTypeDependent() || E->isValueDependent() ||
7761 E->isInstantiationDependent())) {
7762 auto TyposResolved = DelayedTypos.size();
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007763 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007764 TyposResolved -= DelayedTypos.size();
Nick Lewycky4d59b772014-12-16 22:02:06 +00007765 if (Result.isInvalid() || Result.get() != E) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007766 ExprEvalContexts.back().NumTypos -= TyposResolved;
7767 return Result;
7768 }
Nick Lewycky4d59b772014-12-16 22:02:06 +00007769 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
Kaelyn Takata49d84322014-11-11 23:26:56 +00007770 }
7771 return E;
7772}
7773
Richard Smith945f8d32013-01-14 22:39:08 +00007774ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007775 bool DiscardedValue,
Richard Smithb3d203f2018-10-19 19:01:34 +00007776 bool IsConstexpr) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007777 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00007778
7779 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00007780 return ExprError();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007781
Richard Smithb3d203f2018-10-19 19:01:34 +00007782 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00007783 return ExprError();
7784
Richard Smith945f8d32013-01-14 22:39:08 +00007785 if (DiscardedValue) {
Richard Smithb3d203f2018-10-19 19:01:34 +00007786 // Top-level expressions default to 'id' when we're in a debugger.
7787 if (getLangOpts().DebuggerCastResultToId &&
7788 FullExpr.get()->getType() == Context.UnknownAnyTy) {
7789 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
7790 if (FullExpr.isInvalid())
7791 return ExprError();
7792 }
7793
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007794 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007795 if (FullExpr.isInvalid())
7796 return ExprError();
7797
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007798 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007799 if (FullExpr.isInvalid())
7800 return ExprError();
7801 }
John Wiegley01296292011-04-08 18:41:53 +00007802
Kaelyn Takata49d84322014-11-11 23:26:56 +00007803 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7804 if (FullExpr.isInvalid())
7805 return ExprError();
Kaelyn Takata6c759512014-10-27 18:07:37 +00007806
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007807 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007808
Simon Pilgrim75c26882016-09-30 14:25:09 +00007809 // At the end of this full expression (which could be a deeply nested
7810 // lambda), if there is a potential capture within the nested lambda,
Faisal Vali218e94b2013-11-12 03:56:08 +00007811 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00007812 // Consider the following code:
7813 // void f(int, int);
7814 // void f(const int&, double);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007815 // void foo() {
Faisal Valia17d19f2013-11-07 05:17:06 +00007816 // const int x = 10, y = 20;
7817 // auto L = [=](auto a) {
7818 // auto M = [=](auto b) {
7819 // f(x, b); <-- requires x to be captured by L and M
7820 // f(y, a); <-- requires y to be captured by L, but not all Ms
7821 // };
7822 // };
7823 // }
7824
Simon Pilgrim75c26882016-09-30 14:25:09 +00007825 // FIXME: Also consider what happens for something like this that involves
7826 // the gnu-extension statement-expressions or even lambda-init-captures:
Faisal Valia17d19f2013-11-07 05:17:06 +00007827 // void f() {
7828 // const int n = 0;
7829 // auto L = [&](auto a) {
7830 // +n + ({ 0; a; });
7831 // };
7832 // }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007833 //
7834 // Here, we see +n, and then the full-expression 0; ends, so we don't
7835 // capture n (and instead remove it from our list of potential captures),
7836 // and then the full-expression +n + ({ 0; }); ends, but it's too late
Faisal Vali218e94b2013-11-12 03:56:08 +00007837 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00007838
Alexey Bataev31939e32016-11-11 12:36:20 +00007839 LambdaScopeInfo *const CurrentLSI =
7840 getCurLambda(/*IgnoreCapturedRegions=*/true);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007841 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007842 // even if CurContext is not a lambda call operator. Refer to that Bug Report
Simon Pilgrim75c26882016-09-30 14:25:09 +00007843 // for an example of the code that might cause this asynchrony.
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007844 // By ensuring we are in the context of a lambda's call operator
7845 // we can fix the bug (we only need to check whether we need to capture
Simon Pilgrim75c26882016-09-30 14:25:09 +00007846 // if we are within a lambda's body); but per the comments in that
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007847 // PR, a proper fix would entail :
7848 // "Alternative suggestion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00007849 // - Add to Sema an integer holding the smallest (outermost) scope
7850 // index that we are *lexically* within, and save/restore/set to
7851 // FunctionScopes.size() in InstantiatingTemplate's
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007852 // constructor/destructor.
Simon Pilgrim75c26882016-09-30 14:25:09 +00007853 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00007854 // stop at the outermost enclosing lexical scope."
Alexey Bataev31939e32016-11-11 12:36:20 +00007855 DeclContext *DC = CurContext;
7856 while (DC && isa<CapturedDecl>(DC))
7857 DC = DC->getParent();
7858 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
Faisal Valiab3d6462013-12-07 20:22:44 +00007859 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007860 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00007861 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7862 *this);
John McCall5d413782010-12-06 08:20:24 +00007863 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00007864}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007865
7866StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7867 if (!FullStmt) return StmtError();
7868
John McCall5d413782010-12-06 08:20:24 +00007869 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007870}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007871
Simon Pilgrim75c26882016-09-30 14:25:09 +00007872Sema::IfExistsResult
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007873Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7874 CXXScopeSpec &SS,
7875 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007876 DeclarationName TargetName = TargetNameInfo.getName();
7877 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00007878 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007879
Douglas Gregor43edb322011-10-24 22:31:10 +00007880 // If the name itself is dependent, then the result is dependent.
7881 if (TargetName.isDependentName())
7882 return IER_Dependent;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007883
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007884 // Do the redeclaration lookup in the current scope.
7885 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7886 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00007887 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007888 R.suppressDiagnostics();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007889
Douglas Gregor43edb322011-10-24 22:31:10 +00007890 switch (R.getResultKind()) {
7891 case LookupResult::Found:
7892 case LookupResult::FoundOverloaded:
7893 case LookupResult::FoundUnresolvedValue:
7894 case LookupResult::Ambiguous:
7895 return IER_Exists;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007896
Douglas Gregor43edb322011-10-24 22:31:10 +00007897 case LookupResult::NotFound:
7898 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007899
Douglas Gregor43edb322011-10-24 22:31:10 +00007900 case LookupResult::NotFoundInCurrentInstantiation:
7901 return IER_Dependent;
7902 }
David Blaikie8a40f702012-01-17 06:56:22 +00007903
7904 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007905}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007906
Simon Pilgrim75c26882016-09-30 14:25:09 +00007907Sema::IfExistsResult
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007908Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7909 bool IsIfExists, CXXScopeSpec &SS,
7910 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007911 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007912
Richard Smith151c4562016-12-20 21:35:28 +00007913 // Check for an unexpanded parameter pack.
7914 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7915 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7916 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007917 return IER_Error;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007918
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007919 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7920}